通过python获取你的位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24906833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:27:01  来源:igfitidea点击:

Get your location through python

pythongeolocation

提问by Stacker-flow

Is there anyway that I can get the location of my device through python. Currently I am having to use selenium and open up a browser, use a location service website and setting the result of that to variables for lat/long.

无论如何我可以通过python获取我的设备的位置。目前我不得不使用 selenium 并打开浏览器,使用位置服务网站并将其结果设置为纬度/经度的变量。

But is there an easier way to do this?

但是有没有更简单的方法来做到这一点?

UPDATE: I am using a 3G dongle on my RaspberryPi, so looking for a way to get the specific lat/long of it - I can successfully do this through web service, just wondering if there is a quicker way built into python for these requests?

更新:我在我的 RaspberryPi 上使用 3G 加密狗,所以正在寻找一种方法来获取它的特定纬度/经度 - 我可以通过网络服务成功地做到这一点,只是想知道是否有一种更快的方法内置到 python 中来处理这些请求?

采纳答案by JishnuM

Update: This API endpoint is deprecatedand will stopworking on July 1st, 2018. For more information please visit: https://github.com/apilayer/freegeoip#readme"

更新:此API端点被弃用,并且将停止在7月1日,2018年欲了解更多信息,请访问工作:https://github.com/apilayer/freegeoip#readme

Assumptions:

假设:

The device for which location is being sought is the one running the Python You have Internet access (seems fair since you mention a location service website)

正在寻找位置的设备是运行 Python 的设备 您可以访问 Internet(因为您提到了一个位置服务网站,这似乎很公平)

In such a case, there are services similar to the one linked in the comment where the IP of the request is used to generate the location. For example, http://freegeoip.net/.

在这种情况下,有些服务类似于评论中链接的服务,其中请求的 IP 用于生成位置。例如,http://freegeoip.net/

import requests
import json

send_url = 'http://freegeoip.net/json'
r = requests.get(send_url)
j = json.loads(r.text)
lat = j['latitude']
lon = j['longitude']

Drawbacks

缺点

Only IP is used to generate location.

仅使用 IP 来生成位置。

回答by user1116928

Here's a Python Geocoding Module that has GeoFreeIP

这是一个具有 GeoFreeIP 的 Python 地理编码模块

Example: http://geocoder.readthedocs.io/

示例:http: //geocoder.readthedocs.io/

$ pip install geocoder

Using CLI

使用命令行界面

$ geocode '99.240.181.199' --provider freegeoip --pretty --json

Using Python

使用 Python

>>> import geocoder
>>> g = geocoder.freegeoip('99.240.181.199')
<[OK] Freegeoip - Geocode [Ottawa, Ontario Canada]>
>>> g.json

回答by Kuba Jeziorny

@JishnuM answered the questions marvelously.

@JishnuM 出色地回答了这些问题。

2 cents from me. You don't really need to import json library.

给我 2 美分。你真的不需要导入 json 库。

You can go as follows:

您可以按照以下方式进行:

freegeoip = "http://freegeoip.net/json"
geo_r = requests.get(freegeoip)
geo_json = geo_r.json()

user_postition = [geo_json["latitude"], geo_json["longitude"]]

print(user_postition)

回答by Ben Dowling

Others have mentioned a few services, but another one to consider is my own, https://ipinfo.io, which'll give you latitude, longitude and a bunch of other information:

其他人提到了一些服务,但另一个需要考虑的是我自己的https://ipinfo.io,它会给你纬度、经度和一堆其他信息:

Usage for Bash:

用于 Bash:

$ curl ipinfo.io
{
  "ip": "24.6.61.239",
  "hostname": "c-24-6-61-239.hsd1.ca.comcast.net",
  "city": "Mountain View",
  "region": "California",
  "country": "US",
  "loc": "37.3845,-122.0881",
  "org": "AS7922 Comcast Cable Communications, LLC",
  "postal": "94040"
}

If you only want the coordinate data you can get just that by requesting /loc:

如果您只想要坐标数据,您可以通过请求获得/loc

$ curl ipinfo.io/loc
37.3845,-122.0881

See https://ipinfo.io/developersfor more details.

有关更多详细信息,请参阅https://ipinfo.io/developers

回答by Apollo_LFB

been playing around with this, so thanks to all for the useful answers in this thread (and SO in general!) thought I'd share my short program in case anyone wants to see it in combination with great circle calc

一直在玩这个,所以感谢所有人在这个线程中提供有用的答案(以及一般情况下!)我想我会分享我的短程序,以防有人想看到它与 Great circle calc 结合使用

import geocoder

import requests
freegeoip = "http://freegeoip.net/json"
geo_r = requests.get(freegeoip)
geo_json = geo_r.json()

address=input('enter an address: ')
g= geocoder.google(address)
lat_ad=g.latlng[0]
lon_ad=g.latlng[1]

user_postition = [geo_json["latitude"], geo_json["longitude"]]
lat_ip=user_postition[0]
lon_ip=user_postition[1]

#Calculate the great circle distance between two points on the earth (specified in decimal degrees)

from math import radians, cos, sin, asin, sqrt
# convert decimal degrees to radians 
lon_ad, lat_ad, lon_ip, lat_ip = map(radians, [lon_ad, lat_ad, lon_ip, lat_ip])

# haversine formula 
dlon = lon_ip - lon_ad 
dlat = lat_ip - lat_ad 
a = sin(dlat/2)**2 + cos(lat_ad) * cos(lat_ip) * sin(dlon/2)**2
c = 2 * asin(sqrt(a)) 
km = 6367 * c
#end of calculation

#limit decimals
km = ('%.0f'%km)

print(address+' is about '+str(km)+' km away from you')

回答by Apollo_LFB

or, as simple as this

或者,就这么简单

import geocoder
g = geocoder.ip('me')
print(g.latlng)

回答by Jonathan

With the ipdata.coAPI

使用ipdata.coAPI

This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signupfor your own Free API Key and get up to 1500 requests daily for development.

这个答案使用了一个非常有限的“测试”API 密钥,仅用于测试几个调用。注册您自己的免费 API 密钥,每天最多可收到 1500 个开发请求。

import requests
r = requests.get('https://api.ipdata.co?api-key=test').json()
r['country_name']
# United States

回答by Aashish

Since http://freegeoip.net/jsonAPI endpoint is deprecated and will stop working on July 1st, 2018. So, they release new API http://api.ipstack.com.

由于http://freegeoip.net/jsonAPI 端点已弃用,并将于 2018 年 7 月 1 日停止工作。因此,他们发布了新的 API http://api.ipstack.com

So, you may try out this with new API:

所以,你可以用新的 API 来试试这个:

import requests
import json

send_url = "http://api.ipstack.com/check?access_key=YOUR_ACCESS_KEY"
geo_req = requests.get(send_url)
geo_json = json.loads(geo_req.text)
latitude = geo_json['latitude']
longitude = geo_json['longitude']
city = geo_json['city']

In order to get your own ACCESS_KEY, you have to first create an account on ipstack.comwhich is free at https://ipstack.com/signup/free.

为了获得您自己的ACCESS_KEY,您必须首先ipstack.comhttps://ipstack.com/signup/free创建一个免费帐户。

Along with latitude, longitudeand city; you can also fetch zip, continent_code, continent_name, country_code, country_name, region_code, region_name.

随着latitude,longitudecity; 您还可以获取zip, continent_code, continent_name, country_code, country_name, region_code, region_name

Limitation: Free account only allow you 10,000 requests/month. If you requirement is more then you can upgrade you account.

限制:免费帐户仅允许您每月 10,000 个请求。如果您的要求更多,那么您可以升级您的帐户。

For more information about this new API you can visit at https://github.com/apilayer/freegeoip

有关此新 API 的更多信息,您可以访问https://github.com/apilayer/freegeoip

Reference: @JishnuM answer

参考:@JishnuM 答案

回答by Joel Jogy

Location based on IP address gives only location for your server. To find location based on where your current location is, you would need to give the browser access to location. This can be done using selenium.

基于 IP 地址的位置仅为您的服务器提供位置。要根据您当前所在的位置查找位置,您需要授予浏览器访问位置的权限。这可以使用硒来完成。

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait

def getLocation():
    chrome_options = Options()
    chrome_options.add_argument("--use-fake-ui-for-media-stream")
    timeout = 20
    driver = webdriver.Chrome(chrome_options=chrome_options)
    driver.get("https://mycurrentlocation.net/")
    wait = WebDriverWait(driver, timeout)
    longitude = driver.find_elements_by_xpath('//*[@id="longitude"]')
    longitude = [x.text for x in longitude]
    longitude = str(longitude[0])
    latitude = driver.find_elements_by_xpath('//*[@id="latitude"]')
    latitude = [x.text for x in latitude]
    latitude = str(latitude[0])
    driver.quit()
    return (latitude,longitude)
print getLocation()

A tutorial on how to do it is hereor find the GitHub repo here

如何做到这一点的指南是在这里还是找到GitHub库在这里

回答by amra

The freegoip.net and the api.ipstack.com endpoints appear to use the location of the internet service provider (ISP), not the location of my device. I tried curl http://api.ipstack.com/check?access_key=YOUR_KEY, and what I got was

freegoip.net 和 api.ipstack.com 端点似乎使用互联网服务提供商 (ISP) 的位置,而不是我设备的位置。我试过 curl http://api.ipstack.com/check?access_key=YOUR_KEY,我得到的是

{"ip":"106.51.151.31","type":"ipv4","continent_code":"AS","continent_name":"Asia","country_code":"IN","country_name":"India","region_code":"KA","region_name":"Karnataka","city":"Bengaluru","zip":"560008","latitude":12.9833,"longitude":77.5833,"location":{"geoname_id":1277333,"capital":"New Delhi","languages":[{"code":"hi","name":"Hindi","native":"\u0939\u093f\u0928\u094d\u0926\u0940"},{"code":"en","name":"English","native":"English"}],"country_flag":"http:\/\/assets.ipstack.com\/flags\/in.svg","country_flag_emoji":"\ud83c\uddee\ud83c\uddf3","country_flag_emoji_unicode":"U+1F1EE U+1F1F3","calling_code":"91","is_eu":false}}

Checking the location lat, long on Google maps indicates that this is the location of the service provider, not the location of the server/device.

检查 Google 地图上的 lat, long 位置表明这是服务提供商的位置,而不是服务器/设备的位置。

This solution is still usable, but probably only to a granularity of a city or country, based on how the ISP organises and locates its gateways.

此解决方案仍然可用,但可能仅适用于城市或国家/地区的粒度,具体取决于 ISP 组织和定位其网关的方式。