Home>

Geo searchlbs, storing the latitude and longitude coordinates of each place,Search for nearby places.Indexing geographic locations can improve query efficiency.

mongodb geolocation index,2d and 2dsphere, corresponding to planes and spheres.

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:"Lin Hexi"
  }
)
db.lbs.insert (
  {
    loc:{
      type:"point",      coordinates:[113.328095, 23.165376]
    },    name:"Balance Frame"
  }
)

2. Create a geographic index

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

3. Query nearby coordinates

The current position is:Times Square,

coordinate:

113.323568, 23.146436

Search for points within a kilometer nearby.Sort from near to far

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

Search results for:

</p>
<p>
{"_id":objectid ("556a651996f1ac2add8928fa"), "loc":{"type":"point", "coordinates":[113.330611, 23.147234]}, "name":"Lin Hexi"}
</p>
<p>

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 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 into mongodb
function add ($dbconn, $tablename, $longitude, $latitude, $name) {
  $index=array ("loc" =>"2dsphere");
  $data=array (
      "loc" =>array (
          "type" =>"point",          "coordinates" =>array (doubleval ($longitude), 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 coordinates
function query ($dbconn, $tablename, $longitude, $latitude, $maxdistance, $limit=10) {
  $param=array (
    "loc" =>array (
      "$nearsphere" =>array (
        "$geometry" =>array (
          "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 the php code, first you need to create a user and execute auth in the mongodb's lbs. Methods as below:

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

Calculate the distance between two points in geographic coordinatesFeature:Based on the pi and earth radius coefficient and the latitude and longitude of the two-point coordinate,Calculate the spherical distance between two points.

Get the coordinate distance of two points:

<?php
/**
 * Calculate the distance between two points of geographic coordinates
 * @param decimal $longitude1 longitude of starting point
 * @param decimal $latitude1 starting latitude
 * @param decimal $longitude2 end longitude
 * @param decimal $latitude2 end latitude
 * @param int $unit unit 1:meter 2:kilometers
 * @param int $decimal precision
 * @return decimal
 * /
function getdistance ($longitude1, $latitude1, $longitude2, $latitude2, $unit=2, $decimal=2) {
  $earth_radius=6370.996;//Earth radius factor
  $pi=3.1415926;
  $radlat1=$latitude1 * $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);
}
//starting point coordinates
$longitude1=113.330405;
$latitude1=23.147255;
//end coordinates
$longitude2=113.314271;
$latitude2=23.1323;
$distance=getdistance ($longitude1, $latitude1, $longitude2, $latitude2, 1);
echo $distance. "m";//2342.38m
$distance=getdistance ($longitude1, $latitude1, $longitude2, $latitude2, 2);
echo $distance. "km";//2.34km
?>
php
  • Previous Strcmp () and strcasecmp () function string comparison usage analysis in PHP
  • Next Java implementation verification code specific pictures (pictures, Chinese characters)