When i click on map, which will be best way to find nearest marker or markers? is there some functions in api that will help me to do that?
it s google map api v3.
Sommaire |
When i click on map, which will be best way to find nearest marker or markers? is there some functions in api that will help me to do that?
it s google map api v3.
First you have to add the eventlistener
google.maps.event.addListener(map, click , find_closest_marker);
http://en.wikipedia.org/wiki/Haversine_formula http://en.wikipedia.org/wiki/Haversine_formula
function rad(x) {return x*Math.PI/180;} function find_closest_marker( event ) { var lat = event.latLng.lat(); var lng = event.latLng.lng(); var R = 6371; // radius of earth in km var distances = []; var closest = -1; for( i=0;i<map.markers.length; i++ ) { var mlat = map.markers[i].position.lat(); var mlng = map.markers[i].position.lng(); var dLat = rad(mlat - lat); var dLong = rad(mlng - lng); var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(rad(lat)) * Math.cos(rad(lat)) * Math.sin(dLong/2) * Math.sin(dLong/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = R * c; distances[i] = d; if ( closest == -1 || d < distances[closest] ) { closest = i; } } alert(map.markers[closest].title); }
This keeps track of the closest markers and alerts its title.
I have my markers as an array on my map object
License : cc by-sa 3.0
http://stackoverflow.com/questions/4057665/google-maps-api-v3-find-nearest-markers