One of the alternatives to using Google maps in your applications is the use of OpenStreetMap maps. They are free and work pretty well.

We start by adding the necessary libraries for the project ie osmdroid-android-4.0.jar and slf4j-android-1.5.8.jar (or their newer versions if they appear):

 

We also need to add these libraries to the Build Path project. We do this by going to the project properties, then going to “Java Build Path” and selecting “Add Jars”:

 

 

We choose these two newly added libraries and we approve. Time to insert a map object into our layout. The org.osmdroid.views.MapView element is shown below:

 

As the application will need to download data (maps) from the internet, we must take care of the appropriate permissions. So add the following lines to the manifest file:

<uses-permission android: name = “android.permission.INTERNET” />

<uses-permission android: name = “android.permission.ACCESS_NETWORK_STATE” />

just behind the tag

These are sufficient permissions necessary to operate the OpenStreetMaps map. In our example, we will use our real GPS position and display the map section around our position. For this reason, you will need to add additional permissions:

<uses-permission android: name = “android.permission.ACCESS_FINE_LOCATION” />

<uses-permission android: name = “android.permission.ACCESS_COARSE_LOCATION” />

In case we do not use the GPS position, we do not add the latter. In general, the whole thing should look like this:

 

We now go to the activity that we use to present the map. I add a few boxes to the class. Fields in lines 17-20 are related to the use of GPS, so if we do not intend to use it, we do not define them. Only objects from line 23.24 will be needed:

 

 

The code from lines 42-45 is related to the download of the GPS position, I discussed in one of the previous chapters exactly how the code works and I will not be here. We are interested in lines 35-40 and 46-50. Line 35 is not an element associated with the map itself, it is used to associate references to a map component. In line 36 we indicate the source from which we download maps. Lines 37 and 38 define the behavior of the map. SetBuildInZoomControls (line 37) sets whether you want to zoom in or out on the map (if you specify true, the + and – buttons on the map will be available). The setMultiTouchControls (line 38) method sets the ability to use touch gestures on the screen – such as zooming in and out with two fingers. In line 40 we define the default map approximation. In line 46 we create a GeoPoint object representing our location. In line 49 we center the map at the point indicated by the geoPoint object set to line 46. Calling the invalidate method on line 50 is a refreshing of the view.