【发布时间】:2017-10-05 12:30:25
【问题描述】:
我想实现一个功能,人们可以改变他们的位置。为此,我想使用 google places api。现在我想要的是一个搜索框,当有人输入城镇/地点时,它会搜索谷歌地点并得出结果。一旦选择了位置,它就会给我那个地方的纬度和经度。没有地图也可以吗?
谢谢
【问题讨论】:
标签: google-maps google-maps-api-3 google-places-api
我想实现一个功能,人们可以改变他们的位置。为此,我想使用 google places api。现在我想要的是一个搜索框,当有人输入城镇/地点时,它会搜索谷歌地点并得出结果。一旦选择了位置,它就会给我那个地方的纬度和经度。没有地图也可以吗?
谢谢
【问题讨论】:
标签: google-maps google-maps-api-3 google-places-api
您可以使用 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
我还在这里插入了代码 sn-p 以防 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>
【讨论】:
抱歉迟到了。您可以在这里找到答案:
https://developers.google.com/maps/documentation/javascript/places-autocomplete#video
```
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
var input = document.getElementById('searchTextField');
var searchBox = new google.maps.places.SearchBox(input, {
bounds: defaultBounds
});
```
无需地图对象引用,只需通过边界即可。
【讨论】: