我有自定义谷歌地图多个标记。当我使用反向地理定位多个标记我接收大多数标记的未知地址如果我使用alert btwn调用我得到大多数地址的结果
for(var z = 0 ; z < markersArray.length; z++){
alert(z);
geocoder.geocode({'location': markersArray[z].position}, function(results, status) {
if(status == 'OK'){
if(results != null){
address = address + z +" : "+ results[1].formatted_address + "<br>";
alert(z);
}
else
{
address = address + z +" : "+"Unknown Address" + "<br>";
}
}
else{
alert(z);
address = address + z +" : "+"Unknown Address"+ "<br>";
}
});
}
答案 0 :(得分:1)
尝试在通话之间添加短暂延迟。有一次同样的问题,检查每个电话的结果并尝试重新发送几次有帮助。
答案 1 :(得分:1)
地理编码器是异步的。到回调函数运行时,循环已完成,z等于markersArray.length(这不是数组的有效条目)。这个问题可以通过函数闭包来解决([问题:Google Maps JS API v3 - Simple Multiple Marker Example中的示例用于标记点击监听器函数。
for (var z = 0; z < markersArray.length; z++) {
geocoder.geocode({
'location': markersArray[z].position
}, (function(z) {
// get function closure on z
return function(results, status) {
if (status == 'OK') {
if (results != null) {
var address = z + " : " + results[0].formatted_address + "<br>";
var marker = new google.maps.Marker({
position: markersArray[z].position,
title: address,
map: map
});
bounds.extend(marker.getPosition());
map.fitBounds(bounds);
google.maps.event.addListener(marker,'click', function(evt) {
infowindow.setContent(address);
infowindow.open(map, this);
})
} else {
var address = z + " : " + "Unknown Address" + "<br>";
}
} else {
var address = z + " : " + "Unknown Address" + "<br>";
}
}
})(z));
}
代码段
var geocoder;
var map;
var markersArray = [{position: {lat: 40.7127837,lng: -74.0059413}},
{position: {lat: 40.735657,lng: -74.1723667}},
{position: {lat:39.2903848,lng: -76.6121893}},
{position: {lat: 39.9525839,lng: -75.1652215}}];
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
for (var z = 0; z < markersArray.length; z++) {
geocoder.geocode({
'location': markersArray[z].position
}, (function(z) {
// get function closure on z
return function(results, status) {
if (status == 'OK') {
if (results != null) {
var address = z + " : " + results[0].formatted_address + "<br>";
var marker = new google.maps.Marker({
position: markersArray[z].position,
title: address,
map: map
});
bounds.extend(marker.getPosition());
map.fitBounds(bounds);
google.maps.event.addListener(marker, 'click', function(evt) {
infowindow.setContent(address);
infowindow.open(map, this);
})
} else {
var address = z + " : " + "Unknown Address" + "<br>";
}
} else {
var address = z + " : " + "Unknown Address" + "<br>";
}
}
})(z));
}
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>