Multiple Markers for Google Maps API V3 With Custom Icon

后端 未结 2 1648
星月不相逢
星月不相逢 2021-02-04 22:41

I\'m having problems with making multiple markers appear on my Google Map. I\'ve been trying stuff from all over the internet but most of the time the map just breaks.

E

相关标签:
2条回答
  • 2021-02-04 23:12

    Let's say you have an array of LatLng objects call latLngs and that you wanted a marker for each of those objects. You might do it something like this (taking the tail end of your code in your question and modifying it):

    var markers = new Array(latLngs.length);
    for (var i = 0; i < markers.length; i++) {
        markers[i] = new google.maps.Marker({
            position: latLngs[i],
            title:"Marker "+i,
            icon: image,
            shadow: shadow,
            map: map,
            shape: shape
        });
        markers[i].setMap(map);
    }
    

    The main thing is that you can't reuse your marker variable. You need to use a different variable for each marker, hence the array.

    0 讨论(0)
  • 2021-02-04 23:27

    Looks like the OP was able to use Trott's solution, but I couldn't get it to work myself. I found something else that is perhaps simpler and works for me right here. To summarize, wrap the addlistener call in your own function and then call that function from within your loop (wherever you are looping through data or markers). My function is simply...

    function listenInfoWindows(marker, infowindow) {
      google.maps.event.addListener(marker, 'click', function(){
          infowindow.open(map, marker); 
        }
      );
    }
    
    0 讨论(0)
提交回复
热议问题