Using OpenStreetMap
Published? true
FormatLanguage: WikiFormat
Problem:
You want to use OpenStreetMap (OSM) map data to display maps in your application.
Solution:
Use the third-party osmdroid library to interact with OpenStreetMap data.
Discussion:
OpenStreetMap is a free, editable map of the world. The OpenStreetMapView is a (almost) full/free replacement for Android's MapView class. See the osmdroid googlecode page for more details.
The capabilities of OSM and Google maps are similar; some people prefer
OSM because of the fewer limitations on what you can do with the data.
For example, you are forbidden from using Google Map data for turn-by-turn navigation, because much of Google's data is licensed from commercial GPS
data services. See http://www.openstreetmap.org/about for more information.
To use OSM in your android app, you need to include two jars in the Android project namely, osmdroid-android-x.xx.jar and slf4j-android-1.5.8.jar. OSMDroid is a set of tools for OpenStreetMap data; SLF4J is (yet another) simplified logging facade. These can be downloaded from the links below:
Or you can use the Maven artifact (see Hello World - Maven Version), which is currently:
<dependency>
<groupId>org.osmdroid</groupId>
<artifactId>osmdroid-android</artifactId>
<version>4.2</version>
</dependency>
See Referencing libraries to implement external functionality to learn how to use external libraries in your Android project.
After adding the JARs to the project we can start coding.
- You need to add a OSM MapView to an XML layout like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<org.osmdroid.views.MapView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/mapview">
</org.osmdroid.views.MapView>
</LinearLayout>
- Also include the ACCESS_NETWORK_STATE and INTERNET permissions in the AndroidManifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
- Now we have to use this MapView in the Activity code. This is done exactly as you would do in the case of Google maps.
private MapView mapView;
private MapController mapController;
mapView = (MapView) this.findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setMultiTouchControls(true);
mapController = this.mapView.getController();
mapController.setZoom(2);
Once you are done with the code, go ahead and run it! This is how the application should look:
Download:
The source code for this project is in the Android Cookbook repository,
http://github.com/IanDarwin/Android-Cookbook-Examples/,in the subdirectory OSMIntro.