2016-03-03 261 views
-1

过去一天左右,我一直在头撞我的桌子,无法弄清楚这一点。每当标记添加到我的地图时,他们随机生成他们的标签。这样可以,但是在页面上调用的PHP代码会按照列出的顺序显示位置。该列表必须与标记匹配。我想使用位置数组中的数字作为我的标签,但无论我尝试什么,我都无法获取label:locations [i] [2](或任何变体)的工作。谷歌地图地理编码与自定义标签地址?

我试着在for循环中添加一个等于位置[i] [2]的变量,但它只是在标记函数中调用变量时存储和显示最后一个数字。

希望这是有道理的。

var locations = [ 
    ['text','address1','1'], 
    ['text','address2','2'], 
    ]; 

var labels = '123456789'; 
var labelIndex = 0; 

var map = new google.maps.Map(document.getElementById('map'), { 
    zoom: 10, 
    center: new google.maps.LatLng(38.3509665,-81.6881185), 
    mapTypeId: google.maps.MapTypeId.ROADMAP, 
    disableDefaultUI: true 
}); 

var trafficLayer = new google.maps.TrafficLayer(); 
trafficLayer.setMap(map); 

var infowindow = new google.maps.InfoWindow(); 
var geocoder = new google.maps.Geocoder(); 

var marker, i; 

for (i = 0; i < locations.length; i++) { 
    geocodeAddress(locations[i]); 
} 

function geocodeAddress(location) { 
geocoder.geocode({ 'address': location[1]}, function(results, status) { 
//alert(status); 
if (status == google.maps.GeocoderStatus.OK) { 

    //alert(results[0].geometry.location); 
    map.setCenter(results[0].geometry.location); 
    createMarker(results[0].geometry.location,location[0]+"<br>"+location[1]); 
} 
else 
{ 
    alert("some problem in geocode" + status); 
} 
}); 
} 

function createMarker(latlng,html){ 
var marker = new google.maps.Marker({ 
position: latlng, 
map: map, 
label: labels[labelIndex++ % labels.length], 
}); 

google.maps.event.addListener(marker, 'mouseover', function() { 
infowindow.setContent(html); 
infowindow.open(map, marker); 
}); 

google.maps.event.addListener(marker, 'mouseout', function() { 
infowindow.close(); 
}); 

} 

google.maps.event.addDomListener(window, 'load', initialize); 

在此先感谢。

回答

0

这里是更新的功能,我添加了createMarker的第三个变量,名为label,其中我将location[2]传递给此变量。

function geocodeAddress(location) { 
geocoder.geocode({ 'address': location[1]}, function(results, status) { 
//alert(status); 
if (status == google.maps.GeocoderStatus.OK) { 

    //alert(results[0].geometry.location); 
    map.setCenter(results[0].geometry.location); 
    createMarker(results[0].geometry.location,location[0]+"<br>"+location[1],location[2]); 
} 
else 
{ 
    alert("some problem in geocode" + status); 
} 
}); 
} 

function createMarker(latlng,html,label){ 
var marker = new google.maps.Marker({ 
position: latlng, 
map: map, 
label: label 
}); 
+0

废话。我不敢相信这会很容易。我现在觉得很愚蠢。 谢谢! – gr8whtd0pe