简体   繁体   中英

How to fetch location from mongodb based on latitude and longitude using Laravel eloquent?

I am using Moloquent model for fetching data from MongoDB in Laravel.

Everything was fine except getting data based on latitude and longitude. This is how my collection looks:

{
   "_id" : "some_id",
   "place_id" : "353789030392849490",
   "latitude": "22.5726",
   "longitude" : "88.3639"
}

In MySQL and Laravel Eloquent, we can fetch data using latitude and longitude like this:

DB:select("SELECT id, (
    6371 * acos( cos( radians(37) ) * cos( radians( lat ) ) 
    * cos( radians( long ) - radians(-122) )
    + sin( radians(37) ) * sin(radians(lat)) )
) AS distance 
FROM myTable
HAVING distance < 50
ORDER BY distance")->get();

Can I do the same using Laravel Eloquent to fetch data from MongoDB? Or do I need to do it in some other way?

PS. I am new to MongoDB.

You can do it like the following as stated in the README.md of laravel-mongodb :

$users = User::where('location', 'near', [
    '$geometry' => [
        'type' => 'Point',
        'coordinates' => [
            -0.1367563,
            51.5100913,
        ],
    ],
    '$maxDistance' => 50,
]);

NOTE: Specify coordinates in this order: longitude, latitude.

Your collection should have a 2dsphere index: https://docs.mongodb.com/manual/core/2dsphere/

An example of a collection:

{
    loc : { type: "Point", coordinates: [ -73.97, 40.77 ] },
    name: "Central Park",
    category : "Parks"
}

For more information about the $near : https://docs.mongodb.com/manual/core/2dsphere/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM