Here is a new version.
-
We are closing the safari window, and going back to pythonista.
This looks not possible with the embedded webview, as the UIWebWiew ignores window.close() (this could be changed by omz).
-
We are faking a (dumb and not compliant) web server, to bypass the heavy weight HTTPServer
-
To use, simply call get_lat_long. This should give you the latitude and longitude as float
-
The whole stuff needs better error checking...
import socket
import webbrowser
import re
html = """
<!DOCTYPE html>
<html>
<head>
<script>
function returnToPythonista() {
window.open('pythonista://', '_self', '');
window.close();
}
function sendPosition(position) {
var xhr = new XMLHttpRequest();
xhr.addEventListener("loadend", function () {
window.setTimeout(returnToPythonista,0);
}, false);
var lat = position.coords.latitude;
var lng = position.coords.longitude;
xhr.open('HEAD', '/?lat=' + lat + '&lng=' + lng, true);
xhr.send("");
}
navigator.geolocation.getCurrentPosition(sendPosition);
</script>
</head>
<body>
<h1>Wait...</h1>
</body>
</html>
"""
def get_lat_long(port=3050):
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind( ('127.0.0.1', port) )
s.listen(1)
webbrowser.open('safari-http://localhost:3050/')
def send(s, data):
s2, addrinfo = s.accept()
resp = s2.recv(4096)
s2.send("\n".join(("HTTP/1.0 200 OK", "Content-Type: text/html", "Content-Length: {}".format(len(data)), "", data)))
s2.close()
return resp
# Send html page on first connection
send(s, html)
# Send empty page
data = send(s, "")
s.close()
result = re.search(r'lat=([\d.]*)&lng=([\d.]*)', data)
if result:
return [float(n) for n in result.groups()]
return None, None
if __name__ == '__main__':
lat, lng = get_lat_long()
print ('lat {}, lng {}'.format(lat, lng))