我有一个输入字段,用户输入地址。 Google Maps API自动填充它,然后重新定位地图标记,并将地图移动到该位置。
var map_location = new google.maps.LatLng(45.815015, 15.981912);
var marker;
var map;
var autocomplete;
function initialize() {
var mapOptions = {
zoom: 13,
center: map_location
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
marker = new google.maps.Marker({
map: map,
draggable: true,
position: map_location
});
google.maps.event.addListener(marker, 'dragend', function (event) {
document.getElementById("lat_hidden").value = this.getPosition().lat();
document.getElementById("long_hidden").value = this.getPosition().lng();
});
autocomplete = new google.maps.places.Autocomplete(
document.getElementById('autocomplete'),
{types: ['geocode']});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
map_location = new google.maps.LatLng(
parseFloat(document.getElementById("lat_hidden").value),
parseFloat(document.getElementById("long_hidden").value)
);
marker.setPosition(map_location);
map.panTo(map_location);
});
}
最后一行代码导致无限递归。我也试过了.setCenter
。 Firefox追踪到maps.gstatic.com脚本的递归,该脚本一直调用它自己的两个函数。
导致问题的原因是什么?如何解决?
答案 0 :(得分:1)
您没有在place_changed
事件中设置lat_hidden和long_hidden字段。因此,此代码不会创建有效的google.maps.LatLng()
:
map_location = new google.maps.LatLng(
parseFloat(document.getElementById("lat_hidden").value),
parseFloat(document.getElementById("long_hidden").value)
);
工作代码段:
var map_location = new google.maps.LatLng(45.815015, 15.981912);
var marker;
var map;
var autocomplete;
function initialize() {
var mapOptions = {
zoom: 13,
center: map_location
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
marker = new google.maps.Marker({
map: map,
draggable: true,
position: map_location
});
google.maps.event.addListener(marker, 'dragend', function(event) {
document.getElementById("lat_hidden").value = this.getPosition().lat();
document.getElementById("long_hidden").value = this.getPosition().lng();
});
autocomplete = new google.maps.places.Autocomplete(
document.getElementById('autocomplete'), {
types: ['geocode']
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
document.getElementById("lat_hidden").value = autocomplete.getPlace().geometry.location.lat();
document.getElementById("long_hidden").value = autocomplete.getPlace().geometry.location.lng();
map_location = new google.maps.LatLng(
parseFloat(document.getElementById("lat_hidden").value),
parseFloat(document.getElementById("long_hidden").value)
);
marker.setPosition(map_location);
map.panTo(map_location);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<div id="map-canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>
<input id="lat_hidden" />
<input id="long_hidden" />
<input id="autocomplete" />