Google Maps API,所有标记均打开相同的信息窗口 [英] Google Maps API, all markers opening the same infowindow

查看:67
本文介绍了Google Maps API,所有标记均打开相同的信息窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,该页面可以检索一堆位置以及有关其关联标记的一些数据,并将其放置在Google Maps地图上.每个人都应该在单击时弹出自己的小消息.但是,单击它们中的任何一个都会在最新添加的标记处弹出最新添加的消息.是什么赋予了?我是否无法正确编写click事件的脚本?这是相关的代码:

I've got a page that retrieves a bunch of locations and some data about their associated markers and puts them on a Google Maps map. Each one is supposed to pop up its own little message when clicked on. However, clicking on ANY of them makes the most recently added message pop up at the most recently added marker. What gives? Am I not scripting the click event properly? Here's the relevant code:

var xmlDoc;
    if (window.XMLHttpRequest)
    {
    xmlDoc=new window.XMLHttpRequest();
    xmlDoc.open("GET","locs.php",false);
    xmlDoc.send("");
    xmlDoc=xmlDoc.responseXML;
    }
    // IE 5 and IE 6
    else if (ActiveXObject("Microsoft.XMLDOM"))
    {
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async=false;
    xmlDoc.load("locs.php");
    }

    var pins = xmlDoc.getElementsByTagName("pin");
    //alert(pins);

    for (i=0;i<pins.length;i++)
    {
       //alert(pins[i].getElementsByTagName("lat")[0].childNodes[0].nodeValue);
       var point = new GLatLng( pins[i].getElementsByTagName("lat")[0].childNodes[0].nodeValue, 
                                pins[i].getElementsByTagName("lon")[0].childNodes[0].nodeValue);
       var colord;
       var curgender = pins[i].getElementsByTagName("gender")[0].childNodes[0].nodeValue;
       if(curgender == "Male")
       {colord = blueOpt;}else if(curgender=="Female"){colord = pinkOpt;}else{colord = purpleOpt;}

       var marker = new GMarker(point, colord);
       var mess =  pins[i].getElementsByTagName("message")[0].childNodes[0].nodeValue;

       GEvent.addListener(marker, "click", function() {
         marker.openInfoWindowHtml(mess);
       });

       map.addOverlay(marker);

    }
  }

推荐答案

Daff对范围是正确的.但是,一种替代方法是使用 bindInfoWindowHtml()而不是带有openInfoWindowHtml()的侦听器.只需用以下代码替换侦听器:

Daff is right about the scope. One alternative, however, is to use bindInfoWindowHtml() instead of a listener with openInfoWindowHtml(). Just replace the listener with this code:

marker.bindInfoWindowHtml(mess);


更新:作为旁注-由于关闭,任何将记住在for循环中创建的变量.解决该问题的直接方法是创建一个单独的函数来创建侦听器.


UPDATE: As a sidenote - because of closure, any variable created in a for loop will be remembered. A direct solution to the problem is to make a separate function to create the Listener.

createMarker(marker,mess);

并添加功能:

function createMarker(marker, mess) {
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(mess);
    });
}

这篇关于Google Maps API,所有标记均打开相同的信息窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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