谷歌地图infowindow显示错误的标记 [英] Google maps infowindow showing on wrong marker

查看:111
本文介绍了谷歌地图infowindow显示错误的标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  for(var)我有一段JavaScript代码,我在这里创建标记并将InfoWindows附加到它们上,如下所示: i = 0; i <8; i ++){
var marker = new google.maps.Marker({
map:map,
position:new google.maps.LatLng(lat [
icon:'/ static / images / iconsets / gmap / iconb'+(i + 1)+'.png',
});
var infowindow = new google.maps.InfoWindow({
content:'test string'
});
google.maps.event.addListener(marker,'click',function(){
infowindow.open(map,marker);
});
}

但是当我点击其中一个标记时,infowindow总是只显示一个标记。我做错了什么?

解决方案

有一个非常简单的解决方案来解决您的问题,即将循环代码放入函数。你的问题是你覆盖变量 marker ,所以当它在click事件中被访问时,它会使用该变量的最新版本,这是你添加的最后一个标记。

所以,当你把它放到一个函数中时,这个变量是在一个单独的名字空间中,因此不会被覆盖。换句话说,这应该起作用:

pre $ for(var i = 0; i <8; i ++){
createMarker(i);
}

函数createMarker(i){
var marker = new google.maps.Marker({
map:map,
position:new google .maps.LatLng(lat,lng),
icon:'/ static / images / iconsets / gmap / iconb'+(i + 1)+'.png',
});
var infowindow = new google.maps.InfoWindow({
content:'test string'
});
google.maps.event.addListener(marker,'click',function(){
infowindow.open(map,marker);
});
}


I have a piece of javascript code where I create markers and attach InfoWindows to them, like this:

for (var i = 0; i < 8; i++) {
    var marker = new google.maps.Marker({
       map: map,
       position: new google.maps.LatLng(lat[i], lng[i]),
       icon: '/static/images/iconsets/gmap/iconb' + (i+1) + '.png',
    });
    var infowindow = new google.maps.InfoWindow({
        content: 'test string'
    });
    google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map,marker);
    });
}

But when I click one of the markers, the infowindow always shows only on one marker. What am I doing wrong?

解决方案

There's a very simple solution to your problem, which is to put the loop's code into a function. Your problem is that you overwrite the variable marker, so that when it is accessed in the click event, it uses the latest version of that variable, which is the last marker you added.

So, when you put it into a function, the variable is in a separate namespace and therefore not overwritten. In other words, this should work:

for (var i = 0; i < 8; i++) {
    createMarker(i);
}

function createMarker(i) {
    var marker = new google.maps.Marker({
        map: map,
        position: new google.maps.LatLng(lat, lng),
        icon: '/static/images/iconsets/gmap/iconb' + (i+1) + '.png',
    });
    var infowindow = new google.maps.InfoWindow({
        content: 'test string'
    });
    google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map,marker);
    });
}

这篇关于谷歌地图infowindow显示错误的标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