2016-03-03 122 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