Home  >  Article  >  Backend Development  >  mongodb location search

mongodb location search

WBOY
WBOYOriginal
2016-08-08 09:23:261082browse

LBS, stores the latitude and longitude coordinates of each location, searches for nearby locations, and establishes a geographical location index to improve query efficiency.

mongodb geographical location index, 2d and 2dsphere, corresponding to plane and sphere.

1. Create the coordinates of the lbs collection storage location

use lbs;

db.lbs.insert(
    {
        loc:{
            type: "Point",
            coordinates: [113.332264, 23.156206]
        },
        name: "广州东站"
    }
)

db.lbs.insert(
    {
        loc:{
            type: "Point",
            coordinates: [113.330611, 23.147234]
        },
        name: "林和西"
    }
)

db.lbs.insert(
    {
        loc:{
            type: "Point",
            coordinates: [113.328095, 23.165376]
        },
        name: "天平架"
    }
)

2. Create a geographical location index
db.lbs.ensureIndex(
    {
        loc: "2dsphere"
    }
)

3. Query nearby coordinates

The current location is: Times Square,

Coordinates: 113.323568, 23.146436

Search for points within one kilometer nearby, sort from nearest to far

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

Search results:
{ "_id" : ObjectId("556a651996f1ac2add8928fa"), "loc" : { "type" : "Point", "coordinates" : [ 113.330611, 23.147234 ] }, "name" : "林和西" }

php code is as follows:
<?php
// 连接mongodb
function conn($dbhost, $dbname, $dbuser, $dbpasswd){
    $server = &#39;mongodb://&#39;.$dbuser.&#39;:&#39;.$dbpasswd.&#39;@&#39;.$dbhost.&#39;/&#39;.$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;
}

// 插入坐标到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;
}

// 搜寻附近的坐标
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');

// 随机插入100条坐标纪录
for($i=0; $i<100; $i++){
    $longitude = &#39;113.3&#39;.mt_rand(10000, 99999);
    $latitude = &#39;23.15&#39;.mt_rand(1000, 9999);
    $name = &#39;name&#39;.mt_rand(10000,99999);
    add($db, &#39;lbs&#39;, $longitude, $latitude, $name);
}

// 搜寻一公里内的点
$longitude = 113.323568;
$latitude = 23.146436;
$maxdistance = 1;
$result = query($db, &#39;lbs&#39;, $longitude, $latitude, $maxdistance);
print_r($result);
?>

Demo php Code, first you need to create a user 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"
    }
)

The above introduces the mongodb geographical location search, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn