Android Tutorial (old) Google Maps Android v2 tutorial

Status
Not open for further replies.
If you are using B4A v5.80+ then please follow this tutorial: https://www.b4x.com/android/forum/threads/google-maps.63930/#post-404386

GoogleMaps library requires v2.50 or above.

GoogleMaps library allows you to add Google maps to your application. This library requires Android 3+ and will only work on devices with Google Play service.

This tutorial will cover the configuration steps required for showing a map.

1. Download Google Play services - From the IDE choose Run AVD Manager and then choose Tools - SDK Manager. Select Google Play services under the Extras node and install it:

SS-2012-12-18_18.28.04.png


2. Copy google-play-services.jar to the libraries folder - This file is available under:
C:\<android sdk>\extras\google\google_play_services\libproject\google-play-services_lib\libs (ignore the extra space that the forum script insists on adding)
You should copy it to the libraries folder.

2.5. Download the attached library, unzip it and copy to the libraries folder.

3. Find the key signature - Your application must be signed with a private key other than the debug key. After you select a new or existing key file (Tools - Private Sign Key) you should reopen the private key dialog. The signature information will be displayed (increase the dialog size as needed).
The value after SHA1 is required for the next step:

SS-2012-12-18_18.11.34.png


4. Create an API project - Follow these steps and create an API project.
You should follow the steps under "Creating an API Project" and "Obtaining an API key".

Tips:
- Make sure to select "Google Maps Android API v2" in the services list and not one of the other similar services.
- Under "Simple API Access" you should select "Key for Android apps (with certificates".

5. Add the following code to the manifest editor:
B4X:
AddManifestText( <permission
          android:name="$PACKAGE$.permission.MAPS_RECEIVE"
          android:protectionLevel="signature"/>
      <uses-feature android:glEsVersion="0x00020000" android:required="true"/>)

AddApplicationText(<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="AIzaSyCzspmxxxxxxxxxxxxx"/>
<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"
    />)
AddPermission(android.permission.ACCESS_NETWORK_STATE)
You should replace the value after android:value with the key you received in the previous step.

6. Add an #AdditionalRes attribute to the main activity:

You should add a reference to Google play resources by adding the following line:
B4X:
#AdditionalRes: <google-play-services res folder>, com.google.android.gms
For example:

#AdditionalRes: C:\android-sdk-windows\extras\google\google_play_services\libproject\google-play-services_lib\res, com.google.android.gms

Run the following code:
B4X:
'Activity module
Sub Process_Globals

End Sub

Sub Globals
   Dim mFragment As MapFragment
   Dim gmap As GoogleMap
   Dim MapPanel As Panel
End Sub

Sub Activity_Create(FirstTime As Boolean)
   MapPanel.Initialize("")
   Activity.AddView(MapPanel, 0, 0, 100%x, 100%y)
   If mFragment.IsGooglePlayServicesAvailable = False Then
      ToastMessageShow("Google Play services not available.", True)
   Else
      mFragment.Initialize("Map", MapPanel)
   End If
End Sub
Sub Map_Ready
   Log("map ready")
   gmap = mFragment.GetMap
   If gmap.IsInitialized = False Then
      ToastMessageShow("Error initializing map.", True)
   Else
      gmap.AddMarker(36, 15, "Hello!!!")
      Dim cp As CameraPosition
      cp.Initialize(36, 15, gmap.CameraPosition.Zoom)
      gmap.AnimateCamera(cp)
   End If
End Sub

You should see:

SS-2012-12-18_18.25.14.png


If you see a "white map" then there is most probably a mismatch between the: package name, sign key and the API key (from the manifest editor).

Google documentation: https://developers.google.com/maps/documentation/android/intro
Note that there is a required attribution which you must include in your app (see above link). You can get the string by calling MapFragment.GetOpenSourceSoftwareLicenseInfo.

V1.01: Fixes a bug in AddMarker2.
 

Attachments

  • GoogleMaps.zip
    17.8 KB · Views: 11,581
Last edited:

warwound

Expert
Licensed User
Longtime User
:signOops: Demo code removed as the CameraChange event is already supported!

Martin.
 
Last edited:

yamskie19

