如何获得用户搜索的长拉特?我已经设置了这个 jsfiddle,除了第一次搜索之外,一切正常,当人们搜索“纽约”时,他们会在 map 上看到一个标记,当他们拖动标记时,我会得到长纬度,但是,我怎样才能得到最初搜索时的长拉特?
https://jsfiddle.net/x1a9z5t5/
function init() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {
lat: 40.730610,
lng: -73.935242
},
zoom: 12
});
var searchBox = new google.maps.places.SearchBox(document.getElementById('adress-input'));
map.controls[google.maps.ControlPosition.TOP_CENTER].push(document.getElementById('adress-input'));
google.maps.event.addListener(searchBox, 'places_changed', function() {
searchBox.set('map', null);
var places = searchBox.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i, place;
for (i = 0; place = places[i]; i++) {
(function(place) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(40.730610, -73.935242),
draggable: true,
position: place.geometry.location
});
marker.bindTo('map', searchBox, 'map');
google.maps.event.addListener(marker, 'map_changed', function() {
if (!this.getMap()) {
this.unbindAll();
}
});
bounds.extend(place.geometry.location);
google.maps.event.addListener(marker, 'dragend', function(evt) {
document.getElementById('long-lat').innerHTML = evt.latLng.lat().toFixed(3) + " " + evt.latLng.lng().toFixed(3);
});
}(place));
}
map.fitBounds(bounds);
searchBox.set('map', map);
map.setZoom(Math.min(map.getZoom(), 12));
});
}
google.maps.event.addDomListener(window, 'load', init);
最佳答案
尝试创建一个新的监听器,例如 map.addListener('bounds_changed')
因为 google.maps.event.addListener(marker, 'dragend'
将在拖动标记后监听。
我已将其添加到您的 jsfiddle 中:
map.addListener('bounds_changed', function(e) {
console.log(place.geometry.location.lat())
document.getElementById('long-lat').innerHTML = place.geometry.location.lat().toFixed(3) + " " + place.geometry.location.lng().toFixed(3);
});
搜索后的结果:
拖动后的结果:
希望这有帮助。
关于javascript - 从谷歌地图 API 中的搜索框获取长纬度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43324084/