Skip to content Skip to sidebar Skip to footer

Find Nearest Pins On Google Map

I have been using the javascript Google Maps API to construct the following map: http://springhillfarm.com.au/locations-map/ and now I would like to list the nearest 5 pins when a

Solution 1:

I notice in your production code - which I might add could/should be heavily optimised! - you have your location and a bunch of markers using the following:

var myLatlng = new google.maps.LatLng(-37.5759571, 143.8064523);
var marker0 = new google.maps.Marker({ position: new google.maps.LatLng(-37.7994512, 144.9643374), map: map, title:"Toothpicks, 720 Swanston Street Carlton 3052 VIC", icon:image });
var marker1 = new google.maps.Marker({ position: new google.maps.LatLng(-31.9097004, 115.8485327), map: map, title:"Good Life Shop, Shop 7 Dog Swamp Shopping Centre, Yokine WA 6060", icon:image });

etc...

If you had those markers in an array, eg:

var markers = [ marker0, marker1, etc... ]

a simple approach would be to use a bit of pythagoras to get the distance between your current location and all the markers. Something like:

// make a new array of markers since you probably don't want to modify the existing arrayvar markersByDistance = [];
for ( var i = 0; i < markers.length; i++ ) {
    var marker = markers[i];

    // using pythagoras does not take into account curvature, // but will work fine over small distances.// you can use more complicated trigonometry to // take curvature into considerationvar dx = myLatlng.longitude - marker.longitude;
    var dy = myLatlng.latitude - marker.latitude;
    var distance = Math.sqrt( dx * dx + dy * dy );

    markersByDistance[ i ] = marker;
    markersByDistance[ i ].distance = distance;

}

// function to sort your data...functionsorter (a,b) { 
    return a.distance > b.distance ? 1 : -1;
}

// sort the array... now the first 5 elements should be your closest points.
markersByDistance.sort( sorter );

This all may be pointless since Google Maps API might do this natively for you.

Solution 2:

I am not sure if it only makes sense to display 5 pins if a user searches - he might move the map and then he will still see only 5 pins...

Instead I would go for a different approach: if loading the complete set of pins (like now) is too slow, just send the Google Maps viewport to an AJAX script and let this script return all pins in the current viewport. You can then only draw the pins that are relevant for the current map. When a user searches for his location, the viewport changes (you zoom to the new location), you request the AJAX script and get all pins in this area. This makes it much simpler and more scalable.

Post a Comment for "Find Nearest Pins On Google Map"