Google map API v3 - Add multiple infowindows

后端 未结 2 1859
你的背包
你的背包 2020-12-05 10:50

I\'ve got a working section of google maps javascript, I did have a problem.

Now the issue I had was that only one infowindow was showing up, the la

相关标签:
2条回答
  • 2020-12-05 11:26

    For some reason, I had to modify marker object and access that data inside event lisener function.

    Scope of click event fuction on marker is marker object.

    var infowindow = new google.maps.InfoWindow();
    
    for(int i = 0; i < locations.length; i++){
        var latLng = new google.maps.LatLng(locations[i][1], locations[i][2]);
        var contentString = locations[i][0];
    
        marker = new google.maps.Marker({           
              position: latLng,
              map: map,
              contentString: contentString
        });
        marker.data = locations[i]; // adds object to marker object
    
    
        marker.addListener('click', function() {
            // read custom data in this.data   
            infowindow.setContent("<div id='infowindow'>"+ this.data[0] +"</div>");
    
            infowindow.open(map, this);
            map.setCenter(this.getPosition());
         });
    }
    
    0 讨论(0)
  • 2020-12-05 11:27

    Don't loop your infowindow...
    You need only one instance of the infowindow object.
    Move it outside of the loop, same for your functions.
    Inside the loop assign its content as relative to the clicked marker

    const locations = [
      {lat: 45.840196, lng: 15.964331, name: "Zagreb"},
      {lat: 43.514851, lng: 16.449083, name: "Split"},
      {lat: 42.645725, lng: 18.094058, name: "Dubrovnik"},
    ];
    
    function initGoogleMap(){
    
      const infowindow = new google.maps.InfoWindow(); // Only one InfoWindow
      const map = new google.maps.Map(document.getElementById('map-canvas'), {
          zoom: 6,
          center: new google.maps.LatLng(45, 15)
      });
      
      function placeMarker( loc ) {
        const marker = new google.maps.Marker({
          position : new google.maps.LatLng( loc.lat, loc.lng ),
          map : map
        });
        google.maps.event.addListener(marker, 'click', function(){
            infowindow.close(); // Close previously opened infowindow
            infowindow.setContent(`<div id="infowindow">${loc.name}</div>`);
            infowindow.open(map, marker);
        });
      }
      
      // ITERATE ALL LOCATIONS. Pass every location to placeMarker
      locations.forEach( placeMarker );
      
    }
    
    google.maps.event.addDomListener(window, 'load', initGoogleMap);
    html, body, #map-canvas { height: 100%; margin: 0px; }
    #infowindow{ padding: 10px; }
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
    <div id="map-canvas"></div>

    0 讨论(0)
提交回复
热议问题