我有問題把鏈接放在多個標記,我可以在地圖上顯示我的標記,但是當我嘗試把鏈接放在他們身上時,我總是所有標記上的相同鏈接,最後一個。這裏我提供一個示例代碼:Javascript谷歌地圖Api,多個標記鏈接,只geoceder
<div id="map" style="height: 400px; width:100%;"></div>
<script>
var markers = [{"name":"Vasto","url":"http://www.google.com"},{"name":"Chieti","url":"http://www.wikipedia.com"}];
var geocoder;
var map;
var LatLng;
var url;
console.log(markers);
function initMap() {
LatLng = {lat: 42.2872297, lng: 13.3403448};
map = new google.maps.Map(document.getElementById('map'), {zoom: 8, center: LatLng});
geocoder = new google.maps.Geocoder();
setMarkers();
}
function setMarkers() {
var marker, i, url;
for(i = 0; i < markers.length; i++) {
url = markers[i].url;
geocoder.geocode({'address': markers[i].name}, function(results, status) {
if (status === 'OK') {
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: results[0].address_components[0].long_name,
});
google.maps.event.addListener(marker, "click", function() {
window.location.href = url;
});
} else {
/*console.log('Geocode was not successful for the following reason: ' + status);*/
}});
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=MYKEY&callback=initMap" async defer></script>
任何解決方案? 在此先感謝
異步函數(geocoder.geocode)內的for循環......當我們將永遠學習 - 我尋找合適的副本,但似乎無法找到它,因爲我一直醉漢 –
是的好,但我需要geocoder,因爲我不能'存儲latlng數據,有一種方法或替代? –
你不需要替代方案 - 問題是異步代碼...在調用geocoder.geocode回調中的代碼時,'url'的值被**保證**爲'markers [markers。長度 - 1] .url' –