Oliver Tappin
Oliver Tappin

Reputation: 2541

Finding nearest listed (array?) city from known location

I'm looking to integrate the HTML5 geolocation functionality into a website. The issue I have is getting the nearest city/town in a chosen list. The site is only supported/marketed in a certain number of towns and cites so the idea is that the browser finds their location and chooses their nearest town or city. Sounds simple enough but it's the 'finding the nearest' that I can get my head around.

I've found a thread that has helped me through the process of getting the long/lat from the browser and turning it into their Town/City name but this doesn't help finding the nearest listed one: Reverse Geocoding With Google Map API And PHP To Get Nearest Location Using Lat,Long coordinates

Are there any APIs (preferably in Google) that will find the nearest listed location? I've had a look and can't find any of the sort.

Upvotes: 0

Views: 3495

Answers (3)

david strachan
david strachan

Reputation: 7228

You can find the nearest city using the Haversine formula. The following functions are used to calculate the distance between the geolocated coordinates and the those of your array

function deg2rad(degrees){
radians = degrees * (Math.PI/180);
return radians;
}

function Haversine(lat1,lon1,lat2,lon2) {
  deltaLat = lat2 - lat1 ;
  deltaLon = lon2 - lon1 ;
  earthRadius = 3959; // in miles 6371 in meters.
  alpha    = deltaLat/2;
  beta     = deltaLon/2;
  a        = Math.sin(deg2rad(alpha)) * Math.sin(deg2rad(alpha)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(deg2rad(beta)) * Math.sin(deg2rad(beta)) ;
  c        = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  distance =  earthRadius * c;
  return distance.toFixed(2);
}

Upvotes: 5

Seain Malkin
Seain Malkin

Reputation: 2303

I think the easiest solution is to store the lat lng coordinates of each town or city in a database and just do a radius based search around the users location and produce the closest result.

Have a look at the accepted answer given to this question.

Search database with lat and long by radius using php mysql

Upvotes: 0

geocodezip
geocodezip

Reputation: 161334

The simplest way is to compute the "as the crow flies" distance from the user's location to all your cities, using the haversine formula or the computeDistanceBetween method of the spherical geometry library, and pick the smallest one.

If you have less than 100 locations, you can use the Distance Matrix to determine the shortest driving distance, then pick the town with the shortest result.

Upvotes: 0

Related Questions