Skip to main content
 首页 » 编程设计

python之在 Python 中获取用户的经纬度

2024年11月01日10傻小

我想在 python 中获取用户位置。我认为这在某种程度上是可能的,因为谷歌能够做到这一点(https://maps.google.com/ 点击方向键下方的圆圈)。

有人知道吗?

请您参考如下方法:

如果您想自己滚动,有些网站会以各种格式提供有关您的 IP 地址的信息。

http://ipinfo.io/json会给出这样的东西:

{ 
  "ip": "12.34.56.78", 
  "hostname": "XXXXX.com", 
  "city": "Saint-Lambert", 
  "region": "Quebec", 
  "country": "CA", 
  "loc": "45.5073,-73.5082", 
  "org": "AS577 Bell Canada", 
  "postal": "J4P" 
} 

正如 Joran 上面所说,这并不准确。我不在 Saint-Lambert,我在蒙特利尔,但距离不远。

您可以在 Python 中使用 urllib2.urlopen 获取它,然后使用 json 模块将其转换为字典。

import json 
import urllib2 
 
def location_lookup(): 
  try: 
    return json.load(urllib2.urlopen('http://ipinfo.io/json')) 
  except urllib2.HTTPError: 
    return False 
 
location = location_lookup() 
 
# print city and latitude/longitude 
print location['city'] + ' (' + location['loc'] + ')' 

对于上面的 JSON 输出,这段 Python 代码将给出

Saint-Lambert (45.5073,-73.5082)