给定一个位置的经度和纬度,如何知道该位置的有效时区?

在大多数情况下,我们正在寻找IANA/Olson时区id,尽管有些服务可能只返回UTC偏移量或其他一些时区标识符。详细信息请阅读时区标签信息。


当前回答

There are several sources online that have geojson data for timezones (here's one, here's another) Use a geometry library to create polygon objects from the geojson coordinates (shapely [python], GEOS [c++], JTS [java], NTS [.net]). Convert your lat/lng to a point object (however your library represents that) and check if it intersects the timezone polygon. from shapely.geometry import Polygon, Point def get_tz_from_lat_lng(lat, lng): for tz, geojson in timezones.iteritems(): coordinates = geojson['features'][0]['geometry']['coordinates'] polygon = Polygon(coordinates) point = Point(lng, lat) if polygon.contains(point): return tz

其他回答

It's indeed important to recognize that this a more complicated problem than most would suspect. In practice many of us are also willing to accept a working set of code that works for "as many cases as possible", where at least its fatal issues can be identified and minimized collectively. So I post this with all of that and the spirit of the OP in mind. Finally, for practical value to others who are trying to convert GPS to timezone with the end goal of having a location-sensitive time object (and more importantly to help advance the quality of average implementations with time objects that follow from this wiki) here is what I generated in Python (please feel free to edit):

import pytz
from datetime import datetime
from tzwhere import tzwhere

