我想实现一个人们可以更改位置的功能。为此我想使用google places api。现在我想要的是一个搜索框,当有人输入一个城镇/地方时,它会搜索谷歌的地方并得出结果。一旦选择了位置,它将给我拉特和那个地方。没有地图可以吗?
感谢
答案 0 :(得分:5)
您可以使用Google地图位置自动填充功能获取准确的地址,然后在成功获取地址后,您可以对其进行地理编码以获取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>
&#13;
答案 1 :(得分:0)
很抱歉迟到了。您可以在这里找到答案:
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
});
```
不需要引用地图对象就可以通过边界。