如何使用谷歌地图位置搜索框api从搜索到的位置获取经度和纬度。
我使用与谷歌演示相同的代码-https://developers.google.com/maps/documentation/javascript/examples/places-searchbox
function GetLatlong() {
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('textboxid').value;
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
}
});
}
您可以使用上面的函数,它会给出用户输入的区域的纬度和经度。
您提供的链接上的代码显示了输入搜索时要执行的功能。首先,它创建一个空的标记数组(执行搜索后在地图上看到的大头针)。
因此,检查以以下内容开头的函数:
google.maps.event.add监听器(搜索框,places_changed,函数){
稍后你会看到已经创建了一个标记(甚至还有注释):
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
因此,在place.geometry.location
上,您有一个Google Maps Location对象。您可以使用place.geometry.location.lat()和place.geometry.location.lng()。
也在这里查看:https://stackoverflow.com/a/15315483/1012139
来自文档:
// Autocomplete Options
var defaultBounds = new google.maps.LatLngBounds();
var options = {
types: ['(cities)'],
bounds: defaultBounds
};
// get DOM's input element
var input = document.getElementById('location_address');
// Make Autocomplete instance
var autocomplete = new google.maps.places.Autocomplete(input, options);
// Listener for whenever input value changes
autocomplete.addListener('place_changed', function() {
// Get place info
var place = autocomplete.getPlace();
// Do whatever with the value!
console.log(place.geometry.location.lat());
});