I would like to get my accurate position using a Python script. I've tried different services based on IP location, which didn't work at all (always miles away from my actual location).
I noticed that the HTML5 geolocation tool is quite accurate on Firefox & Google Chrome, so I decided to use the selenium module to launch a web browser and grab my position from this.
Though I'm facing 2 issues: first, I can't force either Firefox or Chrome to allow location services on a local webpage. Second, I don't know how to grab the result of a javascript function in which I get my coordinates.
Here's what I've done so far:
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>
test.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()
Do you know how to solve this?
Thanks!