Android Question Automatically center the map of Google maps

carlos7000

Well-Known Member
Licensed User
Longtime User
Hello! I am working on a GPS tracking application that uses the Google Maps library. The goal of this app is to display the location of given coordinates at the center of the map. Initially, I was using another GPS library to obtain the device's coordinates and send the data to the map whenever the location changed, so that the map would center on the new coordinates.

However, after researching, I realized that the Google Maps library can also retrieve the user's location, so I decided to eliminate the GPS library and use a 'Timer' to periodically obtain coordinates directly from the Google Maps library. I would like to know if any of you know whether the Google Maps library has an event that triggers every time the user's location changes. This way, I can avoid using the Timer altogether. Alternatively, if anyone knows how to make the map automatically stay centered on the user's position, that would be very helpful too.

This is the way I centered the map using a timer

B4X:
#Region Shared Files
#CustomBuildAction: folders ready, %WINDIR%\System32\Robocopy.exe,"..\..\Shared Files" "..\Files"
'Ctrl + click to sync files: ide://run?file=%WINDIR%\System32\Robocopy.exe&args=..\..\Shared+Files&args=..\Files&FilesSync=True
#End Region

'Ctrl + click to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=Project.zip

Sub Class_Globals
    Private Root As B4XView
    Private xui As XUI
    
    Private gmap As GoogleMap
    Private MapFragment1 As MapFragment
    
    Private t As Timer
End Sub

Public Sub Initialize
'    B4XPages.GetManager.LogEvents = True

    If MapFragment1.IsGooglePlayServicesAvailable = False Then
        MsgboxAsync("Please install Google Play Services.", "Google Play Services")
    End If
    
    t.Initialize("Click", 3000)
    t.Enabled = True
    ToastMessageShow("Timer ok", False)
End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
    Root.LoadLayout("MainPage")
    B4XPages.SetTitle(Me, "Google Maps-Tracker")
    
    Dim rp As RuntimePermissions
    rp.CheckAndRequest(rp.PERMISSION_ACCESS_FINE_LOCATION)
    Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
    gmap.MyLocationEnabled = Result
    
End Sub

'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.

Sub MapFragment1_Ready
    Try
        gmap = MapFragment1.GetMap
    Catch
        Log("MapFragment1: " & LastException)
    End Try

End Sub

Sub Click_Tick
    Dim Camera As CameraPosition
    Camera.Initialize(gmap.MyLocation.Latitude, gmap.MyLocation.Longitude, 17) '10 Lejos. 15 mas cerca
    gmap.AnimateCamera(Camera)
End Sub
 
Top