Get geolocation from GPS

Learn:

  • GPS
  • Wait for Event

This program reads the geolocation. GPS requires line of sight of the GPS satellites to work. This means you need to be in the open otherwise an error will be reported. In such a case, the network can be used to obtain the location. It is a good idea to run your favourite map app to get a fix of your location if you are running this example the first time.

gps.py

import android droid = android.Android() droid.startLocating() print "reading GPS ..." event = droid.eventWaitFor('location',10000).result if event['name'] == "location": try: lat = str(event['data']['gps']['latitude']) lng = str(event['data']['gps']['longitude']) except KeyError: lat = str(event['data']['network']['latitude']) lng = str(event['data']['network']['longitude']) latlng = 'lat: ' + lat + ' lng: ' + lng print latlng droid.stopLocating()

Code Explained

droid.startLocating()

Start the GPS.

event = droid.eventWaitFor('location',10000).result

Wait up to 10000ms for location event to occur.

lat = str(event['data']['gps']['latitude']) lng = str(event['data']['gps']['longitude'])

Get the lat and lng information.

droid.stopLocating()

Stop the GPS.

Geocode

Geocode returns addresses based on latitude and longtitude information. Information on the gecode method can be found in the ApiReference. You do not need the GoogleMap API key but network access must be available for this to work.

address = droid.geocode(lat, lng).result

The address format is list of dictionaries. Generally only one entry in the list is returned for address lookups, though the geocoder may return several results when address queries are ambiguous:
[{u'thoroughfare': u'Some Street', u'locality': u'Some Town', u'sub_admin_area': u'Some Borough', u'admin_area': u'Some City', u'feature_name': u'House Numbers', u'country_code': u'GB', u'country_name': u'United Kingdom', u'postal_code': u'ST1 1'}]

Further information on the geocode method can be obtained from the LocationFacade.java source code.

Scan the script to your smartphone using the Test EMANT380 app or download to PC/Emulator

gps.zip