问题
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