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:

wes58

Active Member
Licensed User
Longtime User
You will need to use a different activity for the map.
I thought about it after I posted a question, but it complicates things since the map doesn't cover the whole screen, there are buttons and labels (tabs) which I don't want to cover and I want to have access to.
 

wheretheidivides

Active Member
Licensed User
Longtime User
Why does everything take 100 steps to do? hmm. It worked. Cool. My phone has 2.1 but my tablet 3+. Now if I can figure out how to set locations. Good job erel as always.
 

George Popovic

Member
Licensed User
Longtime User
Error Initializing Map

Hi,

I am going throught this tutorial and I get a map to show but no marker.
The log does not show "Map Ready" so Sub Map Ready does not get executed. Any ideas??? Thanks
 

George Popovic

Member
Licensed User
Longtime User
Tried the suggested APK, same thing. I get a map to show but no marker.
The log does not show "Map Ready". The device is a Motorola tablet.
 

magarcan

Active Member
Licensed User
Longtime User
Hi!

I've some questions about that :eek:
-Do I need to have installed also Google Map app in order to use mine?
-Can I add a Placemark with it's own Rich text description (I mean text, images...)?
-Can I list all Placemarks in my map, for example, 12Km around any position?

Maybe some of that questions are answered in the documentation, where can I find it?

Cheers!
 
Last edited:

warwound

Expert
Licensed User
Longtime User
Due to popular demand(!!) i have created the GoogleMapsExtras library adding support for more Google Maps Android v2 features in b4a.
GoogleMapsExtras library files can be found in this thread: http://www.b4x.com/forum/additional...pdates/26277-googlemapsextras.html#post152004

This example shows the syntax to use to add a custom TileOverlay to your map.
The example displays tiles from the OpenStreetMap project.

B4X:
Sub Process_Globals
End Sub

Sub Globals
    Dim MapFragment1 As MapFragment
    Dim GoogleMap1 As GoogleMap
    Dim MapPanel As Panel
   Dim TileOverlay1 As TileOverlay
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
      '   set the map-type to none
      '   the new TileOverlay is not transparent and we do not want to load any of the built in tile sources
      GoogleMap1.MapType=GoogleMap1.MAP_TYPE_NONE
      
      Dim GoogleMapsExtras1 As GoogleMapsExtras
      Dim TileOverlayOptions1 As TileOverlayOptions
      Dim UrlTileProvider1 As UrlTileProvider
      
      '   Url parameters are %1$d tileX, %2$d tileY, %3$d zoom
      '   OSM slippy map tilename convention is <url>/zoom/x/y.png
      
      UrlTileProvider1.Initialize("http://b.tile.openstreetmap.org/%3$d/%1$d/%2$d.png", 256, 256)
      TileOverlayOptions1.Initialize
      TileOverlayOptions1.SetTileProvider(UrlTileProvider1)
      TileOverlay1=GoogleMapsExtras1.AddTileOverlay(GoogleMap1, TileOverlayOptions1)
      
      Dim Marker1 As Marker
        Marker1=GoogleMap1.AddMarker(52.75619, 0.3980, "Home Sweet Home")
        Dim CameraPosition1 As CameraPosition
        CameraPosition1.Initialize(52.75619, 0.3980, 6)
        GoogleMap1.AnimateCamera(CameraPosition1)
    End If
End Sub

Sub ClearCacheButton_Click
   TileOverlay1.ClearTileCache
End Sub

Sub RemoveButton_Click
   TileOverlay1.Remove
End Sub

Sub VisibilityButton_Click
   TileOverlay1.Visible=Not(TileOverlay1.IsVisible)
End Sub

I disable the built in tile sources using GoogleMap1.MapType=GoogleMap1.MAP_TYPE_NONE and the OSM tiles display on their own.
If you had a semi-transparent set of custom tiles you'd probably enable one of the built in tile sources (road map, satellite etc) and then display your semi-transparent tiles over the built in tile source.

You can display tiles from a tile server if you can pass a suitable UrlTemplate String to the UrlTileProvider Initialize method.
The UrlTemplate contains placeholders which get replaced each time a tile is requested by the map.
In the example, the UrlTemplate is http://b.tile.openstreetmap.org/%3$d/%1$d/%2$d.png.
The placeholders represent:
  • %1$d tileX coordinate.
  • %2$d tileY coordinate.
  • %3$d zoom level.

There's another public tile server at: Free Relief Layers for Google Maps and you could use the maps-for-free tiles with a UrlTemplate of http://www.maps-for-free.com/layer/relief/z%3$d/row%2$d/%3$d_%1$d-%2$d.jpg.
You'll probably notice that these public tile servers are far slower to serve tiles than the Google Maps tile servers - Google have the capital to pay for lots of very fast tile servers and a very fast connection to the internet, the public tile servers are generally funded by donations and haven't got the resources needed to compete with Google.

I haven't experimented yet to see if we can use a local file based Url for the tiles, in theory it'd work but needs to be tested...

Martin.
 

Attachments

  • TileOverlayDemo.zip
    8 KB · Views: 1,052

warwound

Expert
Licensed User
Longtime User
This example shows how to add a GroundOverlay to your map.
The example replicates the official javascript Google Maps API example at https://google-developers.appspot.com/maps/documentation/javascript/examples/groundoverlay-simple

B4X:
Sub Process_Globals
End Sub

