首页 > 技术文档 > 技术文档 > mongdb的lbs位置查询的php语法

mongdb的lbs位置查询的php语法

时间:2016-7-1 已查看2121次

# 插入数据 lng对应经度  lat对应纬度 均为float型

db.collection.insert({location:[lng,lat],title:'test title'})

# 创建2D空间索引

# 2dsphere支持球面检索  2d二维空间搜索

db.collection.ensureIndex({location:'2dsphere'})

# 按照半径搜索 搜索半径内的所有的点 按照由近到远排序

db.collection.find(

    {

        location:

        {

            $geoWithin:

            {

                $centerSphere: [ [lng, lat], 检索半径]

            }

        }

    }

)

# 搜索全部数据 按照由近到远排序

db.collection.find(

    {

        location:

        {

            $near:

            [lng, lat]

        }

    }

)

搜索出的结果已经是由远到近排序了,如果需要输出距离计算。$geoNear搜索返回的数据中已有distance(距离),不过不支持其他命令,如limit



php代码:

// 搜寻附近的坐标  

function query($dbconn, $tablename, $longitude, $latitude, $maxdistance, $limit=10){  

    $param = array(  

        'location' => array(  

            '$geoWithin' => array(  

                '$geometry' => array(  

                    'centerSphere' => array(array(doubleval($longitude), doubleval($latitude)),$maxdistance/111),   

                )

            )  

        )  

    );  

  

    $coll = $dbconn->selectCollection($tablename);  

    $cursor = $coll->find($param);  

    $cursor = $cursor->limit($limit);  

      

    $result = array();  

    foreach($cursor as $v){  

        $result[] = $v;  

    }    

  

    return $result;  

}  


上一篇:php利用stream_socket_server与stream_socket_client 下一篇:php下的mongodb地理位置搜寻