Friday 13 November 2015

Managing markers with the Same Coordinates in a Google Map

Hi Everybody,

In this blog we will discuss about managing multiple markers with the exact same location.
Google Maps API is an awesome tool, even though it has enough cons to hate it, it still has more pros to enjoy. In 3d revision of the API Google introduced new feature called clusters, which allows you to unite multiple markers in certain location and display a cluster instead, with a number of places it includes. Clicking on a cluster leads to zooming in, which reveals hidden markers and cluster disappears.

It works great, although there is an issue which is not covered by the library yet. When you have multiple markers with the exact same location, no matter how deep you zoom in, you won’t get a chance to see markers. If you remove clustering on a certain zoom levels (or remove it at all), you’ll see only one marker there(the top one), others will remain hidden underneath, since they stack on top of each other.

Solution


I’ve found couple of solutions out there in the web, but this one works best for me so far.

The idea is to iteratively check if existing markers match the coordinates of the new marker, if some of them do – than we add an offset to their coordinates.

I assume you already have a working application, which uses Google Maps API.

In your createMarker function add this code:

function createMarker(number, address, lat, lng) {
    var contentString = address;
    var newLat = lat + (Math.random() -.5) / 1500;// * (Math.random() * (max - min) + min);

    var newLng = lng + (Math.random() -.5) / 1500;// * (Math.random() * (max - min) + min);
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(newLatnewLng),
        map: map,
        icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld='+number+'|FF0000|000000'
    });

    google.maps.event.addListener(marker, 'click', function () {
        infowindow.setContent(contentString);
        infowindow.open(map, marker);
    });
    bounds.extend(marker.position);
}

(Math.random() -.5) / 1500 is about 100m, feel free to tweak an offset however you want.

    (Math.random() -.5) / 750 ~ 50m
    (Math.random() -.5) / 3000 ~ 200m

Note:-It’s not the cleanest solution, since your slightly corrupt data and some applications simply can’t afford it. I’d like to do this later on, but for a quick fix this solution will work just fine.

No comments:

Post a Comment