How to set a popup on markers with Google Maps API?

后端 未结 4 437
小鲜肉
小鲜肉 2021-02-01 18:09

I have this code where I display and set all my markers. How can I add a popup with some information on markers with this code? I add \"i\" variable on text, but it sets on all

4条回答
  •  再見小時候
    2021-02-01 18:43

    First, change the loop condition to i < arraylng.length. Right now it is not capturing the last element of your array.

    JavaScript variables works with function scope so you need to call a function for each marker listener to create the correct variable references. You can use an anonymous function, as seen here, or define a function for creating the click listener:

    Multiple infoWindows:

    function makeInfoWindowEvent(map, infowindow, marker) {
      google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map, marker);
      });
    }
    

    Most likely you will not want more than one InfoWindow open at the same time, because it is annoying to have to click on the close x. Then you will only want one InfoWindow object, and set the content as the marker is clicked:

    Single InfoWindow:

    ...
      var infowindow = new google.maps.InfoWindow();
    
      for (var i = 0; i < arraylng.length-1; i++) {
        var marker = new google.maps.Marker({
          position: new google.maps.LatLng(arraylng[i], arraylat[i]),
          map: map
        });
    
        makeInfoWindowEvent(map, infowindow, "test" + i, marker);
    
        markers.push(marker);
      }
    }
    
    function makeInfoWindowEvent(map, infowindow, contentString, marker) {
      google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(contentString);
        infowindow.open(map, marker);
      });
    }
    

提交回复
热议问题