53

I want to find a nearest location from following database table

Address                            Latitude                longitude 

Kathmandu 44600, Nepal              27.7                   85.33333330000005
Los, Antoniterstraße                37.09024               -95.71289100000001
Sydney NSW, Australia               49.7480755             8.111794700000019
goa india                           15.2993265             74.12399600000003

I have fetched this all data from Google Maps. Here I have to find nearest location from a place. Suppose I am at place Surkhet its latitude is 28.6 and longitude is 81.6, how can I find nearest place from the place Surkhet.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Krishna Karki
  • 1,304
  • 4
  • 14
  • 31

8 Answers8

99

Finding locations nearby with MySQL

Here's the SQL statement that will find the closest 20 locations that are within a radius of 25 miles to the 37, -122 coordinate. It calculates the distance based on the latitude/longitude of that row and the target latitude/longitude, and then asks for only rows where the distance value is less than 25, orders the whole query by distance, and limits it to 20 results. To search by kilometers instead of miles, replace 3959 with 6371.

Table Structure :

id,name,address,lat,lng

NOTE - Here latitude = 37 & longitude = -122. So you just pass your own.

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * 
cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * 
sin( radians( lat ) ) ) ) AS distance FROM your_table_name HAVING
distance < 25 ORDER BY distance LIMIT 0 , 20;

You can find details here.

Pang
  • 9,564
  • 146
  • 81
  • 122
Scorpion
  • 6,831
  • 16
  • 75
  • 123
  • 3
    Also go through this one. It explains everything in nice way. https://developers.google.com/maps/articles/phpsqlsearch – Scorpion Jun 20 '12 at 04:54
  • Thank you so much for query. I have to find nearest location from Surkhet which latitude is 28.6 and longitude is 81.6. How to include this point on this query.. Please suggest me..:) – Krishna Karki Jun 20 '12 at 05:06
  • See the note. I edited my answer. You need to pass your lat & lng in place of 37 & -122, – Scorpion Jun 20 '12 at 05:15
  • 3
    Does this work for you?? And also keep in mind that i have used 3959, it will search by miles. If you want to search by km change it to 6371. – Scorpion Jun 20 '12 at 05:41
  • SELECT address, lng, SQRT( POW(69.1 * (lat -21.0486), 2) + POW(69.1 * ( 76.5344 - lng) * COS(lat/ 57.3), 2)) AS distance FROM partner_locations HAVING distance < 25000 ORDER BY distance I found this query.. Its working properly.. But i m not sure about unit of distance.. is it kilometer or miles... can you suggest me please – Krishna Karki Jun 20 '12 at 07:16
  • Sorry but don't have any idea about this query. Have you try the query which i give you? Try it once.. – Scorpion Jun 20 '12 at 08:25
  • @Scorpion i am facing a error in this query. will you please help? – Sandy Mar 10 '14 at 08:17
  • can you please tell us if this work fine for thousand records. Thanks – Muhammad Usama Mashkoor Aug 10 '17 at 20:15
30
SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;
Adriaan
  • 17,741
  • 7
  • 42
  • 75
Krishna Karki
  • 1,304
  • 4
  • 14
  • 31
3

To find the nearby location , you can use the Geocoder Class.Since you have the Geopoints(latitude and longitude), Reverse geocoding can be used. Reverse Geocoding is the process of transforming a (latitude, longitude) coordinate into a (partial) address. Check out this for more information.

Ankit Saxena
  • 2,309
  • 2
  • 18
  • 20
2
SELECT latitude, longitude, SQRT(
    POW(69.1 * (latitude - [startlat]), 2) +
    POW(69.1 * ([startlng] - longitude) * COS(latitude / 57.3), 2)) AS distance
FROM TableName HAVING distance < 25 ORDER BY distance;

where [starlat] and [startlng] is the position where to start measuring the distance and 25 is the distance in kms.

It is advised to make stored procedure to use the query because it would be checking a lots of rows to find the result.

Himanshu Upadhyay
  • 6,558
  • 1
  • 20
  • 33
0

The SQL have a problem. In table like:

`ubicacion` (
  `id_ubicacion` INT(10) NOT NULL AUTO_INCREMENT ,
  `latitud` DOUBLE NOT NULL ,
  `longitud` DOUBLE NOT NULL ,
  PRIMARY KEY (`id_ubicacion`) )

The id_ubicacion change when use:

SELECT  `id_ubicacion` , ( 3959 * ACOS( COS( RADIANS( 9.053933 ) ) * COS( RADIANS( latitud ) ) * COS( RADIANS( longitud ) - RADIANS( - 79.421215 ) ) + SIN( RADIANS( 9.053933 ) ) * SIN( RADIANS( latitud ) ) ) ) AS distance
FROM ubicacion
HAVING distance <25
ORDER BY distance
LIMIT 0 , 20
0
sesach : ( 3959 * acos( cos( radians('.$_REQUEST['latitude'].') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('.$_REQUEST['longitude'].') ) + sin( radians('.$_REQUEST['latitude'].') ) * sin( radians( latitude ) ) ) ) <='.$_REQUEST['mile'];
0

When the method should perform it is nicer to first filter on latitude and longitude, and then calculate the squared distance approximative. For Nordic countries, it will be about 0.3 percent off within 1000 km's.

So instead of calculatinG the distance as:

dist_Sphere = r_earth * acos ( sin (lat1) * sin (lat2) + cos(lat1)*cos(lat2)*cos(lon 2 - lon 1)

one can calculate the approximate value (assume that lat = lat 1 is close to lat 2) as

const cLat2 = cos lat ^ 2
const r_earth2 = r_earth ^ 2
dist_App ^2 = r_earth2 * ((lat 2 - lat 1) ^2 + clat2 *(lon 2 - lon 1) ^2)

Order by Dist_App 2, and then simply take the square root off the result.

Jesper Kleis
  • 51
  • 1
  • 6
0

1

If you want to display all values with distance

replace lat long with double quote ( " " )

the query will display only 25km distance data for more increase value

check for tricks and tips:- multigrad.in

SELECT *, SQRT(
POW(69.1 * (lat - "YOUR LATITUDE VALUE"), 2) +
POW(69.1 * ("YOY LONGITUDE VALUE" - lon) * COS(lat / 57.3), 2)) AS distance FROM moms HAVING distance < 25 ORDER BY distance;
vimuth
  • 5,064
  • 33
  • 79
  • 116