MongoDB develops LBS application

With the rapid popularization of various mobile terminals in recent years, there are more and more location-based services (LBS) and related applications, and one of the most basic technologies supporting these applications is the processing of location-based information.

For a detailed introduction to LBS and several general solutions, you can refer to: Symfony2 - Developing LBS Applications with MongoDB

 

This article mainly illustrates the implementation of finding nearby people using Perl language + MongoDB .

List of official API documentation involved:

1、2dsphere Indexes

2、GeoJSON Objects

3、$geoNear (aggregation)

 

The implementation steps are as follows:

1. Create a database table geoperson, including the location information field: loc (organized in GeoJSON format) , the data is as follows:

{

    "_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原生支持地理位置索引,且高性能、支持复杂查询。

是不是很简单呀。

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326078749&siteId=291194637