简体   繁体   English

Google地图动态添加标记

[英]Google Maps Adding Markers dynamically

I want to add dynamic markers to my Map, where each is located at longitude[i] and latitude[i], and I want a pop-up window to open when the user click on the marker, where in the url of the window &id=id[i]. 我想在我的Map中添加动态标记,其中每个都位于经度[i]和纬度[i],我想要在用户点击标记时打开一个弹出窗口,在窗口的url中&ID = ID [i]中。

I tried using the following: 我尝试使用以下内容:

  <script type="text/javascript">
function initialize() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(48, 2),
mapTypeId: google.maps.MapTypeId.ROADMAP
};

var map = new google.maps.Map(document.getElementById('map-canvas'),
  mapOptions);

for (var i = 0; i < id.length; i++) {
var position = new google.maps.LatLng(latitude[i],longitude[i]);
marker[i] = new google.maps.Marker({
  position: position,
  map: map
});

marker[i].setTitle("pv");
google.maps.event.addListener(marker[i], 'click', function() {
window.open('blah.php?id='+id[i],'name','height=1000,width=1000')
});

}
}

google.maps.event.addDomListener(window, 'load', initialize);
  </script>

It doesn't seem to work, because the when clicking on the marker, the function addListener will be called and at the moment i = id.length 它似乎不起作用,因为当点击标记时,函数addListener将被调用,此刻i = id.length

what I want is for marker[0] to open the window with id[0], id[1] for marker[1] etc... 我想要的是标记[0]打开id [0]的窗口,标记[1]的id [1]等...

Can you try replacing this - 你能尝试更换吗 -

google.maps.event.addListener(marker[i], 'click', function() {
    window.open('blah.php?id='+id[i],'name','height=1000,width=1000')
});

by this - 这样 -

(function (i) {
    google.maps.event.addListener(marker[i], 'click', function() {
        window.open('blah.php?id='+id[i],'name','height=1000,width=1000')
    });
})(i);

Wrapping the listener in a closure will execute it with the state at that point of time. 将侦听器包装在闭包中将使用该时间点的状态执行它。 Check this out for more details - adding 'click' event listeners in loop 查看更多详细信息 - 在循环中添加“click”事件侦听器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM