Android Tutorial GPS tutorial

Status
Not open for further replies.
This example shows how to work with the GPS library.

upload_2016-6-23_9-56-49.png


The GPS object is declared in the Starter service. It is easier to put the GPS in a service and not in an Activity as the services life cycle is simpler.

When the program starts we check whether the location features are enabled:
B4X:
Sub Activity_Resume
   If Starter.GPS1.GPSEnabled = False Then
       ToastMessageShow("Please enable the GPS device.", True)
       StartActivity(Starter.GPS1.LocationSettingsIntent) 'Will open the relevant settings screen.
   Else
       Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION)
       Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
       If Result Then CallSubDelayed(Starter, "StartGPS")
   End If
End Sub
If not then we open the relevant settings screen.

The next step is to check for the ACCESS_FINE_LOCATION permission (runtime permissions tutorial).
If we have permission then we call the StartGPS sub from the Starter service.

Now all that is left is to delegate the LocationChanged event from the service to the activity and show the information.
B4X:
'Starter service
Sub GPS_LocationChanged (Location1 As Location)
   CallSub2(Main, "LocationChanged", Location1)
End Sub

'Main activity
Public Sub LocationChanged(Location1 As Location)
   lblLat.Text = "Lat = " & Location1.ConvertToMinutes(Location1.Latitude)
   lblLon.Text = "Lon = " & Location1.ConvertToMinutes(Location1.Longitude)
   lblSpeed.Text = $"Speed = $1.2{Location1.Speed} m/s "$
End Sub

Due to Google policy change you also need to add this line to the manifest editor:
B4X:
AddManifestText(<uses-feature android:name="android.hardware.location.gps"/>)
This will prevent the app from being installed on devices without GPS hardware.

The example is attached.

Modified example with NMEA listener: https://www.b4x.com/android/forum/t...-not-firing-on-android-10.112140/#post-699351
 

Attachments

  • GPS.zip
    8.1 KB · Views: 7,233
Last edited:

mitsusdev

Member
Licensed User
Longtime User
if i use the tutorial example, when i walk some speed are set to 0 (zero).

for example:

1,4 m/s
1,5 m/s
0
1.3 m/s
1.6 m/s
ecc.ecc

Can i set the best gps precision ?
 

Adrian Jansen

Member
Licensed User
Longtime User
Although you say that the user must enable the GPS, I have several other apps, like "GPS Essentials" and the Google Maps app, which dont appear to need this, they just turn on the GPS when the app is launched, and turn it off when closed. Can you clarify this please.
 

merlin2049er

Well-Known Member
Licensed User
Longtime User
My satellites show up as false? Can't lock onto a position?

My google maps seems to work fine.
 

johnaaronrose

Active Member
Licensed User
Longtime User
The GPS is an important feature of many Android devices.
Fortunately it is pretty easy to work with it.
In this tutorial we will cover a simple program that shows the current position as well as the satellites status.

gps1.png


The GPS functionality is packaged in the GPS library.
Therefore we should first add a reference to this library:
gps2.png


There are three types of relevant objects. The main one is GPS.
The GPS manages the connection and events. The second is Location.
A Location is a structure that holds the data available regarding a specific "fix". The data includes the latitude and longitude coordinates, the time (expressed as ticks) of this fix and other information like bearing, altitude and so on.
It may happen that not all information is available (due to poor reception for example).

The Location also includes other functionalities like calculating the distance and bearing to another location and methods to convert the coordinates string formats.
Usually you will work with Location objects passed to you in the LocationChanged events. However you can also initialize such objects yourself (this is useful for calculating distance and bearing between locations).

The last one is GPSSatellite. This is a structure that holds various information regarding the currently known satellites. It is passed to you in GPSStatus event.

Back to GPS.
The GPS object should be declared as a Process_Global object. Otherwise new instances will be created each time the activity is recreated.

The first step is to initialize the object. Like many other Initialize methods this one expects an EventName parameter. This is the prefix for the events that will be raised by the GPS object.

Here is the complete code:
B4X:
Sub Process_Globals
    Dim GPS1 As GPS
End Sub

Sub Globals
    Dim lblLon As Label
    Dim lblLat As Label
    Dim lblSpeed As Label
    Dim lblSatellites As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then
        GPS1.Initialize("GPS")
    End If
    Activity.LoadLayout("1")
End Sub

