2

I have a collection of documents with a geospatial index location: {lat:XX.XXXX, lng:XX.XXXX}. But I would like them to be outputted by TimeZone.

I was thinking of converting geolocation to Timezone, and have an index based on that, but I'm not sure how to do that either, or if it'll be easier to use the geospatial index anyway.

Mr. Demetrius Michael
  • 2,326
  • 5
  • 28
  • 40
  • The solution depends on how you need to order your timezones. If it is just the usual east-to-west (or vice versa) then my answer below using offsets from UTC should help. If you need to do DST adjustments it gets a little bit more complicated: you can either update your TZ collection or create multiple documents for each TZ with a start/end date range & the corresponding UTC offset. You can first filter based on the current time and then you'll have the correct (DST adjusted) TZ order. – Sim Apr 08 '13 at 02:56
  • @Sim - See also [this community wiki entry](http://stackoverflow.com/q/16086962/634824) – Matt Johnson-Pint Apr 18 '13 at 16:12

2 Answers2

2

MongoDB can perform checks for inclusion of a point in an arbitrary polygon described in GeoJSON using $geoWithin query criteria. You can create a new collection of timezone documents with their location polygons in GeoJSON. For that, try this GitHub repo. My answer to this related SO question could also be useful.

Once you have the timezone collection you can pre-calculate the TZ, store it in your documents and index it for faster queries. You'll need to come up with an ordering for the timezones. Offsets from UTC could be a good starting point.

Community
  • 1
  • 1
Sim
  • 13,147
  • 9
  • 66
  • 95
0

The excellent answer Sim provided will let you do it all in your own code - but it does require a bit of overhead. If you just want to resolve the locations to time zones, and don'y mind calling an external service, you can use Google's Time Zone API.

See also this related question and its answers.

Community
  • 1
  • 1
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • I'm sorry but how is calling an external API over the wire not overhead? And what about the complexity of handling edge cases such as networking problems or dealing with the cases when the API is not available for one reason or another? – Sim Apr 11 '13 at 06:44
  • @Sim - I think either solution is valid, it just depends on your scenario. For some, dealing with the spatial data isn't worth it. They may only have a limited number of lookups. Perhaps they can resolve the time zone when the document is submitted and just store that instead. In general, I do agree with your solution though. I actually wrote [an implementation of this for RavenDB](https://github.com/mj1856/Raven.TimeZones) not too long ago. :) – Matt Johnson-Pint Apr 11 '13 at 14:59
  • Sure, it's the definition of "overhead" that caught my eye. – Sim Apr 13 '13 at 04:31