Android Tutorial OSMDroid - MapView for B4A tutorial

nemiroG1

Member
Licensed User
Martin,
OK, I finally managed to try the URLTileSource for OSMDroid 4.1, and taking that, and combining it with the XML data you posted above worked straight off! Thank you! For reference, here is the code (not that it is hard to figure out) to use aviation sectional maps (US Only at this time):

B4X:
Version=4.2
IconFile=
NumberOfModules=0
Build1=Default,uk.co.martinpearman.b4a.osmdroiddemo
DoNotOverwriteManifest=False
ManifestCode='This code will be applied to the manifest file during compilation.~\n~'You do not need to modify it in most cases.~\n~'See this link for for more information: http://www.basic4ppc.com/forum/showthread.php?p=78136~\n~AddManifestText(~\n~<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="14"/>~\n~<supports-screens android:largeScreens="true" ~\n~    android:normalScreens="true" ~\n~    android:smallScreens="true" ~\n~    android:anyDensity="true"/>)~\n~SetApplicationAttribute(android:icon, "@drawable/icon")~\n~SetApplicationAttribute(android:label, "$LABEL$")~\n~'End of default text.~\n~~\n~'    required for ScaleBarOverlay?~\n~SetApplicationAttribute(android:hardwareAccelerated, "false")
NumberOfFiles=0
NumberOfLibraries=2
Library1=core
Library2=osmdroid_4_1
@EndOfDesignText@
#Region  Project Attributes 
    #ApplicationLabel: OSMDroid demo
    #VersionCode: 1
    #VersionName: 
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

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

Sub Process_Globals
    Dim Constants1 As OSMDroid_Constants
End Sub

Sub Globals
    Dim InitialGeoPoint As OSMDroid_GeoPoint
    Dim MapView1 As OSMDroid_MapView
End Sub

Sub Activity_Create(FirstTime As Boolean)
    '    check the manifest for edits made re hardware acceleration
   
    MapView1.Initialize("")
   
    Dim MyTileSourceName As String="MyTileSourceName"
    Dim TileSourceFactory1 As OSMDroid_TileSourceFactory
    If Not(TileSourceFactory1.ContainsTileSource(MyTileSourceName)) Then
        Dim MyTileSource As OSMDroid_UrlTileSource
        MyTileSource.Initialize(MapView1, MyTileSourceName, "http://wms.chartbundle.com/tms/v1.0/sec/%3$d/%1$d/%2$d.png?type=google", 0, 16, 256)
        TileSourceFactory1.AddTileSource(MyTileSource)
    End If
   
    MapView1.SetTileSource(TileSourceFactory1.GetTileSource(MyTileSourceName))
   
    MapView1.GetOverlayManager.GetTilesOverlay.SetLoadingBackgroundColor(Colors.Green)
    MapView1.GetOverlayManager.GetTilesOverlay.SetLoadingLineColor(Colors.Red)
    MapView1.SetBuiltInZoomControls(True)
    MapView1.SetMultiTouchControls(True)
   
    '    now set the initial view
    '    set the zoom before the center
    InitialGeoPoint.Initialize(52.75240, 0.4040)
    MapView1.GetController.SetZoom(12)
    MapView1.GetController.SetCenter(InitialGeoPoint)
   
    Activity.AddView(MapView1, 0,0, 100%x, 100%y)
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub
 

jsk001

Member
Licensed User
...Is there a way to display the marker info immediately (without clicking) ???


AIM: Add a MarkersOverlay layer to the MapView.

With MarkersOverlay you can add Marker objects to your MapView.

If you use the default Marker icon, then MarkersOverlay requires the resources in the drawable-nodpi folder that is included with the library download.
Copy the drawable-nodpi to your project's Objects/res folder and ensure that all files in that folder are set to read-only


MarkersOverlay generates two events: Click and LongClick.

A Marker object is initialized:

B4X:
Dim Marker1 As Marker
Marker1.Initialize("A title", "A description", aLatitude, aLongitude, anIcon)
When a Marker is Clicked or LongClicked, the title, description and position of the Marker are pass as parameters to the event listener.
The position is passed as a GeoPoint object.

MarkersOverlay leaves the developer to take action when a Marker is Clicked or LongClicked - it does nothing more than generate the events.

Here's the example code:

B4X:
Sub Process_Globals
   Dim MapCenter As GeoPoint
   Dim TileSource As String
   Dim ZoomLevel As Int
