Laravel-mongodb: Storing Geodata

Created on 28 Nov 2014  路  6Comments  路  Source: jenssegers/laravel-mongodb

Tried hunting for this without much success so help me if you can.

I want to store Geodata specifically a geojson point. What's the best way to go about that?

Most helpful comment

You just have to save your data in the GeoJSON format (specification here : http://geojson.org/geojson-spec.html). For a simple point, it is just something like that :

$event->location = ['type' => 'Point', 'coordinates' => [100.0, 0.0];
$event->save();

If you want to perform geospatial requests you have to create the index in a migration :

Schema::collection('events', function ($table) {
    $table->index(['location' => '2dsphere']);
});

And then you can do :

$query->where('location', 'near', [
    '$geometry' => ['type' => 'Point', 'coordinates' => [101.54, 0.43],
    '$maxDistance' => 200,
]);

All 6 comments

There is no specific support for geodata in this library, but you can still use the original MongoDb methods to do special stuff.

You just have to save your data in the GeoJSON format (specification here : http://geojson.org/geojson-spec.html). For a simple point, it is just something like that :

$event->location = ['type' => 'Point', 'coordinates' => [100.0, 0.0];
$event->save();

If you want to perform geospatial requests you have to create the index in a migration :

Schema::collection('events', function ($table) {
    $table->index(['location' => '2dsphere']);
});

And then you can do :

$query->where('location', 'near', [
    '$geometry' => ['type' => 'Point', 'coordinates' => [101.54, 0.43],
    '$maxDistance' => 200,
]);

Thanks a bunch guys. Working great.

It takes time to find this information. I think it should be in the documentation ;) Thanks for the info :+1:

But in the migration wich type of data i need to set as column type?

@anodal88 column type ? That doesn't exist in MongoDB !

Was this page helpful?
0 / 5 - 0 ratings

Related issues

yupangestu picture yupangestu  路  3Comments

ricardofontanelli picture ricardofontanelli  路  3Comments

geofflancaster picture geofflancaster  路  3Comments

phuocduy1988 picture phuocduy1988  路  3Comments

sanjay1688 picture sanjay1688  路  3Comments