0

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

Lucy
  • 471
  • 4
  • 12
  • 28

2 Answers2

3

One of the components is using the geometry library function computeDistanceBetween(from:LatLng, to:LatLng, radius?:number) where radius is optional (Earth's radius).

You must include geometry with the JS API using the libraries parameter:

<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:

homes.sort(function(a,b) { return parseFloat(a.price) - parseFloat(b.price) } );
Community
  • 1
  • 1
Tina CG Hoehr
  • 6,721
  • 6
  • 44
  • 57
0

I have some code for that on my main computer but basically here's what you have to do:

  • Loop through the coordinates and calculate the distance between each one and m (Haversine Formula)
  • Store each distance with the position's name in an array
  • Sort the array

Bingo.

EDIT:

Some code to calculate Haversine:

Number.prototype.toRad=function() {
 return this * (Math.PI / 180);
}


function Haversine=function(lat1, lon1, lat2, lon2) {
  var R = 6371; // km
  var dLat = (lat2-lat1).toRad();
  var dLon = (lon2-lon1).toRad();
  var lat1 = lat1.toRad();
  var lat2 = lat2.toRad();
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c;
  return d;
}
dda
  • 6,030
  • 2
  • 25
  • 34