End Sub

Sub Globals
   Dim MapView1 As MapView
   Dim MinimapOverlay1 As MinimapOverlay
   Dim ScaleBarOverlay1 As ScaleBarOverlay
   Dim TileSourceSpinner As Spinner
  
   '   create the MarkersOverlay
   Dim MarkersOverlay1 As MarkersOverlay
End Sub

Sub Activity_Create(FirstTime As Boolean)
   '   update the MenuItems
   Activity.AddMenuItem("Fit map to markers", "MenuItemSelect")
  
   '   MapView initialized with no EventName as we'll not be listening for MapView events
   MapView1.Initialize("")
   Activity.AddView(MapView1, 0, 48dip, 100%x, 100%y-48dip)
  
   MapView1.SetMultiTouchEnabled(True)
   MapView1.SetZoomEnabled(True)
  
   '   initialize the MarkersOverlay and add it to the MapView
   '   an EventName is required as we will listen for the two events that MarkersOverlay generates
   MarkersOverlay1.Initialize(MapView1, "MarkersOverlay1")
   MapView1.AddOverlay(MarkersOverlay1)
  
   '   create and initialize 2 Markers
  
   '   for Marker1 i'll use a custom icon
   Dim Icon As BitmapDrawable
   Icon.Initialize(LoadBitmap(File.DirAssets, "my_icon.png"))
  
   Dim Marker1 As Marker
   Marker1.Initialize("Home sweet home", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi egestas suscipit convallis. Etiam pellentesque gravida est, quis luctus nunc commodo at. Nam et risus orci. Integer malesuada lorem dolor. Maecenas vestibulum cursus enim, tincidunt luctus libero placerat non. In vitae metus tellus, nec euismod nibh. Phasellus ut quam vitae justo sagittis auctor. Sed vel sapien dolor. Etiam ut sem id dolor iaculis ullamcorper. Aenean eget sem nibh, a tempor augue. Nulla interdum luctus molestie.", 52.75610, 0.39748, Icon)
  
   '   Marker2 will display the default OSMDroid icon
   '   the default icon is used if Null is passed as the Icon parameter
   Dim Marker2 As Marker
   Marker2.Initialize("Elsewhere", "Downham Market", 52.60801, 0.39047, Null)
  
   '   create a List and initialize it with the 2 Markers
   Dim Markers As List
  
   '   ** example code updated **
   '   Markers.Initialize2(Array As Marker(Marker1, Marker2))   '   this is the previous code
   Markers.Initialize2(Array As Object(Marker1, Marker2))      '   this is the new code
  
   '   add the List of Markers to the MarkersOverlay
   MarkersOverlay1.AddMarkers(Markers)
  
   If FirstTime Then
      TileSource="Mapnik"
     
      '   fit the MapView to the MarkersOverlay
      MapView1.FitMapToBoundingBox(MarkersOverlay1.GetBoundingBox)
   Else
      '   restore saved zoom level and map center
      MapView1.Zoom=ZoomLevel
      MapView1.SetCenter3(MapCenter)
   End If
  
  
   ScaleBarOverlay1.Initialize(MapView1)
   MapView1.AddOverlay(ScaleBarOverlay1)
  
   '   ensure that the MinimapOverlay is the LAST overlay added to the MapView
   MinimapOverlay1.Initialize(MapView1)
   MapView1.AddOverlay(MinimapOverlay1)
  
   TileSourceSpinner.Initialize("TileSourceSelect")
   Activity.AddView(TileSourceSpinner, 0, 0, 100%x, 48dip)
  
   TileSourceSpinner.AddAll(MapView1.GetTileSources)
   TileSourceSpinner.Prompt="Select a TileSource"
   TileSourceSpinner.SelectedIndex=TileSourceSpinner.IndexOf(TileSource)
   TileSourceSelect_ItemClick(TileSourceSpinner.SelectedIndex, TileSourceSpinner.SelectedItem)
End Sub

Sub Activity_Resume
End Sub

Sub Activity_Pause (UserClosed As Boolean)
   MapCenter=MapView1.GetCenter
   TileSource=MapView1.GetTileSource
   ZoomLevel=MapView1.Zoom
End Sub

'   two event listeners listen for the MarkersOverlay's two events

Sub MarkersOverlay1_Click(Title As String, Description As String, Point As GeoPoint)
   Log("MarkersOverlay1_Click")
   ToastMessageShow(Title&": "&Description, True)
End Sub

Sub MarkersOverlay1_LongClick(Title As String, Description As String, Point As GeoPoint)
   Log("MarkersOverlay1_LongClick")
   ToastMessageShow(Title&": Latitude="&Point.Latitude&", Longitude="&Point.Longitude, True)
  
   '   zoom the map in and center (with animation) on the LongClicked Marker
   MapView1.Zoom=MapView1.GetMaxZoomLevel-1
   MapView1.AnimateTo3(Point)
End Sub

Sub MenuItemSelect_Click
   Dim MenuItem As String
   MenuItem=Sender
   Select MenuItem
      Case "Fit map to markers"
         '   fit the MapView to the MarkersOverlay
         MapView1.FitMapToBoundingBox(MarkersOverlay1.GetBoundingBox)
   End Select
End Sub

Sub TileSourceSelect_ItemClick (Position As Int, Value As Object)
   MapView1.SetTileSource(Value)
   MinimapOverlay1.SetTileSource(Value)
End Sub
A MarkersOverlay is created, initialized and added to the MapView.

Two Markers are created and initialized.
The first Marker is initialized with a custom icon, the second Marker is initialized with Null passed as it's icon so the second Marker will display the default OSMDroid icon.

MarkerOverlay has a single method to add Markers - AddMarkers (Markers As List).
So you must pass this method a List of Marker objects.

If this is the first time that the activity has been created then the MapView FitMapToBoundingBox method is called passing the bounding box returned by the MarkersOverlay GetBoundingBox method.
The map center and zoom level are adjusted to fully display all Markers on the MarkersOverlay.

If this is not the first time that the activity has been created then the previously saved map center and zoom level are restored.
In Activity_Pause the map center and zoom level are saved.

A Click on a Marker will display a toast message with the Marker's Title and Description.

A LongClick on a Marker will display a toast message with the Marker's Title, Latitude and Longitude.
It will also zoom the map in to it's maximum zoom level minus one and center on the Marker's position using the MapView AnimateTo methid.
The animation will likely not be noticeable unless the tiles for the zoomed in area have already been cached.

MarkersOverlay and MarkersFocusOverlay (which i shall cover next) are both functional but lacking in features i think.
You cannot change a Marker's position for example, and if you add Markers and have previously added Markers then the previous Markers are replaced not added to.

Another point to note is how difficult it is to Click or LongClick a small icon.
The default OSMDroid icon seems to small to me, the custom icon i have used is much easier to Click or LongClick.

I shall look at creating a more feature packed MarkersOverlay and MarkersFocusOverlay over the next week or so.

Anyway, on to the last example - the MarkersFocusOverlay.

Martin.
 

shashkiranr

Active Member
Licensed User
Hi Warwound,

I want to create an offiline map. I am using MOBAC but i am not able to download for mapnik as they have removed the support to download. Is there any way i can download and create the files for osm?

Regards,
SK
 

warwound

Expert
Licensed User
Hi Warwound,

I want to create an offiline map. I am using MOBAC but i am not able to download for mapnik as they have removed the support to download. Is there any way i can download and create the files for osm?

Regards,
SK
Take a look here:
https://switch2osm.org/serving-tiles/

You could set up your own tile server and connect to your tile server with MOBAC.

If you don't have a linux box available I'd suggest using VirtualBox to create a virtual Ubuntu 12.04 box.
Install the packages: https://switch2osm.org/serving-tiles/building-a-tile-server-from-packages/
Then download the binary map data and you can then generate your own tiles.
 

Carlo2015

Member
Licensed User
hi! Im new to b4a and I am impressed with its capabilities. and to you warwound for this great lib.

now my question is can I use this http://download.geofabrik.de/asia.html with your library? and if yes then can you please show some example?

when i browsed the folder where the tiles are found the format of the files are in .png.tile but the file from the above link is in pbf and it says "suitable for Osmium, Osmosis, imposm, osm2pgsql, mkgmap, and others".

I am confused about this one.

Or can you please give me a link where I can download mapnik tiles for asia or just for the Phlippines?

I need to let my users have it preinstalled before they went on their way.

Thanks

Edit: Im now experimenting with Mobile Atlas Creator. Will ask more questions if I hit a wall again.
 
Last edited:

warwound

Expert
Licensed User
@Carlo2015

There links to .osm.pbf file on the Geofabrik page and you can download these and display them offline on either OSMDroid or GoogleMaps.
Search the forum for MapsforgeTileSource (for OSMDroid) and MapsForgeTileProvider (GoogleMaps).

These .osm.pbf files are binary databases containing Open Street Map data and are far smaller in size than an equivalent 'offline tile archive' created by MOBAC which would contains 1000s of tile images.
 

Carlo2015

Member
Licensed User
warwound thanks for the fast reply, I was able to download maps for OSMPublicTransport but the files inside the folders(zip) are just .png whereas the files created by your examples are in .png.tile

I am more confused now. :)