Sub Globals
    Dim MapFragment1 As MapFragment
    Dim GoogleMap1 As GoogleMap
    Dim MapPanel As Panel
   Dim GroundOverlay1 As GroundOverlay
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
      '   replicate the web based API GroundOverlay example at: https://google-developers.appspot.com/maps/documentation/javascript/examples/groundoverlay-simple
      GoogleMap1.MapType=GoogleMap1.MAP_TYPE_NORMAL
      
      Dim GoogleMapsExtras1 As GoogleMapsExtras
      Dim GroundOverlayOptions1 As GroundOverlayOptions
      Dim LatLngBounds1 As LatLngBounds
      Dim SouthWest, NorthEast As LatLng
      
      SouthWest.Initialize(40.712216,-74.22655)
      NorthEast.Initialize(40.773941,-74.12544)
      LatLngBounds1.Initialize(SouthWest, NorthEast)
      GroundOverlayOptions1.Initialize
      GroundOverlayOptions1.Image(LoadBitmap(File.DirAssets, "newark_nj_1922.jpg")).PositionFromBounds(LatLngBounds1).SetTransparency(0.2)
      GroundOverlay1=GoogleMapsExtras1.AddGroundOverlay(GoogleMap1, GroundOverlayOptions1)
      
        Dim CameraPosition1 As CameraPosition
        CameraPosition1.Initialize(40.7395, -74.175, 12)
        GoogleMap1.AnimateCamera(CameraPosition1)
    End If
End Sub

Sub RemoveButton_Click
   GroundOverlay1.Remove
End Sub

Sub VisibilityButton_Click
   GroundOverlay1.Visible=Not(GroundOverlay1.IsVisible)
End Sub

One thing to note is that you'll run into the common out of memory exceptions if you try to use a large image as a ground overlay.
I did experiment with adding the manifest attribute largeHeap and that enabled me to use a large bitmap where previously (without largeHeap) the Activity force closed with an out of memory exception.
More details about that can be found in this thread: http://www.b4x.com/forum/additional...ogle-map-library-tile-overlay.html#post149931.

If you have a lot of imagery to overlay on to the map then a TileOverlay seems the better solution.

Martin.
 

Attachments

  • GroundOverlayDemo.zip
    145.9 KB · Views: 917
Last edited:

warwound

Expert
Licensed User
Longtime User
This example shows partial support for the Polygon object.
I haven't had time to add the code required to enable holes in polygons, so currently you can display just basic simple polygons.
(Hopefully i'll add support for holes within the next week).

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 Point1, Point2, Point3, Point4, Point5 As LatLng
      Dim Points As List
      
      Points.Initialize
      
      '   points must be ordered in a  counterclockwise order
      '   (i found FillColor will fail if not correctly ordered)
      
      Point1.Initialize(52.756, 0.400)
      Points.Add(Point1)
      Point2.Initialize(52.417, 0.753)
      Points.Add(Point2)
      Point3.Initialize(52.638, 1.291)
      Points.Add(Point3)
      Point4.Initialize(52.902, 0.617)
      Points.Add(Point4)
      Point5.Initialize(52.756, 0.400)
      Points.Add(Point5)   '   closes the path
      
      PolygonOptions1.Initialize
      PolygonOptions1.FillColor=Colors.ARGB(128, 255, 0, 0)
      PolygonOptions1.Points=Points
      PolygonOptions1.StrokeColor=Colors.Black
      PolygonOptions1.StrokeWidth=2
      
      Polygon1=GoogleMapsExtras1.AddPolygon(GoogleMap1, PolygonOptions1)
      
        Dim CameraPosition1 As CameraPosition
        CameraPosition1.Initialize(52.689, 0.770, 10)
        GoogleMap1.AnimateCamera(CameraPosition1)
    End If
End Sub

Sub RemoveButton_Click
   Polygon1.Remove
End Sub

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

The map displays a polygon with 4 vertices over Norfolk, UK.
The polygon has a 2 pixel wide black border and a semi-transparent red fill color.

Note that when adding points you must order the points in a counterclockwise direction.
I didn't do that originally and the polygon failed to display any fill color.
Correctly ordering the points fixed that and the fill color was displayed.

Martin.
 

Attachments

  • PolygonDemo.zip
    7.9 KB · Views: 844

rboeck

Well-Known Member
Licensed User
Longtime User
Hi,
sorry for my notunderstanding: what steps from posting 1 are needed to use the demo projects. They are ready signed or do i have to change them to my signatures. At this time i dont want to make my own project, i want only study the possibilities...
Greetings
Reinhard
 

warwound

Expert
Licensed User
Longtime User
Hi,
sorry for my notunderstanding: what steps from posting 1 are needed to use the demo projects. They are ready signed or do i have to change them to my signatures. At this time i dont want to make my own project, i want only study the possibilities...
Greetings
Reinhard

I was forgetting about the key signing 'hassle' required...

I'd guess that none of the example projects i uploaded will run as they are - my API key will not be valid for other users.

So you could take a working project such as the project you created from post #1 in this thread, and copy/paste my example code into that working project.
(Note that my examples all use a .bal layout file which can be seen in the Files tab, the GroundOverlay example also requires a .jpg which can also be seen in the files tab).

Or you could open my examples and go though the process of obtaining a valid API key to compile my examples on your computer.

(What a hassle lol).

Martin.
 

ErickAsas

Member
Licensed User
Longtime User
Marker DragEnd Events and Labels

Hi Erel,

How do you implement DragEnd event with the new google map library?

Can you post an example where you can customize the contents of the info window? ie, bold text, line breaks etc...

:sign0104:
 
Status
Not open for further replies.
Top