I try to obtain the GPS-Location of my Android Phone in Python (using QPython3 app). This kind of works, but it seems there are several LocationProviders in Android:
Problem: When I run my script (below) I only get my location provided by "network" wich is not accurate enough.
But I can't find a way to force a specific LocationProvider.
Code:
# import needed modules
import android
import time
import sys, select, os #for loop exit
#Initiate android-module
droid = android.Android()
#notify me
droid.makeToast("fetching GPS data")
print("start gps-sensor...")
droid.startLocating()
while True:
#exit loop hook
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
line = input()
print("exit endless loop...")
break
#wait for location-event
event = droid.eventWaitFor('location',10000).result
if event['name'] == "location":
try:
#try to get gps location data
timestamp = repr(event['data']['gps']['time'])
longitude = repr(event['data']['gps']['longitude'])
latitude = repr(event['data']['gps']['latitude'])
altitude = repr(event['data']['gps']['altitude'])
speed = repr(event['data']['gps']['speed'])
accuracy = repr(event['data']['gps']['accuracy'])
loctype = "gps"
except KeyError:
#if no gps data, get the network location instead (inaccurate)
timestamp = repr(event['data']['network']['time'])
longitude = repr(event['data']['network']['longitude'])
latitude = repr(event['data']['network']['latitude'])
altitude = repr(event['data']['network']['altitude'])
speed = repr(event['data']['network']['speed'])
accuracy = repr(event['data']['network']['accuracy'])
loctype = "net"
data = loctype + ";" + timestamp + ";" + longitude + ";" + latitude + ";" + altitude + ";" + speed + ";" + accuracy
print(data) #logging
time.sleep(5) #wait for 5 seconds
print("stop gps-sensor...")
droid.stopLocating()
Sample Output (fake coordinates):
net;1429704519675;37.235065;-115.811117;0;0;23
net;1429704519675;37.235065;-115.811117;0;0;23
net;1429704519675;37.235065;-115.811117;0;0;23
Summarization: How do I get a precise GPS location in Android using Python?
Thanks in advance everyone!
EDIT: already tested:
I had the same problem. You Can do something Like this if you want to enforce GPS as LocationProvider
import android, time
droid = android.Android()
droid.startLocating()
print('reading GPS ...')
event=droid.eventWaitFor('location', 10000)
while 1:
try :
provider = event.result['data']['gps']['provider']
if provider == 'gps':
lat = str(event['data']['gps']['latitude'])
lng = str(event['data']['gps']['longitude'])
latlng = 'lat: ' + lat + ' lng: ' + lng
print(latlng)
break
else: continue
except KeyError:
continue