Prz*_*tas 0 google-maps google-maps-api-3 google-places-api
我想实现一个人们可以改变他们位置的功能.为此我想使用google places api.现在我想要的是一个搜索框,当有人输入一个城镇/地方时,它将搜索谷歌的地方并得出结果.一旦选择了位置,它将给我拉特和那个地方.没有地图可以吗?
谢谢
您可以使用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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
请查看此工作示例: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);
}Run Code Online (Sandbox Code Playgroud)
#autocomplete {
width: 100%;
}Run Code Online (Sandbox Code Playgroud)
<!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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5298 次 |
| 最近记录: |