0

I'm trying to create a Javascript function that can find the closest coordinate match in an array of coordinates.

My coordinates: 33.9321, 18.8602 These coordinates will vary, but the 4 locations listed below will stay the same.

Location1: 33.9143, 18.5701 Location2: 26.2041, 28.0473 Location3: 25.7479, 28.2293 Location4: 29.8587, 31.0218

Michiel van Dijk
  • 783
  • 2
  • 8
  • 19
  • see this question: https://stackoverflow.com/questions/21279559/geolocation-closest-locationlat-long-from-my-position – Kresimir Pendic Nov 15 '17 at 13:48
  • I've been looking at that one for quite a while, and it's definitely the closest answer I could find. However, I do not seem to be able to change the coordinates that are being pulled through the user's location in that example, to the variable coordinates I want to use – Michiel van Dijk Nov 15 '17 at 13:51
  • did you get to see the example code that I posted for you @Michiel – Kresimir Pendic Nov 19 '17 at 12:43
  • Yes, thanks for that. I haven't got it to work as I'm using the Javascript in our CRM system (Podio). That system doesn't allow the use of console.log for instance, so I've logged a Support request with them. Just waiting for their response and hopefully I can apply your code then.. – Michiel van Dijk Nov 20 '17 at 12:58

1 Answers1

0

try to run my code to see if it helps you. I have used var home as your stargint point if browser didn't work for you. Also I have saved all locations in var points so you can change that if you need.

Then I just look over each point and it will output in the console what is the distance to ref point. In your case it's the first point

var home = [ '33.9321', '18.8602' ];
var points = [ 
  [ '33.9143', '18.5701' ],
  [ '26.2041', '28.0473' ],
  [ '25.7479', '28.2293' ],
  [ '29.8587', '31.0218' ]
];
// loop over each point and output distance!
for( var i = 0; i < points.length; i++){
  var diff = twoPointsDiff(home[0],home[1],points[i][0],points[i][1]);
  console.log( 'distance from point' + (i+1) + ': ' + diff );
}
// helper fn to calc distance
function twoPointsDiff(lat1,lon1,lat2,lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1); 
  var a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ; 
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
  var d = R * c; // Distance in km
  return d;
}
// helper fn to convert deg to radians
function deg2rad(deg) {
  return deg * (Math.PI/180)
}
Kresimir Pendic
  • 3,597
  • 1
  • 21
  • 28