How to get latitude and longitude for a timezon database name (tzinfo)?

191 views Asked by At

My web app has a need to very roughly locate the user in order to calculate sunset and sunrise times.

Since geolocation features necessarily ask the user for permission, I'm brainstorming other ways to get at the location in a way that is good enough for this application.

The timezone offset isn't enough, as

  • I need latitude as well and
  • the offset is often astronomically wrong by one or two hours.

Luckily, browsers can get at the tz database name (eg. Europe/Madrid) configured in the OS these days. Now it's just a question of getting the coordinates for the city in question.

Even though there are several services that give you a timezone for coordinates, I haven't seen the reverse and I couldn't find a library with coordinates either.

I could create my own from geolocation services, but this is a bit tedious and error-prone to do, so I'd first like to check if somebody has a better idea.

1

There are 1 answers

1
Matt Johnson-Pint On BEST ANSWER

The coordinates for most IANA time zones are in the zone.tab and zone1970.tab files that are part of the time zone database itself. You can find them in the official tzdata distribution, or view them in the unofficial GitHub repository.

That said, I don't think your idea is a going to work out they way you think it will. There are several parts of the world where a single time zone is in use that spans a wide longitudinal area. The best example is China, which has the IANA time zone id Asia/Shangahi and is at UTC+08:00. It is called "Beijing Time" and is in use across the entire country (approximately 5,000 kilometers wide), except for areas that unofficially observe "Xinjiang Time" (more on this on Wikipedia here). This can create a sunrise/sunset difference of up to 4 hours between the eastern and western parts of the country, depending on time of year.

For sunrise/sunset calculations, your best bet is to use geolocation APIs to get lat/lon coordinates, calculate results for that position in UTC, then convert to the desired time zone.

In the case where the user denies permission for geolocation, you can fallback to using the IP address. There are many services to choose from, both free and commercial. Search for "IP Geolocation API" in your favorite search engine to find them. Of course, they will only be as accurate as the data, and you'll have erroneous lookups in some cases such as when VPNs are in use.