Anyway I'm no way near giving up.
 
Last edited:

warwound

Expert
Licensed User
.png and .png.tile are identical...

I think that naming a .png to .png.tile simply prevents the android media scanner finding the tile images and so prevents the tile images from appearing in the device's Gallery.
 

Carlo2015

Member
Licensed User
Great!

I am currently fetchng tiles for the whole Philippines. I will just use a windows application to rename all png in the folder.

I will update here for the results.


Thanks.
 

warwound

Expert
Licensed User
Great!

I am currently fetchng tiles for the whole Philippines. I will just use a windows application to rename all png in the folder.

I will update here for the results.


Thanks.
http://download.geofabrik.de/asia.html
See the .oms.pbf binary data for the entire Philippines is 'just' 111MBs?
Once converted from .osm.pbf format to the MapsForge .map format that's likely to be around 60MBs.

So your choice is to have either:
  • A (massive) tile archive containing many .png tile images.
    This will look best on the device - the tiles should be quick to load.
    Coverage of different areas and zoom levels will depend entirely on what tile images you have in your tile archive.
    The tile archive will likely be far larger than 60MBs.
  • A single MapsForge binary database of around 60MBs.
    Rendering map tiles on the fly on the device is a single threaded solution.
    So when your map requires tiles they get queued and rendered one at a time.
    That results in a not so good user experience - not as good as an offline tile archive.
    But the MapsForge .map file will give you coverage of the entire Philippines at all zoom levels.

