我想实现一个功能,人们将能够改变他们的位置。为此,我想使用google places api。现在我想要的是一个搜索框,当有人输入一个城镇/地方时,它会搜索谷歌地点并给出结果。一旦位置被选择,它会给我那个地方的lat和lng。没有地图也行吗?
谢谢
发布于 2017-10-05 21:48:16
您可以使用Google Maps Places Autocomplete来获取准确的地址,然后在成功获取地址之后,可以对其进行地理编码以获取lat和lng。
如下所示:
function codeAddress(address) {
geocoder.geocode({ 'address': address}, function(results, status) {
if (status == 'OK') {
alert(results[0].geometry.location); // This is the lat and lng
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
检查下面的工作示例:https://jsbin.com/pejagub/edit?html,js,output
我还在这里插入了代码片段,以防jsbin无法工作。
var placeSearch, autocomplete, geocoder;
function initAutocomplete() {
geocoder = new google.maps.Geocoder();
autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')), {
types: ['geocode']
});
autocomplete.addListener('place_changed', fillInAddress);
}
function codeAddress(address) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == 'OK') {
// This is the lat and lng results[0].geometry.location
alert(results[0].geometry.location);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function fillInAddress() {
var place = autocomplete.getPlace();
codeAddress(document.getElementById('autocomplete').value);
}
#autocomplete {
width: 100%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="locationField">
<input id="autocomplete" placeholder="Enter your address" type="text" />
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCKQX3cyZ7pVKmBwE8wiowivW9qH62AVk8&libraries=places&callback=initAutocomplete" async defer></script>
</body>
</html>
发布于 2018-08-16 23:30:31
抱歉来迟了。你可以在这里找到你的答案:
https://developers.google.com/maps/documentation/javascript/places-autocomplete#video
```javascript
Google.maps.LatLngBounds defaultBounds =新的var (
新google.maps.LatLng(-33.8902,151.1759),
新的google.maps.LatLng(-33.8474,151.2631);
var输入= document.getElementById('searchTextField');
var searchBox =新输入(google.maps.places.SearchBox,{
边界: defaultBounds
});
不需要映射对象引用,只需传递边界即可。
https://stackoverflow.com/questions/46585692
复制相似问题