Android Tutorial Google Maps

Status
Not open for further replies.
upload_2016-2-24_12-2-46.png



Installation instructions:

- Register your app in Google developer console: https://console.developers.google.com
You need to enable Google Maps Android API.
Then click on Credentials -> Create Credentials -> API Key -> Android Key.
You should get a key that looks like: AIzaSyCmFHamGE0O0BvxxxxxxxxXbTCSrjFVg-Q

- Copy the attached library and put it in the additional libraries folder. Add a reference to the GoogleMaps library.

- Add this to the manifest editor (replace the value with your key):
B4X:
CreateResourceFromFile(Macro, FirebaseAnalytics.GooglePlayBase)

AddApplicationText(
<meta-data
  android:name="com.google.android.geo.API_KEY"
  android:value="xxxxxxxxxxxxxx"/>
)

AddApplicationText(
<uses-library
      android:name="org.apache.http.legacy"
      android:required="false" />
)


Don't add #AdditionalRes or #ExcludeClasses.

- Set minSdkVersion to 14 (Android 4).

- Add a MapFragment with the visual designer. It will appear under the CustomView menu. If you don't see it then make sure that the GoogleMaps library is selected.
You can change the properties from the designer.
Set the anchors to BOTH so the map will fill the activity:

SS-2016-02-24_12.13.18.png



Implement the Ready event to get a reference to the GoogleMap object.
Complete code:
B4X:
Sub Process_Globals
   Private rp As RuntimePermissions
End Sub

Sub Globals
   Private gmap As GoogleMap
   Private MapFragment1 As MapFragment
End Sub

Sub Activity_Create(FirstTime As Boolean)
   Activity.LoadLayout("1")
   Wait For MapFragment1_Ready
   gmap = MapFragment1.GetMap
   rp.CheckAndRequest(rp.PERMISSION_ACCESS_FINE_LOCATION)
   Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
   If Result Then
       gmap.MyLocationEnabled = True
   Else
       Log("No permission!")
   End If
End Sub

Notes


Updates

-
v2.50 - Required dependencies were added to the library.
My Location Enabled property was removed from the designer as it needs to be set after the permission is granted.
- v2.02 EXTERNAL_STORAGE permission removed. It is no longer required.
GetOpenSourceLicenseInfo returns an empty string.
Fixes an issue with the ready event being lost if the activity is paused before the map is ready.

Note that you will need to update the package name and api key in the attached example.
 

Attachments

  • GoogleMapsExample.zip
    8.4 KB · Views: 3,673
  • GoogleMaps.zip
    19.4 KB · Views: 3,933
Last edited:

Anser

Well-Known Member
Licensed User
Longtime User
Can anybody confirm that GoogleMap works only if MapFragment added via Designer and that it will not work if added via code
Everything working fine if use a Layout via Designer

The following code does not work (via code and not designer)
B4X:
Sub Globals
  Dim mFragment1 As MapFragment
  Dim gmap As GoogleMap
  Dim MapPanel1 As Panel
End Sub

Sub Activity_Create(FirstTime As Boolean)
  MapPanel1.Initialize("")
  Activity.AddView(MapPanel1, 0, 0, 100%x, 100%Y)
  If mFragment1.IsGooglePlayServicesAvailable = False Then
    ToastMessageShow("Google Play services not available.", True)
  Else
    mFragment1.Initialize("Map1", MapPanel1)
  End If
End Sub

Sub Map1_Ready
   gmap = mFragment1.GetMap
   gmap.AddMarker(30, 30, "test")
End Sub

My phone is not getting detected on my PC thru USB cable, hence unable to find out what the exactly the error is.

When I tested using GenyMotion, GenyMotion says Google Play Service is not available.
On the Phone, it just quit abnormally say "Unfortunately, the app has stopped".

If I use Activity.LoadLayout ie views via Designer then it is working fine and the map is shown on my phone.

A confirmation whether GoogleMaps works via code too will be appreciated.

The example code in the post #1 of this thread is also using designer to create the MapFragment.

Regards
Anser
 

Anser

Well-Known Member
Licensed User
Longtime User
The following is the error log

** Activity (homepage) Pause, UserClosed = false **
** Activity (officelocations) Create, isFirst = true **
** Activity (officelocations) Resume **
java.lang.RuntimeException: java.lang.NullPointerException
at anywheresoftware.b4a.objects.MapFragmentWrapper$1.onMapReady(MapFragmentWrapper.java:196)
at com.google.android.gms.maps.MapFragment$zza$1.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzo$zza.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:361)
at com.google.android.gms.maps.internal.v$a$a.a:)com.google.android.gms.alldynamite:82)
at maps.ei.bu$6.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at anywheresoftware.b4a.objects.MapFragmentWrapper$1.onMapReady(MapFragmentWrapper.java:181)
... 14 more


Regards
Anser
 

Anser

Well-Known Member
Licensed User
Longtime User
Are you using B4A v5.8? Have you added the map with the designer?
That was my question ie whether GoogleMaps work via code ?