New Member
sir

sir i cant understand the instructions in number 2.5 and 3.. what attached file will i download? and why is it that i dont have that kind of image in your screenshot in number 3?
 

warwound

Expert
Licensed User
Longtime User
GoogleMapsExtras now supports polygons with holes.

Here's a code example that shows a polygon around my hometown, i have used the new holes support to create a hole in the polygon where the local docks are located:

B4X:
Sub Process_Globals
End Sub

Sub Globals
    Dim MapFragment1 As MapFragment
    Dim GoogleMap1 As GoogleMap
    Dim MapPanel As Panel
   Dim Polygon1 As Polygon
End Sub

Sub Activity_Create(FirstTime As Boolean)
   Activity.LoadLayout("Main")
    If MapFragment1.IsGooglePlayServicesAvailable = False Then
        ToastMessageShow("Google Play services not available.", True)
    Else
        MapFragment1.Initialize("MapFragment1", MapPanel)
    End If 
End Sub

Sub MapFragment1_Ready
    Log("MapFragment1_Ready")
    GoogleMap1 = MapFragment1.GetMap
    If GoogleMap1.IsInitialized = False Then
        ToastMessageShow("Error initializing map.", True)
    Else
      GoogleMap1.MapType=GoogleMap1.MAP_TYPE_NORMAL
      
      Dim GoogleMapsExtras1 As GoogleMapsExtras
      Dim PolygonOptions1 As PolygonOptions
      
      Dim PolygonCoords() As Double=Array As Double(52.7667, 0.3931, 52.7637, 0.3842, 52.7595, 0.3861, 52.7570, 0.3867, 52.7523, 0.3875, 52.7480, 0.3918, 52.7504, 0.3968, 52.7515, 0.4000, 52.7532, 0.4007, 52.7550, 0.4026, 52.7581, 0.4011, 52.7600, 0.3972, 52.7640, 0.4005, 52.7667, 0.3931)
      Dim PolygonPoints As List=CoordsToLatLngList(PolygonCoords)
      
      Dim HoleCoords() As Double=Array As Double(52.75844, 0.39227, 52.75926, 0.39546, 52.75983, 0.39477, 52.76045, 0.39540, 52.76041, 0.39583, 52.76287, 0.39767, 52.76332, 0.39598, 52.76084, 0.39420, 52.76062, 0.39496, 52.75994, 0.39453, 52.75995, 0.39401, 52.75928, 0.39173, 52.75844, 0.39227)
      Dim HolePoints As List=CoordsToLatLngList(HoleCoords)
      
      PolygonOptions1.Initialize
      PolygonOptions1.AddHole(HolePoints)
      PolygonOptions1.AddPoints(PolygonPoints)   '   version 1.01 requires AddPolygonPoints to be used as the PolygonPoints property is now read-only
      PolygonOptions1.FillColor=Colors.ARGB(128, 255, 0, 0)
      '   PolygonOptions1.PolygonPoints=PolygonPoints version 1.00 property PolygonPoints is now read-only
      PolygonOptions1.StrokeColor=Colors.Black
      PolygonOptions1.StrokeWidth=2
      
      Polygon1=GoogleMapsExtras1.AddPolygon(GoogleMap1, PolygonOptions1)
      
        Dim CameraPosition1 As CameraPosition
        CameraPosition1.Initialize(52.75811, 0.3912, 13)
        GoogleMap1.AnimateCamera(CameraPosition1)
    End If
End Sub

Sub CoordsToLatLngList(PolygonCoords() As Double) As List
   Dim PolygonCoordsCount As Int=PolygonCoords.Length
   Dim LatLngList As List
   LatLngList.Initialize
   Dim i As Int
   For i=0 To PolygonCoords.Length-2 Step 2
      Dim LatLng1 As LatLng
      LatLng1.Initialize(PolygonCoords(i), PolygonCoords(i+1))
      LatLngList.Add(LatLng1)
   Next
   Return LatLngList
End Sub

Sub RemoveButton_Click
   Polygon1.Remove
End Sub

Sub VisibilityButton_Click
   Polygon1.Visible=Not(Polygon1.Visible)
End Sub

