javascriptgreat-circle

Limiting the great circle


I need to limit the radius of the great circle problem. The circle will extend until it hits another item.

I need it to limit the range of the circle to 5 miles

Here is my code

function find_closest_ticket(ticket, lat, lng) {

//  var lat = map.position.coords.latitude;
//  var lon = map.position.coords.longitude;

//  lat = 24.709254;
//  lng = -81.381927;
var R = 6371; // radius of earth in km
var distances = [];
var closest = -1;

for (i = 0; i < ticket.length; i++) {
  var mlat = ticket[i].soLAT;
  var mlng = ticket[i].soLNG;
  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;
  }
  }
return closest;
}

Solution

  • First, it is surprising you use a function that returns a radius in km, and then want to limit it to 5 miles. You should make up your mind: either write the function to return miles and add the limit in miles, or leave the function as-is and limit it by km (8 km is roughly 5 miles).

    If you want to use miles, then change this line:

    var R = 6371; // radius of earth in km
    

    to:

    var R = 3959; // radius of earth in miles
    

    and replace:

    return closest;
    

    by:

    return Math.min(5, closest);
    

    Alternatively, if you want to stick to km, then only replace:

    return closest;
    

    by:

    return Math.min(8, closest);