PHP: Search for geographical locations and calculate the distance between two geographical locations _ php instance

Source: Internet
Author: User
This article describes how to search for a geographical location in PHP and how to calculate the distance between two geographical locations. The example of a geographical location search uses the MongoDB database. For more information, see Geographic location search
LBS stores the longitude and latitude coordinates of each location, searches for nearby locations, and establishes geographic location indexes to improve query efficiency.
Mongodb geographic location index, 2d and 2 dsphere, corresponding to the plane and sphere.

1. Create coordinates of the location where the lbs collection is stored

Use lbs; db. lbs. insert ({loc: {type: "Point", coordinates: [113.332264, 23.156206]}, name: "Guangzhou East Station"}) db. lbs. insert ({loc: {type: "Point", coordinates: [113.330611, 23.147234]}, name: "Lin and Xi"}) db. lbs. insert ({loc: {type: "Point", coordinates: [113.328095, 23.165376]}, name: "tianyao "})

2. Create a geographic location index

db.lbs.ensureIndex(   {     loc: "2dsphere"   } ) 

3. query coordinates nearby
Current location: Times Square,
Coordinates:

113.323568, 23.146436

Search for points within one kilometer, sorted from near to far

db.lbs.find(   {     loc: {       $near:{         $geometry:{           type: "Point",           coordinates: [113.323568, 23.146436]         },         $maxDistance: 1000       }     }   } ) 

Search Results:

The Code is as follows:

{"_ Id": ObjectId ("556a651996f1ac2add8928fa"), "loc": {"type": "Point", "coordinates": [113.330611, 23.147234]}, "name": "Lin and Xi "}

The php code is as follows:

<? Php // connect to mongodb function conn ($ dbhost, $ dbname, $ dbuser, $ dbpasswd) {$ server = 'mongodb ://'. $ dbuser. ':'. $ dbpasswd. '@'. $ dbhost. '/'. $ dbname; try {$ conn = new Login client ($ server); $ db = $ conn-> selectDB ($ dbname);} catch (LOGIN exception $ e) {throw new ErrorException ('unable to connect to db server. error :'. $ e-> getMessage (), 31);} return $ db;} // insert coordinates to mongodb function add ($ dbconn, $ tablename, $ lon Gcenters, $ latitude, $ name) {$ index = array ('loc '=> '2dsphere '); $ data = array ('loc '=> array ('type' => 'point', 'coordinates' => array (doubleval ($ longpolling ), doubleval ($ latitude), 'name' => $ name); $ coll = $ dbconn-> selectCollection ($ tablename); $ coll-> ensureIndex ($ index ); $ result = $ coll-> insert ($ data, array ('W' => true); return (isset ($ result ['OK']) &! Empty ($ result ['OK'])? True: false;} // search for nearby Coordinate function query ($ dbconn, $ tablename, $ longpolling, $ latitude, $ maxdistance, $ limit = 10) {$ param = array ('loc '=> array (' $ nearSphere '=> array (' $ ry '=> array ('type' => 'point ', 'coordinate' => array (doubleval ($ longpolling), doubleval ($ latitude),), '$ maxDistance' => $ maxdistance * 1000 ))); $ coll = $ dbconn-> selectCollection ($ tablename); $ cursor = $ coll-> find ($ param); $ Cursor = $ cursor-> limit ($ limit); $ result = array (); foreach ($ cursor as $ v) {$ result [] = $ v ;} return $ result;} $ db = conn ('localhost', 'lbs ', 'root', '123 '); // insert 100 coordinate records at random for ($ I = 0; $ I <100; $ I ++) {$ longpolling = '2017. 3 '. mt_rand (10000,999 99); $ latitude = '23. 15 '. mt_rand (1000,999 9); $ name = 'name '. mt_rand (longitude, 99999); add ($ db, 'lbs ', $ longpolling, $ latitude, $ name) ;}// search for a point within one kilometer $ longpolling = 1 13.323568; $ latitude = 23.146436; $ maxdistance = 1; $ result = query ($ db, 'lbs ', $ longpolling, $ latitude, $ maxdistance ); print_r ($ result);?>

To demonstrate the php code, you must first create a user in mongodb's lbs and execute auth. The method is as follows:

use lbs; db.createUser(   {     "user":"root",     "pwd":"123456",     "roles":[]   } )  db.auth(   {     "user":"root",     "pwd":"123456"   } ) 

Calculate the distance between two points of geographic coordinates
Function: calculates the spherical distance between two points based on the circumference rate and the latitude and longitude of the earth's radius coefficient and the two-point coordinate.


Obtain the two-point coordinate distance:

<? Php/*** calculate the distance between two geographical coordinates * @ param Decimal $ longitude1 start longitude * @ param Decimal $ latitude1 start latitude * @ param Decimal $ longitude2 end longitude * @ param Decimal $ latitude2 end latitude * @ param Int $ unit 1: meters 2: Km * @ param Int $ decimal precision reserved Decimal places * @ return decimal */function getDistance ($ longitude1, $ latitude1, $ longitude2, $ latitude2, $ unit = 2, $ decimal = 2) {$ EARTH_RADIUS = 6370.996; // Earth radius coefficient $ PI = 3.1415926; $ radLat1 = $ lat Itude1 * $ PI/180.0; $ radLat2 = $ latitude2 * $ PI/180.0; $ radLng1 = $ longitude1 * $ PI/180.0; $ radLng2 = $ longitude2 * $ PI/180.0; $ a = $ radLat1-$ radLat2; $ B = $ radLng1-$ radLng2; $ distance = 2 * asin (sqrt (pow (sin ($ a/2), 2) + cos ($ radLat1) * cos ($ radLat2) * pow (sin ($ B/2), 2); $ distance = $ distance * $ EARTH_RADIUS * 1000; if ($ unit = 2) {$ distance = $ distance/1000;} return round ($ distance, $ Decimal);} // start coordinate $ longitude1 = 113.330405; $ latitude1 = 23.147255; // end coordinate $ longitude2 = 113.314271; $ latitude2 = 23.1323; $ distance = getDistance ($ longitude1, $ latitude1, $ longitude2, $ latitude2, 1); echo $ distance. 'M'; // 2342.38 m $ distance = getDistance ($ longitude1, $ latitude1, $ longitude2, $ latitude2, 2); echo $ distance. 'km '; // 2.34?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.