If you are currently using version 1.00 of GoogleMapsExtras and it's Polygon object please read the thread linked to above - it mentions some syntax changes in the PolygonOptions object.

Martin.
 

Attachments

  • ComplexPolygonDemo.zip
    8.2 KB · Views: 873

ErickAsas

Member
Licensed User
Longtime User
Hi Erel,

Will there be support on this in the near future? I need to monitor this event when the user stops dragging the marker.

Can you possibly give me the code to monitor this event using other methods?

Thanks in advance.

Erick
 

warwound

Expert
Licensed User
Longtime User
GoogleMapExtras now adds support for the OnMarkerDragListener.

You can detect Drag, DragEnd and DragStart events on your draggable Markers:

B4X:
Sub Process_Globals

End Sub

Sub Globals
    Dim MapFragment1 As MapFragment
    Dim GoogleMap1 As GoogleMap
    Dim MapPanel As Panel
   Dim Label1 As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
   Activity.LoadLayout("Main")
    If MapFragment1.IsGooglePlayServicesAvailable = False Then
        ToastMessageShow("Google Play services not available.", True)
    Else
        MapFragment1.Initialize("MapFragment1", MapPanel)
    End If 
End Sub

Sub MapFragment1_Ready
    Log("MapFragment1_Ready")
    GoogleMap1 = MapFragment1.GetMap
    If GoogleMap1.IsInitialized = False Then
        ToastMessageShow("Error initializing map.", True)
    Else
      GoogleMap1.MapType=GoogleMap1.MAP_TYPE_NORMAL
      
      Dim Coords() As Double=Array As Double(52.7667, 0.3931, 52.7480, 0.3918, 52.7550, 0.4026, 52.7667, 0.3931)
      Dim i As Int
      For i=0 To Coords.Length-2 Step 2
         Dim Marker1 As Marker
         Marker1=GoogleMap1.AddMarker(Coords(i), Coords(i+1), "Marker #"&i)
         Marker1.Draggable=True
      Next
      
      Dim GoogleMapsExtras1 As GoogleMapsExtras
      
      Dim OnMarkerDragListener1 As OnMarkerDragListener
      OnMarkerDragListener1.Initialize("OnMarkerDragListener1")
      
      If OnMarkerDragListener1.IsInitialized Then
         GoogleMapsExtras1.SetOnMarkerDragListener(GoogleMap1, OnMarkerDragListener1)
      Else
         Log("OnMarkerDragListener1 is not initialized - check that the Activity contains at least one callback Sub")
      End If
      
        Dim CameraPosition1 As CameraPosition
        CameraPosition1.Initialize(52.75811, 0.3912, 13)
        GoogleMap1.AnimateCamera(CameraPosition1)
    End If
End Sub

Sub OnMarkerDragListener1_Drag(Marker1 As Marker)
   Log("OnMarkerDragListener1_Drag")
   Label1.Text=Marker1.Title&" : "&Marker1.Position
End Sub

Sub OnMarkerDragListener1_DragEnd(Marker1 As Marker)
   Log("OnMarkerDragListener1_DragEnd")
   Label1.Text=Marker1.Title&" : "&Marker1.Position
End Sub

Sub OnMarkerDragListener1_DragStart(Marker1 As Marker)
   Log("OnMarkerDragListener1_DragStart")
   Label1.Text=Marker1.Title&" : "&Marker1.Position
End Sub

As with previous example code, you will need to modify my example with a correct API key.

Martin.
 

Attachments

  • OnMarkerDragListenerDemo.zip
    7.9 KB · Views: 754

spyboy79

New Member
Licensed User
Longtime User
Hi Erel,
I started "play" with maps, but my and your test app on my Galaxy S 2.3.6 original goes crash with this error:

