`
lzqustc
  • 浏览: 206640 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

MongoDB开发LBS应用

阅读更多

随着近几年各类移动终端的迅速普及,基于地理位置的服务(LBS)和相关应用也越来越多,而支撑这些应用的最基础技术之一,就是基于地理位置信息的处理。

关于LBS的详细介绍及通用的几个解决方案,可以参考:深入浅出Symfony2 - 结合MongoDB开发LBS应用

 

本文主要举例说明使用Perl语言 + MongoDB实现查找附近的人的实现方案。

涉及的官方API说明文档列表:

1、2dsphere Indexes

2、GeoJSON Objects

3、$geoNear (aggregation)

 

实现步骤如下:

1、建立数据库表geoperson,包含位置信息字段:loc (按照GeoJSON格式组织), 数据如下:

{

    "_id": "o15041420964119780063",

    "name": "stephen",

    "head_fid": "f15022500199301140308001",

    "loc": {

        "type": "Point",

        "coordinates": [

            119.29647,

            26.07421

        ]

    },

    "type": "geoperson",

    "province": "福建省"

}

 

2、建立2dsphere索引

my $mocl = mdb()->get_collection("geoperson")->ensure_index({loc=>"2dsphere"});

 

3、查找附近2.5公里的人

my $rad = 2500; # 查找范围 2.5公里

my $max_size = 20; # 最多返回20条匹配数据

my $longitude = 119.31647;  # 中心点坐标(经纬度)

my $latitude = 26.17421;

my $mocl = mdb()->get_collection("geoperson")->aggregate([

                    {

                        '$geoNear'=>{

                                'near'=> { type=>"Point", coordinates=>[$longitude, $latitude] }, # 也要采取GeoJSON格式

                                #'num'=> $max_size,#The default value is 100

                                'spherical'=>1, #Required if using a 2dsphere index.

                                # Specify the distance in meters if the specified point is GeoJSON

                                'maxDistance'=>$rad, # 单位是米

                                # The output field that contains the calculated distance.

                                'distanceField'=>"distance",

                       }

                   },

                   { '$match'=> { "name"=> "lily" } }  # 进一步过滤条件

                   { '$sort'=> { "ut"=> -1 } }  # 排序

         ]);

 

 

MongoDB原生支持地理位置索引,且高性能、支持复杂查询。

是不是很简单呀。

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics