【问题标题】:How to access current location of any user using python [closed]如何使用python访问任何用户的当前位置[关闭]
【发布时间】:2014-09-14 10:07:36
【问题描述】:

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

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

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

【问题讨论】:

  • 查看这个问题/答案:stackoverflow.com/questions/2543018/…
  • 我不确定这是我正在寻找的,因为这是一个通用的 IP 发现 - 我想要精确到我的位置,就像移动地理位置一样。
  • 当您说“我的设备的位置”时,您指的是手机(或类似设备)还是台式电脑?
  • stackoverflow.com/questions/4070169/… 这个问题可能会有所帮助,但它看起来(通过快速谷歌搜索)看起来并不容易......
  • 这里有一些可能会有所帮助的更多信息 - 您需要先从设备获取 GSM 小区信息:stackoverflow.com/questions/10329877/…

标签: python geolocation


【解决方案1】:

或者,就这么简单

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

【讨论】:

    【解决方案2】:

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

    用于 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"
    }
    

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

    $ curl ipinfo.io/loc
    37.3845,-122.0881
    

    更多详情请见https://ipinfo.io/developers

    【讨论】:

    • 谢谢!您的答案比公认的(尽管很酷)答案更准确,后者有时会返回错误的大陆……
    • @peppa ... python 添加没有意义。如果这是一个答案,那么...将该部分作为答案发布,并在此处参考此答案,我将在“来自评论”中对您的编辑发表评论。
    【解决方案3】:

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

    所以,你可以用新的 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']
    

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

    连同latitudelongitudecity;你也可以获取zipcontinent_codecontinent_namecountry_codecountry_nameregion_coderegion_name

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

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

    参考:@JishnuM 答案

    【讨论】:

      【解决方案4】:

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

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

      $ pip install geocoder
      

      使用命令行

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

      使用 Python

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

      【讨论】:

        【解决方案5】:

        Ipregistry 返回当前 IP 地址或给定 IP 地址的位置数据以及货币、时区等(免责声明,我运行该服务)。 PyPI 上还有一个官方的 Python 客户端:

        $ pip install ipregistry
        
        from ipregistry import IpregistryClient
        
        client = IpregistryClient("tryout")  
        ipInfo = client.lookup() 
        print(ipInfo)
        

        与许多其他服务不同,Ipregistry 提供大量数据,包括运营商、公司,以及城市、纬度、经度、货币、时区等。所有这些都在一个快速的请求中完成。

        【讨论】:

        • 除了这给出了非常模糊的位置结果,现在它显示了我在另一个城市的位置,即 6 小时车程。投反对票。
        【解决方案6】:

        一直在玩这个,所以感谢所有在这个线程中有用的答案(以及一般情况下!)我想我会分享我的短程序,以防有人想看到它与大圆计算相结合

        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')
        

        【讨论】:

          【解决方案7】:

          使用ipdata.co API

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

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

          【讨论】:

            【解决方案8】:

            @JishnuM 精彩地回答了这些问题。

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

            你可以这样走:

            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)
            

            【讨论】:

              【解决方案9】:

              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}}
              

              在谷歌地图上查看 lat, long 表示这是服务提供商的位置,而不是服务器/设备的位置。

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

              【讨论】:

                【解决方案10】:

                我已经尝试了几个月来得到这个,最后我找到了一个适用于 Windows 用户的解决方案! 对我来说,它与街道名称一样接近。 你需要安装winrt(https://pypi.org/project/winrt/) 这里是:

                import winrt.windows.devices.geolocation as wdg, asyncio
                
                async def getCoords():
                        locator = wdg.Geolocator()
                        pos = await locator.get_geoposition_async()
                        return [pos.coordinate.latitude, pos.coordinate.longitude]
                    
                def getLoc():
                    return ascyncio.run(getCoords())
                

                【讨论】:

                  【解决方案11】:

                  基于 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()
                  

                  如何做到这一点的教程是here或找到GitHub repo here

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 2011-04-18
                    • 1970-01-01
                    • 1970-01-01
                    • 2018-06-21
                    • 1970-01-01
                    • 2014-03-12
                    • 2016-05-15
                    • 2015-01-12
                    相关资源
                    最近更新 更多