-1
我想實現一個功能,人們可以改變他們的位置。爲此,我想使用谷歌地方API。現在我想要的是一個搜索框,當有人輸入一個城鎮/地點時,它會搜索谷歌地點並獲得結果。一旦選擇了位置,它會給我那個地方的經度和緯度。沒有地圖可以做到嗎?谷歌放置搜索框沒有地圖?
感謝
我想實現一個功能,人們可以改變他們的位置。爲此,我想使用谷歌地方API。現在我想要的是一個搜索框,當有人輸入一個城鎮/地點時,它會搜索谷歌地點並獲得結果。一旦選擇了位置,它會給我那個地方的經度和緯度。沒有地圖可以做到嗎?谷歌放置搜索框沒有地圖?
感謝
您可以使用谷歌地圖商家信息自動填充得到一個準確的地址,然後在成功讓你可以進行地址解析它來獲得緯度和經度的地址。
像這樣:
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>