Veer
Veer

Reputation: 141

get nearest lat long around 25 km from given array lat long

i have array of lat long like :

var locationList = new Array( '23.2531803, 72.4774396', '22.808782, 70.823863', '24.3310019, 72.8516531', '22.3073095, 73.1810976', '22.3038945, 70.8021599', '23.850809, 72.114838' );

i want get nearest around 25 km 's lat long from first given array which is 23.2531803, 72.4774396

are there any calculation for nearest 25 km 's lat long from given array.

NOTE: for some reason i can not use sql query, because i get lat long from given address 

Upvotes: 1

Views: 1287

Answers (3)

core1024
core1024

Reputation: 1882

First of all your data array is awfull. You need to make your data more computer readable. Then you can use Pythagorean theorem to calculate the distance from each location. You can save the first distance and index in an variable then replace it with new distance and index if it's shorter.

var closest = {id:0,dist:-1};
var myloc = [23.2531303, 72.4774398]
for(var i = 0; i < locationList.length; i++)
{
  var long_lat = locationList[i].match(/([0-9.]+)+/)
  long_lat[0] = parseFloat(long_lat[0]);
  long_lat[1] = parseFloat(long_lat[1]);
  var dist = Math.sqrt(Math.pow(long_lat[0] - myloc[0], 2)+Math.pow(long_lat[1] - myloc[1], 2)));
  if((closest.dist == -1) || (closest.dist > dist))
  {
    closest.dist = dist;
    closest.id = i;
  }

}

Upvotes: 1

Dr.Molle
Dr.Molle

Reputation: 117334

When you like to calculate in JS you may use google.maps.geometry.spherical.computeDistanceBetween() to calculate the distance between the single points.

Store the results in an array, sort the array and when the smallest entry is <25km you got what you want.

Upvotes: 0

ty812
ty812

Reputation: 3323

Step 1: Calculate the distance between your start coordinate and every subcoordinate Step 2: Pick the smallest distance Step 3: Is it < 25 km? Success!

How to calculate distance between two coordinates:

function distance($lat1, $lon1, $lat2, $lon2) {

$D = 6371; // Earth Radius
$dLat = $lat2-$lat1;
$dLon = $lon2-$lon1;

$a = sin($dLat/2) * sin($dLat/2) +
     sin($dLon/2) * sin($dLon/2) * cos($lat1) * cos($lat2); 

$b = 2 * atan2(sqrt($a), sqrt(1-$a)); 
$c = 2 * atan2(sqrt($a), sqrt(1-$a)); 


return $D * $c;

}

This function thinks of the Earth as a perfect ball, which it is not - slight variations do apply, but are neglible at the 25km diameter you want.

Upvotes: 4

Related Questions