I have a multidimensional array of latitudes and longitudes, and one other single marker “m”. I need to get the two most closest points to “m” from the array for creating two other markers. Any help would be highly appreciated.
this is the array of lats and lons
var locations= [
['loc1', 54.1121824,-1.3983992],
['loc2', 54.2121824,-1.4323992],
['loc3', 54.4121824,-1.5993992],
['loc4', 54.3871874,-1.6773992],
['loc5', 54.1963824,-1.5983992]
];
I want to get the most two closest points to m=54.1143824,-1.4963992 for creating two markers from them
One of the components is using the
geometrylibrary functioncomputeDistanceBetween(from:LatLng, to:LatLng, radius?:number)whereradiusis optional (Earth’s radius).You must include
geometrywith the JS API using thelibrariesparameter:<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>Now you can loop through your data, saving the computed distance between each coordinate and the special marker
m. The result will be in meters by default (changing the radius optionally will give different units)For each row in the coordinates data, make a
rowLatLng = new google.maps.LatLng(row[1], row[2])google.maps.geometry.spherical.computeDistanceBetween(rowLatLng, m.getPosition())Then, the best way I can think of extracting the two closest points is using an object
{ locationname: "loc1", distance: 20 }to save which point is being compared to marker “m”, and what the computed distance is. Even better, could be to save the “row” index from the locations variable so you can pull the coordinate easily.An array of these objects can then be sorted by distance. I found a post here: Sorting an array of JavaScript objects with the following answer for sorting homes by their price: