PHP geo-search and calculate distances

Source: Internet
Author: User
Tags cos sin
This article mainly introduces the PHP geographical location search and calculates the distance, the interest friend's reference, hoped to be helpful to everybody.

Location Search
LBS, which stores the latitude and longitude coordinates of each location, searches for nearby locations and establishes a geographical index to improve query efficiency.
MongoDB geolocation Index, 2d and 2dsphere, corresponds to planar and spherical surfaces.

1. Create lbs collection Storage location coordinates


use lbs;  Db.lbs.insert (   {     loc:{       type: "point",       coordinates: [113.332264, 23.156206]     },     name: "Guangzhou East railway Station"   } )  Db.lbs.insert (   {     loc:{       type: "point",       coordinates: [113.330611, 23.147234]     },     name: "Forest and West"   })  Db.lbs.insert (   {     loc:{       type: "point",       coordinates: [113.328095, 23.165376]     },     name: "Balance Stand"   })


2. Create a geo-index


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


3. Query for nearby coordinates
The current position is: Times Square,
Coordinate:


113.323568, 23.146436


Search nearby points within a kilometer, sorted by near to far


Db.lbs.find (   {     loc: {       $near: {         $geometry: {           type: ' point ',           coordinates: [113.323568, 23.146436]}         ,         $maxDistance: +}}   )


Search results:

The code is as follows:


{"_id": ObjectId ("556a651996f1ac2add8928fa"), "loc": {"type": "Point", "coordinates": [113.330611, 23.147234]}, " Name ":" Forest and West "}


The PHP code is as follows:


<?php//Connect MONGODB function conn ($dbhost, $dbname, $dbuser, $dbpasswd) {$server = ' mongodb://'. $dbuser. ': ' $dbpasswd. ' @ '. $dbhost. '   /'. $dbname;     try{$conn = new Mongoclient ($server);   $db = $conn->selectdb ($dbname); } catch (Mongoexception $e) {throw new errorexception (' Unable to connect to DB server. Error: '.   $e->getmessage (), 31); } return $db; }//Insert coordinates to MongoDB function add ($dbconn, $tablename, $longitude, $latitude, $name) {$index = array (' loc ' = ' 2dsphere ')   ; $data = Array (' loc ' = = Array (' type ' = ' = ' point ', ' coordinates ' = = Array (doubleval ($lon   Gitude), 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 nearby coordinates function query ($dbconn, $tablename, $longitude, $latitude, $maxdIstance, $limit =10) {$param = array (' loc ' = = Array (' $nearSphere ' = = Array (' $geometry ' = = A          Rray (' type ' = ' point ', ' coordinates ' = ' = ' Array (doubleval ($longitude), 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 ', ' 123456 ');   Randomly insert 100 coordinate records for ($i =0; $i <100; $i + +) {$longitude = ' 113.3 '. Mt_rand (10000, 99999);   $latitude = ' 23.15 '. Mt_rand (1000, 9999);   $name = ' name '. Mt_rand (10000,99999); Add ($db, ' lbs ', $longitude, $latitude, $name); }//Search for points within one kilometer $longitude = 113.323568; $latitude = 23.146436; $maxdistance = 1; $result = Query ($db, ' lbs ', $longitude, $latitude, $maxdistance); Print_r ($result);?>


To demonstrate PHP code, you first need to create users and execute auth in MongoDB's lbs. Here's how:


Use lbs; Db.createuser (   {     "user": "Root",     "pwd": "123456",     "roles": []   })  Db.auth (   {     "user ":" Root ",     " pwd ":" 123456 "   })



Calculate the distance from the two-point geographic coordinates
Function: Calculates the spherical distance between two points according to the latitude and longitude of pi and earth radius coefficients and coordinates of two points.


Get two point coordinate distance:


<?php/** * Calculates the distance between two points of geographic coordinates * @param decimal $longitude 1 beginning Longitude * @param decimal $latitude 1 beginning latitude * @param Decimal $longitude 2 Finish Longitude * @param Decimal $latitude 2 End latitude * @param Int $unit Unit 1: M 2: km * @param Int $decimal precision reserved decimal place * @return Decimal */function getdistance ($longitude 1, $latitude 1, $longitude 2, $latitude 2, $unit =2, $decimal =2) {$EARTH _radius = 6 370.996;  The radius coefficient of the earth $PI = 3.1415926;  $radLat 1 = $latitude 1 * $PI/180.0;  $radLat 2 = $latitude 2 * $PI/180.0;  $radLng 1 = $longitude 1 * $PI/180.0;  $radLng 2 = $longitude 2 * $PI/180.0;  $a = $radLat 1-$radLat 2;  $b = $radLng 1-$radLng 2;  $distance = 2 * ASIN (sqrt (Pow (sin ($a/2), 2) + cos ($radLat 1) * cos ($radLat 2) * POW (sin ($b/2), 2)));  $distance = $distance * $EARTH _radius * 1000;  if ($unit ==2) {$distance = $distance/1000; } return Round ($distance, $decimal);} Start coordinates $longitude1 = 113.330405; $latitude 1 = 23.147255;//end point coordinates $longitude2 = 113.314271; $latitude 2 = 23.1323; $distance = ge Tdistance ($longitude 1, $latitude 1, $lOngitude2, $latitude 2, 1); Echo $distance. ' m '; 2342.38m$distance = Getdistance ($longitude 1, $latitude 1, $longitude 2, $latitude 2, 2); Echo $distance. ' Km '; 2.34km?>




Summary : The above is the entire content of this article, I hope to be able to help you learn.

Related recommendations:

PHP uses curl to simulate the way to log in to the campus Renren

PHP simple way to implement Process control switch

Summary of methods for generating short URLs in PHP


Related Article

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.