Finding the closest list (array?) Of a city from a known location

I want to integrate HTML5 geolocation functionality into a website. The question I have is getting the nearest city / city in the selected list. The site is supported or sold only in a certain number of cities and is cited, so the idea is that the browser finds its location and selects the nearest city or city. It sounds simple enough, but it's a "search for the closest" in which I can plunge.

I found a stream that helped me in the process of getting a long / lat from the browser and turning it into a city / city name, but this does not help to find the closest list: Reverse geocoding with the Google Maps API and PHP to get the closest location using Lat, Long coordinates

Are there any APIs (preferably on Google) that find the closest location? I looked and can not find anything like it.

0
source share
3 answers

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

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); } 
+3
source

The easiest way is to calculate the crow-like distance from the user's location to all your cities using the haversine formula or the computeDistanceBetween method for spherical geometry and select the smallest one.

If you have less than 100 seats, you can use the Distance Matrix to determine the shortest distance, and then select the city with the shortest result.

0
source

I think that the easiest solution is to save the Latin alphabet coordinates of each city or city in the database and just search by the radius around the users location and get the closest result.

Take a look at the accepted answer to this question.

Finding a database with latitude and long radius using php mysql

0
source

Source: https://habr.com/ru/post/950984/


All Articles