B4X:
** Activity (main) Create, isFirst = true **
main_activity_create (java line: 241)
java.lang.NoSuchMethodError: android.app.Activity.getFragmentManager
   at anywheresoftware.b4a.objects.MapFragmentWrapper.Initialize(MapFragmentWrapper.java:115)
   at b4a.maps.example.main._activity_create(main.java:241)
   at java.lang.reflect.Method.invokeNative(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:507)
   at anywheresoftware.b4a.BA.raiseEvent2(BA.java:167)
   at b4a.maps.example.main.afterFirstLayout(main.java:85)
   at b4a.maps.example.main.access$100(main.java:16)
   at b4a.maps.example.main$WaitForLayout.run(main.java:72)
   at android.os.Handler.handleCallback(Handler.java:587)
   at android.os.Handler.dispatchMessage(Handler.java:92)
   at android.os.Looper.loop(Looper.java:130)
   at android.app.ActivityThread.main(ActivityThread.java:3687)
   at java.lang.reflect.Method.invokeNative(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:507)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
   at dalvik.system.NativeStart.main(Native Method)
** Activity (main) Create, isFirst = true **
main_activity_create (java line: 241)
java.lang.NoSuchMethodError: android.app.Activity.getFragmentManager
   at anywheresoftware.b4a.objects.MapFragmentWrapper.Initialize(MapFragmentWrapper.java:115)
   at b4a.maps.example.main._activity_create(main.java:241)
   at java.lang.reflect.Method.invokeNative(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:507)
   at anywheresoftware.b4a.BA.raiseEvent2(BA.java:167)
   at b4a.maps.example.main.afterFirstLayout(main.java:85)
   at b4a.maps.example.main.access$100(main.java:16)
   at b4a.maps.example.main$WaitForLayout.run(main.java:72)
   at android.os.Handler.handleCallback(Handler.java:587)
   at android.os.Handler.dispatchMessage(Handler.java:92)
   at android.os.Looper.loop(Looper.java:130)
   at android.app.ActivityThread.main(ActivityThread.java:3687)
   at java.lang.reflect.Method.invokeNative(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:507)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
   at dalvik.system.NativeStart.main(Native Method)

Any idea?
 

warwound

Expert
Licensed User
Longtime User
You mean Gingerbread 2.3.6 do you?

You need a minimum Android version od 3.0 to use this library - see the first post in this thread.

Martin.
 

ErickAsas

Member
Licensed User
Longtime User
How To Get The Map Center LatLng

Hi Erel/Martin,

Can you help me with this?

In Javascript, this used to be Map.getCenter()...
 

ErickAsas

Member
Licensed User
Longtime User
I tried to get the camera target property when I move the map away from the initial cp position. The camera target property does not change when you move the map.
 

warwound

Expert
Licensed User
Longtime User
Seems to work for me:

B4X:
Sub Process_Globals

End Sub

Sub Globals
    Dim MapFragment1 As MapFragment
    Dim GoogleMap1 As GoogleMap
    Dim MapPanel As Panel
   Dim Polygon1 As Polygon
   Dim LocationLabel As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
   Activity.LoadLayout("Main")
    If MapFragment1.IsGooglePlayServicesAvailable = False Then
        ToastMessageShow("Google Play services not available.", True)
    Else
        MapFragment1.Initialize("MapFragment1", MapPanel)
    End If 
End Sub

Sub MapFragment1_Ready
    Log("MapFragment1_Ready")
    GoogleMap1 = MapFragment1.GetMap
    If GoogleMap1.IsInitialized = False Then
        ToastMessageShow("Error initializing map.", True)
    Else
      GoogleMap1.MapType=GoogleMap1.MAP_TYPE_NORMAL
        Dim CameraPosition1 As CameraPosition
        CameraPosition1.Initialize(52.689, 0.770, 10)
        GoogleMap1.AnimateCamera(CameraPosition1)
    End If
End Sub

Sub LocationButton_Click
   LocationLabel.Text=GoogleMap1.CameraPosition.Target
End Sub

Pan the map and then click LocationButton, repeat a few times, it shows a different map center.

Martin.
 

Attachments

  • GetMapCenter.zip
    7.7 KB · Views: 704

ErickAsas

Member
Licensed User
Longtime User
Thanks for pointing me in the right direction. I was using the wrong target.

When I use cp.Target.Latitude and cp.Target.Longitude, nothing changes.

When I use gmap.CameraPosition.Target.Latitude and gmap.CameraPosition.Target.Longitude, it now works fine.

Thank again.:sign0142:
 
Status
Not open for further replies.
Top