Ruby gem for finding timezone of location

2019-01-08 15:46发布

问题:

I have a location (city, state), date, and time and I want to convert it to utc, but need to first find the timezone of the location. I've done a little research and everything seems to point to either earthtools or geonames but both webservices appear to be latitude and longitude only. Is there a service or gem or any other way to find the timezone based on this format of location? or how can the location be converted to latitude and longitude?

回答1:

You can easily get a latitude and longitude using the google maps geocoding API. There are ruby implementations for the API like GeoKit. Once you have that you can use the timezone gem to easily get the timezone of a latitude and longitude. The gem makes it easy to do time conversions in your timezone as well.

Here is an example using GeoKit and TimeZone.

require 'geokit'
require 'timezone'

res = Geokit::Geocoders::GoogleGeocoder.geocode('140 Market St, San Francisco, CA')
timezone = Timezone::Zone.new(:latlon => res.ll)

timezone.zone
=> "America/Los_Angeles"
timezone.time Time.now
=> 2011-12-01 14:02:13 UTC


回答2:

For the second part of the question, see the accepted answer to this question:

Determine timezone from latitude/longitude without using web services like Geonames.org

As stated in that answer, you should:

  • Download the database of cities from geonames.org
  • convert it to a compact lat/lon -> timezone list
  • use an R-Tree implementation to efficiently lookup the nearest city (or rather, its timezone) to a given coordinate

Keep in mind also that many U.S. states belong to a single time zone, which should make the job easier.



回答3:

You can make your own calls to a geolocation service, like Google Maps to translate City, State into latitude and longitude. There are also open database seeds that will give you latitude and longitudes for cities around the world. You could make a location model and seed that table with one of those.

Here is one place you can download geolocation data for free: http://www.maxmind.com/app/geolitecity



回答4:

Check this gem: https://github.com/sck-v/google_timezone

It uses google timezone api to determine timezone by known latitude and longitude



回答5:

Check the Gist at https://gist.github.com/4676207 for a version that uses Google's API (https://developers.google.com/maps/documentation/timezone/). Together with the Geocoder gem you can easily find all timezone ids :)