I've downloaded and am converting the Philippines .osm.pbf file to MapsForge .map format now and i'll post again when the conversion is complete.
You can compare an offline tile archive to a MapsForge binary database and choose which one to use.

Martin.
 

warwound

Expert
Licensed User
The Philippines .osm.pbf file converted to a MapsForge .map database of 111Mbs in size.
Normally the conversion results in a much smaller file but i guess with all the coastline data for the Philippines, the file size didn't reduce.

You can download the Philippines MapsForge .map file here:
http://b4a.martinpearman.co.uk/osmdroid/philippines.map.zip

Can you let me know when you have downloaded it - i'll then delete it from my server.

Thanks.
 

rayofcumbria

Member
Licensed User
Hi Warwound,

I want to create an offiline map. I am using MOBAC but i am not able to download for mapnik as they have removed the support to download. Is there any way i can download and create the files for osm?

Regards,
SK
Hi SK, try here for offline maps
http://download.mapsforge.org/maps/

here's how I load them too:
' OSM 4.1 library used
Private osmMaps As OSMDroid_MapView
Private MFTSrc As MapsForgeTileSource

MFTSrc.GetMapsForgeTileSourceOptions.SetMapDatabaseFile(File.DirRootExternal, "mapname.map")
MFTSrc.GetMapsForgeTileSourceOptions.SetTileSourceName("MyOwnMap")
MFTSrc.Initialize

osmMaps.Initialize("osmMap")

osmMaps.SetUseDataConnection(True)
osmMaps.SetTileSource(MFTSrc)
 
Last edited:

Tom1s

Member
Licensed User
I couldn't find osmroid 4.1 mapsforgetilesource example ? Is the older one still working with 4.1?
 

Tom1s

Member
Licensed User
I got it working. It works with Activity.AddView(MapView1, 0,0, 100%x, 100%y)
Not with panel7.AddView(MapView1, 0,0, 100%x, 100%y)

Is it possible to use it somehow like this:
Activity.LoadLayout("Pagemain") 'containts actionbar and pcontent

pContent.LoadLayout("page1")'contains panels

pContent.AddView(MapView1, 0,0, 100%x, 100%y) ' this works one time. I have a menu and i like to switch between panels and this map?

Removeviews and then again?
 
Last edited:
Top