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,402
Last edited:

badal405

Member
Licensed User
Longtime User
Google Map

Dear Erel,
I have followed every step you mention in the forum perfectly.
I just copy your code and try to run into emulator but i am getting the following error.
B4X:
   at com.google.android.gms.common.GooglePlayServicesUtil.<clinit>(Unknown Source)
   ... 17 more
** Activity (main) Create, isFirst = true **


** Activity (main) Resume **
** Activity (main) Pause, UserClosed = true **
** Activity (main) Create, isFirst = true **


main_activity_create (java line: 246)


java.lang.ExceptionInInitializerError


   at anywheresoftware.b4a.objects.MapFragmentWrapper.IsGooglePlayServicesAvailable(MapFragmentWrapper.java:101)
   at b4a.example.main._activity_create(main.java:246)
   at java.lang.reflect.Method.invokeNative(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:521)
   at anywheresoftware.b4a.BA.raiseEvent2(BA.java:169)
   at b4a.example.main.afterFirstLayout(main.java:89)
   at b4a.example.main.access$100(main.java:16)
   at b4a.example.main$WaitForLayout.run(main.java:74)
   at android.os.Handler.handleCallback(Handler.java:587)
   at android.os.Handler.dispatchMessage(Handler.java:92)
   at android.os.Looper.loop(Looper.java:123)
   at android.app.ActivityThread.main(ActivityThread.java:4363)
   at java.lang.reflect.Method.invokeNative(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:521)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)


   at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NoClassDefFoundError: android.util.Base64
   at com.google.android.gms.common.GooglePlayServicesUtil.<clinit>(Unknown Source)
   ... 17 more

Here below is code..

B4X:
#Region  Project Attributes 
   #ApplicationLabel: MyGoogleMap
   #VersionCode: 1
   #VersionName: 
   'SupportedOrientations possible values: unspecified, landscape or portrait.
   #SupportedOrientations: unspecified
   #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes 
   #FullScreen: False
   #IncludeTitle: True
#End Region

Sub Process_Globals
   'These global variables will be declared once when the application starts.
   'These variables can be accessed from all modules.

End Sub

Sub Globals
   'These global variables will be redeclared each time the activity is created.
   'These variables can only be accessed from this module.
    Dim mFragment As MapFragment
    Dim gmap As GoogleMap
    Dim MapPanel As Panel

End Sub

Sub Activity_Create(FirstTime As Boolean)
   'Do not forget to load the layout file created with the visual designer. For example:
   Activity.LoadLayout("MyGoogleMap")
    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 Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

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
 

badal405

Member
Licensed User
Longtime User
The error message is not complete. I recommend you to try it on a real device. GoogleMaps uses several services that may not be available in the emulator.

Ok, I will try with a real device and let you know. But the message i provided you is complete. The same way i got the message in b4a.
 

ValDog

Active Member
Licensed User
Longtime User
I am trying to add Google Play Services per the tutorial, but my Android SDK Manager, under Extras, only lists Google USB Driver package. I must be missing something basic here - Help!
 

maleche

Active Member
Licensed User
Longtime User
What is the minimum API I should install to use B4A and Google Maps?
Thanks
 

CaptainJackson

Member
Licensed User
Longtime User
I'm trying to find the altitude change between 2 markers placed on a map. Can't for the life of me figure out how to get the location.altitude to be anything but 0, or any other way to obtain an altitude from a lat/long.

Anyone have a suggestion?
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
What is the minimum API I should install to use B4A and Google Maps?
You should install and use API 12+.

I'm trying to find the altitude change between 2 markers placed on a map. Can't for the life of me figure out how to get the location.altitude to be anything but 0, or any other way to obtain an altitude from a lat/long.
Altitude information is not exposed in GoogleMaps.
 

urikupfer

Member
Licensed User
Longtime User
HI CaptainJackson
You can use JavaScript file with Google maps v3 – it have Elevation calculation and combine it with the b4a Google maps and WebViewExtras libraries
Uri
 

dealsmonkey

Active Member
Licensed User
Longtime User
Or use the HTTP library to query the Google Elevation API.
Martin.

Here is a quick service module that will call the elevation api and return the elevation and resolution. More could be dome for error checking but it works as is fine :)


B4X:
Sub Process_Globals
   'These global variables will be declared once when the application starts.
   'These variables can be accessed from all modules.
   Private elevationJob As HttpJob
   Public Elevation As Double
   Type Servicedata (Latitude As Double, Longitude As Double, Sensor As Boolean)
   Dim mydata As Servicedata
   
End Sub   
Sub Service_Create
elevationJob.Initialize("elevationJob",Me)
End Sub

Sub Service_Start (StartingIntent As Intent)

End Sub

Sub Service_Destroy
Job.Release
End Sub


Sub getElevationData(url As String) 
elevationJob.Download(url)
End Sub


Sub JobDone (Job As HttpJob)
If Job.Success = True Then
DecodeJsonResponse(Job.GetString)
stopservice("")
End If
stopservice("")
End Sub


Sub DecodeJsonResponse(jsonResponse As String)

Dim JSON As JSONParser
Dim Map1 As Map
JSON.Initialize(jsonResponse)
Map1 = JSON.NextObject
Dim m As Map 'helper map for navigating
Dim ResultItems As List
ResultItems = Map1.Get("results")
For i = 0 To ResultItems.Size - 1
    m = ResultItems.Get(i)   
