Google Maps API V3 Indicate multiple markers in same location by different icon

孤街醉人 提交于 2020-01-17 02:54:07

问题


I'm working through all the code examples and have a page working that displays multiple markers. I have an array of locations and sometimes I have multiple markers with the same location. Only the top one displays, which is fine, but I want to indicate that there more markers hidden by changing the icon This bit works:

for (i = 0; i < locations.length; i++) 
{  
  marker = new gm.Marker({
    position: new gm.LatLng(locations[i][1], locations[i][2]),
    map: map,
    icon: MarkerImg,
  });
}

I don't seem to be able to add conditional code to the "icon: MarkerImg" line to change it to a different icon if the coords match to the previous one.

Is there some way to have conditional declarations (if thats the correct terminology) Thanks.


回答1:


If all you need to do is check the previous marker, just keep a reference to it:

var lastMarker = null;
for (i = 0; i < locations.length; i++) 
{  
  var marker = new gm.Marker({
    position: new gm.LatLng(locations[i][1], locations[i][2]),
    map: map,
    icon: MarkerImg,
  });
  if (!!lastMarker && !!lastMarker.getPosition &&
      (marker.getPosition().equals(lastMarker.getPosition()))) {
       marker.setIcon(MarkerImg2);
  }
  lastMarker = marker;
}

fiddle

Note: be careful with google.maps.LatLng.equals, the coordinates have to be exactly the same. Might want to pick a threshold (say 0.1 meter) and consider markers that are closer than that "at the same location".




回答2:


That did the trick, with a few edits: Yes, the markers will be coming in order, so that makes it easier. I had to define a position for lastMarker before the equals would work. I picked 0,0 as I reckon its unlikely to be used. Good solution? Also I set the lastMarker to the current marker for the next iteration. Good point on markers not exactly in the same position. For now they are, but its worth investigating that further.

lastMarker = new gm.Marker(
    {
    position: new gm.LatLng(0,0)
    });

for (i = 0; i < locations.length; i++) 
    {  
    marker = new gm.Marker(
        {
        position: new gm.LatLng(locations[i][1], locations[i][2]),
        map: map,
        icon: MarkerImg,
        });
    if (marker.getPosition().equals(lastMarker.getPosition())) {
        marker.setIcon(MultiMarkerImg);
        }
    lastMarker = marker;


来源:https://stackoverflow.com/questions/24439999/google-maps-api-v3-indicate-multiple-markers-in-same-location-by-different-icon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!