[英]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. 我正在使用Moloquent模型从Laravel中的MongoDB获取数据。
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: 在MySQL和Laravel Eloquent中,我们可以使用纬度和经度来获取数据,如下所示:
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? 我可以使用Laravel Eloquent从MongoDB获取数据吗? Or do I need to do it in some other way?
还是我需要以其他方式做到这一点?
PS. PS。 I am new to MongoDB.
我是MongoDB的新手。
You can do it like the following as stated in the README.md
of laravel-mongodb : 您可以按照laravel-mongodb的README.md中所述的
README.md
进行操作 :
$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/ 您的集合应具有
2dsphere
索引: https : 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/ 有关
$near
更多信息: https : //docs.mongodb.com/manual/core/2dsphere/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.