Finding nearest location using latitude and longitude.

Posted on August 12, 2015 by Suresh Kamrushi in Mysql

Here I am explaining how you can find nearest latitude and longitude with user entered latitude and longitude.

Here i am trying to search all nearby places by providing user location and distance from it. We can get the user location using my earlier article “How to get location on google Map“.

Let create the a table which hold the all the places in the city.

CREATE TABLE `destination` (
  `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
  `place_name` VARCHAR( 100 ) NOT NULL ,
  `address` VARCHAR( 250 ) NOT NULL ,
  `city` VARCHAR( 50 ) NOT NULL ,
  `lat` FLOAT( 10, 6 ) NOT NULL ,
  `lng` FLOAT( 10, 6 ) NOT NULL
) ENGINE = MYISAM;

Now we will dump some data to be search.

INSERT INTO  `destination` (`place_name`,`address`,`city` ,`lat` ,`lng`)
VALUES  ('Golconda Fort',  'Golconda Fort',  'Hyderabad',  '17.379064',  '78.403341'),
        ('NTR Gardens',  'NTR Marg, Central Secretariat, Khairatabad, Hyderabad, Telangana 500004, India',  'Hyderabad',  '17.412616',  '78.468784'),
        ('Lumbini Park',  'Opposite Secretariat New Gate, Khairatabad, Hyderabad, Andhra Pradesh 500004, India',  'Hyderabad',  '17.412616',  '78.468784'),
        ('Birla Mandir',  'Hill Fort Road, Hyderabad, Telangana 500004, India',  'Hyderabad',  '17.405459',  '78.469430'),
        ('Prasads',  'NTR Gardens, LIC Division P.O., Hyderabad, Telangana 500063, India',  'Hyderabad',  '17.412850',  '78.465884');

Now if you want to search for nearby places of user latitude and longitude i.e. 17.4349893 and 78.2342 respectively, just run the below query:

SELECT  ( 3959 * acos( cos( radians(17.414478) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(78.466646) ) + sin( radians(17.414478) ) * sin( radians( lat ) ) ) ) AS distance FROM destination HAVING distance < 5 ORDER BY distance LIMIT 0 , 20;

Query will get first 20 nearest places within 5 miles of given latitude and longitude.

Original Article: https://developers.google.com/maps/articles/phpsqlsearch_v3?csw=1

For more information on latitude and longitude.

  Comments or questions are welcome