Android Question Start Google Map centered on my location

andyp

Member
Licensed User
Hi. Trying to start a google map fragment centered on the users location - without the user manually pressing the 'my location' button.

Basically, I want to programmatically press the 'my location' button, and grab those coordinates to center the map on the users location (and show the users location as the usual blue circle).

I think these are the relevant bits of code, and the last bit is where I want to center the map. Unfortunately when I log my two co-ordinates they are both 0 ... which is my problem :-(

Thank you!

B4X:
Sub Process_Globals
Dim GPS1 As GPS
End Sub

Sub Globals
 Private gmap As GoogleMap
 Private MapFragment1 As MapFragment
 Private scale As MapScaleView
 Dim lblLon As Double
 Dim lblLat As Double
End Sub


Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("CreateBox")
    scale.Initialize("")
    If MapFragment1.IsGooglePlayServicesAvailable = False Then
        ToastMessageShow("Please install Google Play Services.", True)
    End If
    GPS1.Initialize("CreateBox")

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 = Location1.Latitude
    lblLon = Location1.Longitude    
End Sub


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

Sub MapFragment1_Ready
    Log($"map_Ready()"$)
    gmap = MapFragment1.GetMap
   
    Dim cp1 As CameraPosition
    cp1.Initialize(lblLat, lblLon, 15) ' Use own location LAT LON
    gmap.AnimateCamera(cp1)
    Log(lblLat)
    Log(lblLon)
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
You don't need to find the location yourself.

Complete code:
B4X:
Sub Activity_Create(FirstTime As Boolean)
   Activity.LoadLayout("1")
   Wait For MapFragment1_Ready
   gmap = MapFragment1.GetMap
   If gmap.IsInitialized Then
     Do While gmap.MyLocation.IsInitialized = False
       Sleep(100)
     Loop
     Dim cp As CameraPosition
     cp.Initialize(gmap.MyLocation.Latitude, gmap.MyLocation.Longitude, 5)
     gmap.MoveCamera(cp)
   End If
End Sub
 
Upvote 0
Top