I am using v5.8
With designer it is working fine.
I want to use Googlemap via code.
 

Anser

Well-Known Member
Licensed User
Longtime User
You must add it with the designer.
Ohh.
The previous version of GoogleMaps worked via code too. So doesn't it break backward compatibility ?

Thank you for the confirmation.
 

mangojack

Well-Known Member
Licensed User
Longtime User
Have followed the steps carefully .. but getting this error.

I have added the following res ..
#AdditionalRes: C:\android\extras\google\google_play_services\libproject\google-play-services_lib\res, com.google.android.gms

An error occured.
C:\android\extras\google\google-play-services_lib\res\values-v21\appinvite-styles.xml:5:error:Error retrieving parent for item:
No resource found that matches the given name '@ android:style/Theme.Material.Light.DialogWhenLarge.NoActionBar

Any help would be appreciated
Many thanks
 
Last edited:

dfrutos

Member
Licensed User
Longtime User
Erel, i have a problem.

When i load the layout with MapFragment, my app is close inmediatly...


This is my code... I try all options but not work...

#Region Project Attributes
#ApplicationLabel: Mapas
#VersionCode: 1
#VersionName:
'SupportedOrientations possible values: unspecified, landscape or portrait.
#SupportedOrientations: unspecified
#CanInstallToExternalStorage: False
#AdditionalRes: C:\Users\JV\AppData\Local\Android\android-sdk\extras\google\google_play_services\libproject\google-play-services_lib\res, com.google.android.gms
#ExcludeClasses: .games, .drive, .fitness, .wearable, .measurement, .cast, .auth, .nearby
#ExcludeClasses: .tagmanager, .analytics, .wallet, .plus, .vision, .gcm
'remove the following line if you use AdMob
#ExcludeClasses: .ads
#End Region

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

'Activity module
Sub Process_Globals

End Sub

Sub Globals
Private gmap As GoogleMap
Private mapa As MapFragment
End Sub

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

Sub MapFragment1_Ready
' gmap = MapFragment1.GetMap
' Dim m1 As Marker = gmap.AddMarker(10, 30, "test")
' m1.Snippet = "This is the snippet"
End Sub


And... the manifiest


'This code will be applied to the manifest file during compilation.
'You do not need to modify it in most cases.
'See this link for for more information: https://www.b4x.com/forum/showthread.php?p=78136
AddManifestText(
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="19"/>
<supports-screens android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:anyDensity="true"/>)
SetApplicationAttribute(android:icon, "@drawable/icon")
SetApplicationAttribute(android:label, "$LABEL$")
'End of default text.
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="AIzaSyBvaTs07boouzpahlscSjXQ5pJiKOkAgM4"/>
<meta-data android:name="com.google.android.gms.version"
android:value="@Integer/google_play_services_version" />
)



Thank you for your help....
Damián.
 

awakenblueheart

Member
Licensed User
Longtime User
Hi everyone,

I use the same code in the first post but still running into "ToastMessageShow("Please install Google Play Services.", True)" part.
Anyone help???

My code:
B4X:
#Region  Project Attributes
   #ApplicationLabel: B4A Example
   #VersionCode: 1
   #VersionName:
   'SupportedOrientations possible values: unspecified, landscape or portrait.
   #SupportedOrientations: unspecified
   #CanInstallToExternalStorage: False
   #AdditionalRes: C:\android-sdk\extras\google\google_play_services\libproject\google-play-services_lib\res, com.google.android.gms
   #ExcludeClasses: .games, .drive, .fitness, .wearable, .measurement, .cast, .auth, .nearby
   #ExcludeClasses: .tagmanager, .analytics, .wallet, .plus, .vision, .gcm
   'remove the following line if you use AdMob
   #ExcludeClasses: .ads
#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
  Private gmap As GoogleMap
  Private MapFragment1 As MapFragment
End Sub

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

Sub MapFragment1_Ready
  gmap = MapFragment1.GetMap
  Dim m1 As Marker = gmap.AddMarker(10, 30, "test")
  m1.Snippet = "This is the snippet"
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub
 

vfafou

Well-Known Member
Licensed User
Longtime User
Hi!
Check if you have the same library version <your android-sdk folder>\extras\google\google_play_services\libproject\google-play-services_lib\libs\google-play-services.jar
into your B4A libraries folder.
If you have an older library version into your B4A libraries, then you may have such problems.
 

Shay

Well-Known Member
Licensed User
Longtime User
how can I with the new 5.8 and google map v2, update the map (my location) once my location changed?
I used to do it using GoogleMapsExtra and OnMyLocationChangeListener, and then remove and create my marker
can it be done now without using GoogleMapsExtra (Fusedlocation in on different service)
 

Shay

Well-Known Member
Licensed User
Longtime User
It works after code changed I had to do, but I don't want to use is, since according to google: "use com.google.android.gms.location.FusedLocationProviderApi instead. "
 

Shay

Well-Known Member
Licensed User
Longtime User
yes, I thought about it, I just wondered if there is something "built in" in the google maps library
 
Status
Not open for further replies.
Top