jbdemonte / gmap3

jQuery plugin to create Google maps
http://gmap3.net
668 stars 198 forks source link

Wrong marker being retrieved in gmap3 #90

Closed TheInvoker closed 8 years ago

TheInvoker commented 8 years ago

In gmap3 google maps library, I am trying to make a function that makes a marker with an infowindow.

http://gmap3.net/api-infowindow.html

    function addMarker(map, marker, content) {
        map.marker(marker)
        .infowindow({
            'content' : content
        })
        .then(function (infowindow) {
            var map = this.get(0);
            var marker = this.get(1);  // <---- this gets the first marker on both times I call addMarker, i.e. uluru
            marker.addListener('click', function(event, data) {
                infowindow.open(map, this);
            });
        });
    }

    $(document).ready(function() {

        var uluru = {lat: -25.363, lng: 131.044};

        var map = $('#map')
          .gmap3({
            zoom: 4,
            center: uluru
          });

        addMarker(map, {
            position: uluru
        }, "text");
        addMarker(map, {
            position: {lat: 48.8620722, lng: 2.352047}
        }, "text2");
    });

This is what I have, but the problem is, in the top, where I try to get a marker (i put a comment in the code), it seems to be referencing the wrong marker. Both times I call it, it references the first marker I make. As a result, if I click the first marker on the map, I get both infowindows showing up on that marker.

Does anyone know whats wrong?

Thanks

TheInvoker commented 8 years ago

I found a workaround

function addMarker(map, marker, content) {
    map.marker(marker).then(function(marker) {
        map.infowindow({
            'content' : content
        })
        .then(function (infowindow) {
            var map = this.get(0);
            marker.addListener('click', function(event, data) {
                infowindow.open(map, this);
            });
        });
    });
}
jbdemonte commented 8 years ago

Yes, "get" return the created items from the beginning, And yes, your "workaround" is how you're supposed to do, this is done like this in the example

btw, I note that it might be useful to handle negative index in get, ie: get(-1) to get the last item... I'll add it i guess