简体   繁体   中英

How to add title in marker in google map v2?

Hi all here i'm pointing an array of latlng in google map. I've done marking those latlng but not able to point marker title? so, i put GEvent, ie addlistener that display only one title.

for (var i = 0; i < g_listOfBusinessDetails.length ;i++) 
    {
        point = new GLatLng(g_listOfBusinessDetails[i].mapLocation.latitude, g_listOfBusinessDetails[i].mapLocation.longitude);
        map.setCenter(point, 2);
        var marker = new GMarker(point);
        map.addOverlay(marker);
        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(g_listOfBusinessDetails[i].name);
        });

    }

This is a very common JavaScript problem--you can see a similar question asked here and there's also a nice blog post explaining it. The problem is that the variables marker and i , as well as g_listOfBusinessDetails , which you use inside the function are not bound to the values they had when you called GEvent.addListener . On the click event, the function gets run with whatever values they have at that point in time (so that for example i is presumably g_listOfBusinessDetails.length ).

You can bound them as required by calling a factory function that creates the handler function for your marker and title like so:

GEvent.addListener(marker, "click", (function(myMarker, title) {
    return function() {
        myMarker.openInfoWindowHtml(title);
    }
})(marker, g_listOfBusinessDetails[i].name));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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