python - 我可以使用 HTML5 定位工具在 Python 中获得准确的地理定位吗?

标签 python html geolocation position

我想使用 Python 脚本获取我的准确位置。 我已经尝试过基于 IP 位置的不同服务,但根本不起作用(总是离我的实际位置很远)。

我注意到 HTML5 地理定位工具在 Firefox 和 Google Chrome 上非常准确,所以我决定使用 selenium 模块启动网络浏览器并从中获取我的位置。

虽然我面临两个问题:首先,我不能强制 Firefox 或 Chrome 允许本地网页上的位置服务。其次,我不知道如何获取获取坐标的 javascript 函数的结果。

这是我到目前为止所做的:

geo.html

<html>
    <head>
        <title>Test</title>
    <p id="demo"></p>
        <script type="text/javascript">

var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        return navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        return "Geolocation is not supported by this browser.";
    }
}



function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
}
        </script>
    </head>
    <body>
        <p>The element below will receive content</p>
        <div id="div" />
        <script type="text/javascript">getLocation()</script>
    </body>
</html>

测试.py

from selenium import webdriver
from pyvirtualdisplay import Display

try:
    display = Display(visible=1, size=(800, 600))
    display.start()
    browser = webdriver.Firefox()
    browser.get('file:///path/to/geo.html')
    res = browser.execute_script("getLocation()")
    print(res)

except KeyboardInterrupt:
    browser.quit()
    display.stop()

你知道怎么解决吗?

谢谢!

最佳答案

我发现 Geoclue 非常准确,这可能已经在您的系统上了。只需安装 gir1.2-geoclue-2.0 包,然后:

from gi.repository import Geoclue
clue = Geoclue.Simple.new_sync('something',Geoclue.AccuracyLevel.EXACT,None)
location = clue.get_location()
print(location.get_property('latitude'), location.get_property('longitude'))

有关详细信息,请参阅我的 blog post .

关于python - 我可以使用 HTML5 定位工具在 Python 中获得准确的地理定位吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45630606/

相关文章:

python - 如果列值满足语句,如何提取整个数据框行?

python - xgboost 的哪些功能受种子(random_state)影响?

android - Erron 在 Android 中使用 GoogleApiClient 获取最后已知位置

python - 连接到 MySql 服务器失败 - Python

html - 搜索按钮固定不动

javascript - jQuery:如何精确匹配 Div 类

javascript - 颜色数组,试图给它们一些不透明度

iOS - 如何在 APNS 之前放置自定义弹出窗口并启用位置弹出窗口

javascript - 如何在安装应用程序时获取访问权限而不是在使用时请求权限

python - scipy 最小化约束