Sub Activity_Resume
    If GPS1.GPSEnabled = False Then
        ToastMessageShow("Please enable the GPS device.", True)
        StartActivity(GPS1.LocationSettingsIntent) 'Will open the relevant settings screen.
    Else
        GPS1.Start(0, 0) 'Listen to GPS with no filters.
    End If
End Sub

Sub Activity_Pause (UserClosed As Boolean)
    GPS1.Stop
End Sub

Sub GPS_LocationChanged (Location1 As Location)
    lblLat.Text = "Lat = " & Location1.ConvertToMinutes(Location1.Latitude)
    lblLon.Text = "Lon = " & Location1.ConvertToMinutes(Location1.Longitude)
    lblSpeed.Text = "Speed = " & Location1.Speed
End Sub

Sub GPS_UserEnabled (Enabled As Boolean)
    ToastMessageShow("GPS device enabled = " & Enabled, True)
End Sub

Sub GPS_GpsStatus (Satellites As List)
    lblSatellites.Text = "Satellites:" & CRLF
    For i = 0 To Satellites.Size - 1
        Dim Satellite As GPSSatellite
        Satellite = Satellites.Get(i)
        lblSatellites.Text = lblSatellites.Text & CRLF & Satellite.Prn & _
            " " & Satellite.Snr & " " & Satellite.UsedInFix & " " & Satellite.Azimuth _
            & " " & Satellite.Elevation
    Next
End Sub
The next step is to tell the GPS to start listening for data. The GPS can consume quite a lot of battery. Therefore it is recommended to stop using the GPS whenever it is not necessary. It is recommended to start listening in Activity_Resume and stop listening in Activity_Pause.

It may happen that the user has turned off the GPS. Due to privacy concerns the Android OS doesn't allow you to turn the GPS on programatically. The best thing that you can do is to ask the user to enable the GPS device.

The following code shows a message if the GPS is not enabled and also opens the GPS control panel so the user only needs to check the GPS option:
B4X:
Sub Activity_Resume
    If GPS1.GPSEnabled = False Then
        ToastMessageShow("Please enable the GPS device.", True)
        StartActivity(GPS1.LocationSettingsIntent) 'Will open the relevant settings screen.
    Else
        GPS1.Start(0, 0) 'Listen to GPS with no filters.
    End If
End Sub
If the GPS is enabled we are starting to listen for data. The Start method receives two values which are the minimum time (milliseconds) and the minimum distance (meters) between events. An event will be raised when at least one of these criterions is met. This can help saving battery.
In our case we are passing 0 and therefore will get all fix events.

The GPS raises three events:
- GPS_LocationChanged (Location1 As Location)
This is the main event. Location1 holds the data for the new fix.

-GPS_GpsStatus (Satellites As List)
This event allows you to display information about the currently available satellites. Note that not all satellites in the list are actually used for calculating the last fix. So it is possible that the list will include several satellites but still the reception is not good enough for a fix.

- GPS_UserEnabled (Enabled As Boolean)
This event is raised whenever the user changes the status of the GPS device. It is also raised right after calling Start.

The program is attached.

Is it possible to obtain the current location details immediately after initializing the GPS? If so, how?
 

johnaaronrose

Active Member
Licensed User
Longtime User

arjian

Member
Licensed User
Longtime User
I’m confused by LatLonToUTM function,char utmYZone: upon exit, this parameter will contain the zone letter of the UTM coordinate
The returned value for this parameter will be one of : CDEF…
But according to :
Latitudinal zones are not part of the UTM, they are part of the Military General Reference System (MGRS). they are often
used in conjunction with the UTM. they extend from 84°N to 80°S and are designated with the letters C to X (skipping I
and O). Each latitudinal zone is 8 degrees, except for the 12 degree zone X.
Beware of confusion between the standard N and S (indicating north and south of the Equator in the UTM system) and
zone S in the MGRS with is in the northern hemisphere

the returned value for this parameter must be one of : N or S
 

IslamQabel

Active Member
Licensed User
Longtime User
:sign0085: oops, got a problem, this code shows me only 3 satellites, all as 'false', for example "5 9 false 260 53" and does not show any lat or lon. any ideas what could be wrong?

Thanks!

P.S. google maps works and show my location correctly.

The same problem for me............although i am standing with any obstacle to the sky....satellites are false
 
Status
Not open for further replies.
Top