简体   繁体   中英

Wrong marker being retrieved in gmap3

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

The "get" function retrieves the chained results from the beginning, indexes will never change.

Store it locally in your function using the "then"

function addMarker(map, marker, content) {
  var gmMarker;
  map
      .marker(marker)
      .then(function (m) {
        gmMarker = m;
      })
      .infowindow({
        'content' : content
      })
      .then(function (infowindow) {
        var map = this.get(0);
        gmMarker.addListener('click', function(event, data) {
          infowindow.open(map, this);
        });
      });
}

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