简体   繁体   中英

Adding label to multiple markers in google map api

I have multiple longitude, latitude information in stores[][5] and stores[][6] which were passed from python to javascript, and corresponding label information to that longitude/latitude in stores[][1] . To show multiple markers that have their own label, I looped the code as below. It successfully showed multiple markers, but only one marker had a label.

    function initMap() {
    var uluru = {lat: -25.363, lng: 131.044};
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: uluru
    });


    {% for store in stores %}
    var contentString = '{{store[1]}}';
    var infowindow = new google.maps.InfoWindow({
      content: contentString
    });
      marker = new google.maps.Marker({
      position: {lat: {{store[5]}}, lng: {{store[6]}}}, 
      map: map,
      title: 'Uluru (Ayers Rock)'
    });
    marker.addListener('click', function() {
      infowindow.open(map, marker);
    });
    count = count + 1;
    {% endfor %}

As I found it surprising from the start that the same name variable marker can show multiple markers, I tried indexing marker and infowindow with increasing i as in

    marker[i] = new google.maps.Marker({...
    ...
    var infowindow[i] = new google.maps.InfoWindow({...

but in that case, only one marker was shown and no infowindow appeared. This is code between <script> tag in a html file and I'm using jinja2 template in case it makes a difference.

Objects in google maps api works in a different way and you can't simply loop them through without closures and expect them to work properly. Each marker needs to be created in it's of closure. You just need to loop through your array and call createMarkers function. Check the code below

function initMap() {
  var uluru = {
    lat: -25.363,
    lng: 131.044
  };
  var uluru2 = {
    lat: -26.363,
    lng: 139.044
  };
  var contentString = '<div id="content">1</div>';
  var contentString2 = '<div id="content">2</div>';
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: uluru
  });
  createMarkers(map, uluru, contentString);
  createMarkers(map, uluru2, contentString2);
}

function createMarkers(map, coords, CS) {
  var infowindow = new google.maps.InfoWindow({
    content: CS
  });
  var marker = new google.maps.Marker({
    position: coords,
    map: map,
    title: 'Uluru (Ayers Rock)'
  });
  marker.addListener('click', function() {
    infowindow.open(map, marker);
  });

}

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