def timezoned_unixtime(latitude, longitude, dt):
    tzw = tzwhere.tzwhere()
    timezone_str = tzw.tzNameAt(latitude, longitude)
    timezone = pytz.timezone(timezone_str)
    timezone_aware_datetime = timezone.localize(dt, is_dst=None)
    unix_time = (timezone_aware_datetime - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()
    return unix_time

dt = datetime(year=2017, month=1, day=17, hour=12, minute=0, second=0)
print timezoned_unixtime(latitude=40.747854, longitude=-74.004733, dt=dt)

时区位置Web服务

谷歌映射时区API 必应地图时区API Azure地图时区API GeoNames时区API TimeZoneDB API AskGeo -商业(但可以说比GeoNames更准确) 地理车库时区API -商业,专注于航海时区。

原始时区边界数据

Timezone Boundary Builder -从OpenStreetMaps地图数据中构建时区形状文件。包括海岸线附近的领海。

以下项目以前是时区边界数据的来源,但不再积极维护。

tz_world -来自Eric Muller的原始shapefile数据 whereonearth-timezone - GeoJSON版本与WOEDB数据合并

时区地理定位离线实现

使用时区边界生成器数据的实现

node-geo-tz - JavaScript library (Node.js only) timespace - JavaScript library tz-lookup-oss - JavaScript library GeoTimeZone - .NET library Geo-Timezone - PHP library timezonefinder - Python library ZoneDetect - C library Timeshape - Java library TimeZoneMap - Java and Android library lutz - R library go-tz - Go library Timezone lookup - Go library docker-timezone-lookup - docker container wrapping node-geo-tz tzf - Go library tzfpy - Python port of tzf library tzf-rs - Rust port of tzf library

使用较旧的tz_world数据的实现

latlong - Go库(也可以阅读这篇文章)。 TimeZoneMapper - Java库 tzwhere - JavaScript/节点库 pytzwhere - Python库 timezone_finder - Ruby库 LatLongToTimeZone - Java和Swift库 现在几点了?-描述PHP和MongoDB的博客文章 rundel/timezone - R库

调用其中一个web服务的库

timezone -调用GeoNames的Ruby宝石 AskGeo有自己的库,用于从Java或。net进行调用 GeoNames拥有几乎所有东西的客户端库

自托管web服务

geo2tz -基于时区查找,可通过Docker image获得

其他的想法

找到最近有R-Tree的城市 用MySQL找到最近的城市

如果您知道其他名单,请更新此名单

此外,请注意,最近的城市方法可能不会产生“正确”的结果,只是一个近似值。

转换到Windows区域

列出的大多数方法都将返回IANA时区id。如果您需要转换为Windows时区,以便与。net中的TimeZoneInfo类一起使用,请使用TimeZoneConverter库。

不要使用zone.tab

tz数据库包含一个名为zone.tab的文件。该文件主要用于显示时区列表,供用户从中选择。它包括每个时区参考点的纬度和经度坐标。这允许创建一个突出显示这些点的地图。例如,查看moment-timezone主页上显示的交互式地图。

虽然使用这些数据从纬度和经度坐标解析时区可能很诱人,但请考虑这些是点,而不是边界。最好的办法是确定最近的点,但在许多情况下,这并不是正确的点。

考虑下面的例子:

                           

这两个方格表示不同的时区,其中每个方格中的黑点是参考位置,例如在zone.tab中可以找到的位置。蓝点表示我们试图为其寻找时区的位置。显然,这个位置位于左侧的橙色区域内,但如果我们只看距离参考点最近的距离,它将解析为右侧的绿色区域。

There are several sources online that have geojson data for timezones (here's one, here's another) Use a geometry library to create polygon objects from the geojson coordinates (shapely [python], GEOS [c++], JTS [java], NTS [.net]). Convert your lat/lng to a point object (however your library represents that) and check if it intersects the timezone polygon. from shapely.geometry import Polygon, Point def get_tz_from_lat_lng(lat, lng): for tz, geojson in timezones.iteritems(): coordinates = geojson['features'][0]['geometry']['coordinates'] polygon = Polygon(coordinates) point = Point(lng, lat) if polygon.contains(point): return tz

对于我们这些使用Javascript并希望通过谷歌api从邮政编码获取时区的人来说,这里有一个方法。

通过地理定位获取lat/lng 通过这个参数获取时区 进入时区API。 此处使用Luxon进行时区转换。

注意:我的理解是,邮政编码在不同的国家并不是唯一的,所以这可能最适合在美国使用。

const googleMapsClient; // instantiate your client here
const zipcode = '90210'
const myDateThatNeedsTZAdjustment; // define your date that needs adjusting
// fetch lat/lng from google api by zipcode
const geocodeResponse = await googleMapsClient.geocode({ address: zipcode }).asPromise();
if (geocodeResponse.json.status === 'OK') {
  lat = geocodeResponse.json.results[0].geometry.location.lat;
  lng = geocodeResponse.json.results[0].geometry.location.lng;
} else {
  console.log('Geocode was not successful for the following reason: ' + status);
}

// prepare lat/lng and timestamp of profile created_at to fetch time zone
const location = `${lat},${lng}`;
const timestamp = new Date().valueOf() / 1000;
const timezoneResponse = await googleMapsClient
  .timezone({ location: location, timestamp: timestamp })
  .asPromise();

const timeZoneId = timezoneResponse.json.timeZoneId;
// adjust by setting timezone
const timezoneAdjustedDate = DateTime.fromJSDate(
  myDateThatNeedsTZAdjustment
).setZone(timeZoneId);

function jsonpRequest(url, data) { let params = ""; for (let key in data) { if (data.hasOwnProperty(key)) { if (params.length == 0) { params += "?"; } else { params += "&"; } let encodedKey = encodeURIComponent(key); let encodedValue = encodeURIComponent(data[key]); params += encodedKey + "=" + encodedValue; } } let script = document.createElement('script'); script.src = url + params; document.body.appendChild(script); } function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } } let lat_ini=[]; let lon_ini=[]; function showPosition(position) { lat_ini= position.coords.latitude; lon_ini= position.coords.longitude; } ////delay time between lines function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } /////// function getGMT() { getfinalGMT() getLocation() async function sample() { await sleep(2000); let lat_str=lat_ini.toString(); let lng_str=" "+lon_ini.toString(); let url = "https://api.opencagedata.com/geocode/v1/json"; let data = { callback: "displayGMT", q: lat_str + lng_str, key: "fac4471073a347019196c1291e6a97d7" } jsonpRequest(url, data) } sample(); } let your_GMT=[]; function displayGMT(data) { your_GMT=(Number(data.results[0].annotations.timezone.offset_string)) console.log(your_GMT) } ///// function getfinalGMT() { let lat=document.getElementById("lat_id").value; let lng=document.getElementById("lng_id").value; let lat_str=lat.toString(); let lng_str=" "+lng.toString(); let url = "https://api.opencagedata.com/geocode/v1/json"; let data = { callback: "displayfinalGMT", q: lat + lng_str, key: "fac4471073a347019196c1291e6a97d7" } jsonpRequest(url, data) } let final_GMT=[]; function displayfinalGMT(data) { final_GMT=(Number(data.results[0].annotations.timezone.offset_string)) console.log(final_GMT) } /////clock const hourHand = document.querySelector('[data-hour-hand]') const minuteHand = document.querySelector('[data-minute-hand]') const secondHand = document.querySelector('[data-second-hand]') let dif_overall=[]; function setClock() { let gmt_diff=Number(your_GMT-final_GMT)/100 if (gmt_diff>12){ dif_overall=gmt_diff-12 } else{ dif_overall=gmt_diff } console.log(dif_overall) const currentDate = new Date() const secondsRatio = currentDate.getSeconds() / 60 const minutesRatio = (secondsRatio + currentDate.getMinutes()) / 60 const hoursRatio = (minutesRatio + currentDate.getHours() - dif_overall ) / 12 setRotation(secondHand, secondsRatio) setRotation(minuteHand, minutesRatio) setRotation(hourHand, hoursRatio) } function setRotation(element, rotationRatio) { element.style.setProperty('--rotation', rotationRatio * 360) } function activate_clock(){ setClock() setInterval(setClock, 1000) } *, *::after, *::before { box-sizing: border-box; } body { background: linear-gradient(to right, hsl(200, 100%, 50%), hsl(175, 100%, 50%)); display: flex; justify-content: center; align-items: center; min-height: 100vh; overflow: hidden; } .clock { width: 200px; height: 200px; background-color: rgba(255, 255, 255, .8); border-radius: 50%; border: 2px solid black; position: relative; } .clock .number { --rotation: 0; position: absolute; width: 100%; height: 100%; text-align: center; transform: rotate(var(--rotation)); font-size: 1.5rem; } .clock .number1 { --rotation: 30deg; } .clock .number2 { --rotation: 60deg; } .clock .number3 { --rotation: 90deg; } .clock .number4 { --rotation: 120deg; } .clock .number5 { --rotation: 150deg; } .clock .number6 { --rotation: 180deg; } .clock .number7 { --rotation: 210deg; } .clock .number8 { --rotation: 240deg; } .clock .number9 { --rotation: 270deg; } .clock .number10 { --rotation: 300deg; } .clock .number11 { --rotation: 330deg; } .clock .hand { --rotation: 0; position: absolute; bottom: 50%; left: 50%; border: 1px solid white; border-top-left-radius: 10px; border-top-right-radius: 10px; transform-origin: bottom; z-index: 10; transform: translateX(-50%) rotate(calc(var(--rotation) * 1deg)); } .clock::after { content: ''; position: absolute; background-color: black; z-index: 11; width: 15px; height: 15px; top: 50%; left: 50%; transform: translate(-50%, -50%); border-radius: 50%; } .clock .hand.second { width: 3px; height: 45%; background-color: red; } .clock .hand.minute { width: 7px; height: 40%; background-color: black; } .clock .hand.hour { width: 10px; height: 35%; background-color: black; } /* Background Styles Only */ @import url('https://fonts.googleapis.com/css?family=Raleway'); * { font-family: Raleway; } .side-links { position: absolute; top: 15px; right: 15px; } .side-link { display: flex; align-items: center; justify-content: center; text-decoration: none; margin-bottom: 10px; color: white; width: 180px; padding: 10px 0; border-radius: 10px; } .side-link-youtube { background-color: red; } .side-link-twitter { background-color: #1DA1F2; } .side-link-github { background-color: #6e5494; } .side-link-text { margin-left: 10px; font-size: 18px; } .side-link-icon { color: white; font-size: 30px; } <input type="text" id="lat_id" placeholder="lat"><br><br> <input type="text" id="lng_id" placeholder="lng"><br><br> <button class="text" onClick="getLocation()">Location</button> <button class="text" onClick="getGMT()"> GMT</button> <button class="text" onClick="activate_clock()"> Activate</button> <div class="clock"> <div class="hand hour" data-hour-hand></div> <div class="hand minute" data-minute-hand></div> <div class="hand second" data-second-hand></div> <div class="number number1">1</div> <div class="number number2">2</div> <div class="number number3">3</div> <div class="number number4">4</div> <div class="number number5">5</div> <div class="number number6">6</div> <div class="number number7">7</div> <div class="number number8">8</div> <div class="number number9">9</div> <div class="number number10">10</div> <div class="number number11">11</div> <div class="number number12">12</div> </div>