关闭

分享一段mysql,mongodb 实现LBS搜索的简单代码

标签: mongodblbsmysql搜索
357人阅读 评论(0) 收藏 举报
分类:
#仅支持myisam

CREATETABLE address (
 
    addressCHAR(80)NOTNULL,
 
    address_loc POINT NOTNULL,
 
    PRIMARYKEY(address)
 
);

ALTERTABLE address ADDSPATIAL INDEX(address_loc);

INSERTINTO address VALUES('Foobar street 12', GeomFromText('POINT(30.620076 104.067221)'));
 
INSERTINTO address VALUES('Foobar street 13', GeomFromText('POINT(31.720076 105.167221)'));

查询10公里内的
SELECT *
    FROM   address
    WHERE  MBRContains
                    (
                    LineString
                            (
                            Point
                                    (
                                    30.620076 + 10 / ( 111.1 / COS(RADIANS(104.067221))),
                                    104.067221 + 10 / 111.1
                                    ),
                            Point
                                    (
                                    30.620076 - 10 / ( 111.1 / COS(RADIANS(104.067221))),
                                    104.067221 - 10 / 111.1
                                    )
                            ),
                    address_loc
<?php
$m = new MongoClient();
$d = $m->user;
$r = $d->command(array(
    'geoNear' => "user",       // 在 poiConcat 集合中
    'near' => array(104.065847, 30.657554), // 经纬度附近
    'spherical' => true,              // 启用特殊搜索 弧度
    'maxDistance' => 1.5/6371,              // 搜索区域
    'distanceMultiplier' => 6371,           // 返回公里数,自动转换
    'num' => 5,                             // 最多返回5个文档
));
print_r($r);

                    )

MongoDb

1、先建立一张简单的集合user,两条数据如下:

{
  "_id": ObjectId("518b1f1a83ba88ca60000001"),
  "account":"simplephp1@163.com",
  "gps": [
    104.067221,
    30.620076
  ]
}
 
{
  "_id": ObjectId("518b1dae83ba88d660000000"),
  "account":"simplephp6@163.com",
  "gps": [
    104.07958,
    30.653936
  ]

db.user.ensureIndex({"gps":"2d"},{"min":-180,"max":180})

#查询5公里内的,只返回常规数据
db.user.find({ gps :{ $near : [104.065847, 30.657554] , $maxDistance : 5/111.12} })
#查询5公里内的,且返回距离
db.runCommand({ geoNear : "user", near : [104.065847, 30.657554], spherical : true, maxDistance : 5/6371, distanceMultiplier: 6371})

#php实现


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:6653次
    • 积分:147
    • 等级:
    • 排名:千里之外
    • 原创:8篇
    • 转载:3篇
    • 译文:0篇
    • 评论:0条
    文章分类