2011-11-30 49 views
9

我想知道我的用户发送他的请求的当地时间。 基本上,会出现这样的事,作为这样的函数GPS位置到时区

var localTime = getLocalTime(lat, long); 

我不知道如果在LAT一个简单的划分可以工作,因为大多数国家不具备完美的几何形状。

任何帮助将是伟大的。任何语言都被接受。我想避免调用远程API。

+0

好吧,它涉及到一个远程API,但看看这个问题的答案。它可能会给你你想要的:http://stackoverflow.com/questions/41504/timezone-lookup-from-latitude-longitude。 –

回答

-3

难道你不能简单地使用用户IP来确定他们住在哪里?然后使用(Countries | Difference with GMT)数组获取当地时间。

2

我前几天在寻找同样的东西,不幸的是我找不到一个API或一个简单的函数。原因就像你所说的那样,国家没有完美的几何形状。您必须创建每个时区的区域表示并查看您的重点所在。我认为这将是一个痛苦,我不知道它是否可以完成。

我发现的唯一一个描述在这里:Determine timezone from latitude/longitude without using web services like Geonames.org。基本上你需要一个包含时区信息的数据库,并且你正在试图看看哪一个数据库与你的兴趣点最接近。

但是,我一直在寻找静态解决方案(不使用互联网),所以如果你可以使用互联网连接,你可以使用:http://www.earthtools.org/webservices.htm它提供了一个web服务给你的经纬度坐标的时区。

4

Google Time Zone API似乎是你所追求的。

时区API提供地球表面位置的时间偏移数据。请求特定纬度/经度对的时区信息将返回该时区的名称,与UTC的时差,以及夏令时偏移。

3

我今天刚刚面对同样的问题,我不确定我的答案在这段时间后的相关程度如何,但我基本上只是写了一个Python函数来实现你想要的。你可以在这里找到它。

https://github.com/cstich/gpstotz

编辑:

正如评论我也应该张贴代码中提到。该代码基于Eric Muller的时区shapefile,您可以在此获得 - http://efele.net/maps/tz/world/

编辑2:

事实证明shape文件有外部和内部环的有点陈旧定义(基本上外环使用右手法则,而内环使用左手定则)。在任何情况下,菲奥娜似乎都会照顾到这一点,我相应地更新了代码。

from rtree import index # requires libspatialindex-c3.deb 
from shapely.geometry import Polygon 
from shapely.geometry import Point 

import os 
import fiona 

''' Read the world timezone shapefile ''' 
tzshpFN = os.path.join(os.path.dirname(__file__), 
        'resources/world/tz_world.shp') 

''' Build the geo-index ''' 
idx = index.Index() 
with fiona.open(tzshpFN) as shapes: 
    for i, shape in enumerate(shapes): 
     assert shape['geometry']['type'] == 'Polygon' 
     exterior = shape['geometry']['coordinates'][0] 
     interior = shape['geometry']['coordinates'][1:] 
     record = shape['properties']['TZID'] 
     poly = Polygon(exterior, interior) 
     idx.insert(i, poly.bounds, obj=(i, record, poly)) 


def gpsToTimezone(lat, lon): 
    ''' 
    For a pair of lat, lon coordiantes returns the appropriate timezone info. 
    If a point is on a timezone boundary, then this point is not within the 
    timezone as it is on the boundary. Does not deal with maritime points. 
    For a discussion of those see here: 
    http://efele.net/maps/tz/world/ 
    @lat: latitude 
    @lon: longitude 
    @return: Timezone info string 
    ''' 
    query = [n.object for n in idx.intersection((lon, lat, lon, lat), 
               objects=True)] 
    queryPoint = Point(lon, lat) 
    result = [q[1] for q in query 
       if q[2].contains(queryPoint)] 

    if len(result) > 0: 
     return result[0] 
    else: 
     return None 

if __name__ == "__main__": 
    ''' Tests ''' 
    assert gpsToTimezone(0, 0) is None # In the ocean somewhere 
    assert gpsToTimezone(51.50, 0.12) == 'Europe/London' 
+0

您应在此处发布相关代码,而不是要求人员离开现场。与其他网站的链接可能会过时,并且无法通过SO搜索功能进行搜索。 –

+0

这很有道理,只是发布了代码。有没有办法将文件附加到答案? – cstich