Next

'Now show the results. These could be assigned to global variable, saved in ini file etc etc
Log(m.Get("elevation"))
Log(m.Get("resolution"))

End Sub

Then in another module use this code to call the service
B4X:
 'Assign the values to the params required by the API request
 
Dim Latitude As Double = 39.73915360
Dim Longitude As Double = -104.98470340
Dim sensor As Boolean = False
Dim url As String  = "http://maps.googleapis.com/maps/api/elevation/json?locations=" & Latitude & "," & Longitude & "&sensor=" & sensor
CallSubDelayed2(getElevationData,"getElevationData",url)
 
Last edited:

CaptainJackson

Member
Licensed User
Longtime User
Here is a quick service module that will call the elevation api and return the elevation and resolution. More could be dome for error checking but it works as is fine :)


B4X:
Sub Process_Globals
   'These global variables will be declared once when the application starts.
   'These variables can be accessed from all modules.
   Private elevationJob As HttpJob
   Public Elevation As Double
   Type Servicedata (Latitude As Double, Longitude As Double, Sensor As Boolean)
   Dim mydata As Servicedata
   
End Sub   
Sub Service_Create
elevationJob.Initialize("elevationJob",Me)
End Sub

Sub Service_Start (StartingIntent As Intent)

End Sub

Sub Service_Destroy
Job.Release
End Sub


Sub getElevationData(url As String) 
elevationJob.Download(url)
End Sub


Sub JobDone (Job As HttpJob)
If Job.Success = True Then
DecodeJsonResponse(Job.GetString)
stopservice("")
End If
stopservice("")
End Sub


Sub DecodeJsonResponse(jsonResponse As String)

Dim JSON As JSONParser
Dim Map1 As Map
JSON.Initialize(jsonResponse)
Map1 = JSON.NextObject
Dim m As Map 'helper map for navigating
Dim ResultItems As List
ResultItems = Map1.Get("results")
For i = 0 To ResultItems.Size - 1
    m = ResultItems.Get(i)   
Next

'Now show the results. These could be assigned to global variable, saved in ini file etc etc
Log(m.Get("elevation"))
Log(m.Get("resolution"))

End Sub

Then in another module use this code to call the service
B4X:
 'Assign the values to the params required by the API request
 
Dim Latitude As Double = 39.73915360
Dim Longitude As Double = -104.98470340
Dim sensor As Boolean = False
Dim url As String  = "http://maps.googleapis.com/maps/api/elevation/json?locations=" & Latitude & "," & Longitude & "&sensor=" & sensor
CallSubDelayed2(getElevationData,"getElevationData",url)

Thank you so much! Everyone is so helpful and fast here. I have spent so much time with vb and it is about the 8th or 9th language I have used through the years. Now it gets harder and harder to shove new things into my head. Basic4Android has made it much easier to code for android devices.

Thanks Again!:sign0060:
 

dealsmonkey

Active Member
Licensed User
Longtime User
Thank you so much! Everyone is so helpful and fast here. I have spent so much time with vb and it is about the 8th or 9th language I have used through the years. Now it gets harder and harder to shove new things into my head. Basic4Android has made it much easier to code for android devices.

Thanks Again!:sign0060:

Your welcome :eek:
 

CaptainJackson

Member
Licensed User
Longtime User
Couple problems for me. Can you help again please?

Sub Service_Destroy
Job.Release
End Sub

I get variable 'job' not declared error.

I changed it to: elevationJob.Release

Is this what you meant?

Also, the app crashes when it makes the http call here:

Sub getElevationData(url As String)
elevationJob.Download(url)
End Sub

My code, Origin is global:
Origin.Initialize2("35.000", "-119.000")
Dim sensor As Boolean = False
Dim url As String = "http://maps.googleapis.com/maps/api/elevation/json?locations=" & Origin.Latitude & "," & Origin.Longitude & "&sensor=" & sensor
CallSubDelayed2(svcgetElevationData,"getElevationData",url)

I'm guessing I don't have something right in the manifest file to use the v3 API's? which libs are required? I turned on http, json, httputils2.

Also, how does Job_Done ever get called? I don't see how that happens. Should that also be changed to elevationJob_Done?

Thanks,
Jackson
 

dealsmonkey

Active Member
Licensed User
Longtime User
Couple problems for me. Can you help again please?

Sub Service_Destroy
Job.Release
End Sub

I get variable 'job' not declared error.

I changed it to: elevationJob.Release

Is this what you meant?

Also, the app crashes when it makes the http call here:

Sub getElevationData(url As String)
elevationJob.Download(url)
End Sub

My code, Origin is global:
Origin.Initialize2("35.000", "-119.000")
Dim sensor As Boolean = False
Dim url As String = "http://maps.googleapis.com/maps/api/elevation/json?locations=" & Origin.Latitude & "," & Origin.Longitude & "&sensor=" & sensor
CallSubDelayed2(svcgetElevationData,"getElevationData",url)

I'm guessing I don't have something right in the manifest file to use the v3 API's? which libs are required? I turned on http, json, httputils2.

Also, how does Job_Done ever get called? I don't see how that happens. Should that also be changed to elevationJob_Done?

Thanks,
Jackson

Ill start a new thread to answer your questions :)
 
Status
Not open for further replies.
Top