Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Googlemaps search with mongodb geospatial best strategy

I have a website where people can view some places on a google map, which are stored with a lat/lng coordinate. The storage is mongodb. Now when the user navigates the map, I need to lookup up which places now are in the visible part of the map.

I'm new to mongo, but have looked at the spatial part. My question is now an effective way to do this lookup.

Do I need to make a ensureIndex each time the user navigates the map, and how do I then query all places within the visible boundaries of the map?

like image 338
Rasmus Christensen Avatar asked Feb 23 '23 07:02

Rasmus Christensen


1 Answers

According to the mongo docs, you can query within a bounding box like so

box = [[40.73083, -73.99756], [40.741404,  -73.988135]]
db.places.find({"loc" : {"$within" : {"$box" : box}}})

The key point here is the use of within to query within a bounding box.

In order to get the values for your box, just get the bounds of the google map like so

map.getBounds()

Where map is your google maps object. getBounds will return a LatLngBounds object from which you can build your box to query mongo.

As for ensureIndex, you should do that once as far as I know.

like image 167
omarello Avatar answered Mar 03 '23 16:03

omarello