Build native applications on Android devices
An open source toolset for building mapping applications for Android devices with great flexibility for visual styling and customizability.
API overview
This guide will take you through the process of adding a map to your Android app. It assumes you have a Java IDE (like Android Studio) with the Android SDK installed, an application project open, and general familiarity with building User Interfaces in Android.App permissions and services
Ensure the following core permissions are requested in your AndroidManifest.xml file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />If the app is targeting Android Marshmallow (API 23) or later it's necessary to request permissions at runtime.
While your AndroidManifest.xml file is open, you should also include the telemetry service:
<service android:name="com.mapbox.mapboxsdk.telemetry.TelemetryService"/>MapView and MapboxMap
MapView and MapboxMap are the key components of the Mapbox Android SDK. MapView behaves like any other View and its behavior can be changed statically with an XML layout file, or programmatically during runtime. You can think of MapboxMap as the controller class for your map. It includes methods to set and move the camera position, add markers, configure user interatcions, and more.
Lifecycle methods
The MapView contains its own lifecycle methods for managing Android's OpenGL lifecycle that must be called directly from the containing Activity. In order for your app to correctly call the MapView's lifecycle methods, you must override the following lifecycle methods in the Activity that contains the MapView:
onCreate();
onResume();
onPause();
onSaveInstanceState();
onLowMemory();
onDestroy();XML layout
To add the MapView as a layout element, add the following to your xml file:
<com.mapbox.mapboxsdk.maps.MapView
android:id="@+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
mapbox:style_url="@string/style_mapbox_streets"
mapbox:access_token="<your access token here>"/>And then you can call it programmatically within an Activity:
findViewById(R.id.mapview);Access tokens
An access token is necessary to use Mapbox services and APIs, such as maps, directions, and geocoding. Your access tokens can be managed in your account settings, where you can retrieve current tokens and generate new ones. You should create a new token for each of your apps, which will help you track usage and minimize disruption in the event a token needs to be revoked.
Telemetry opt out
Mapbox Telemetry is a powerful location analytics platform included in this SDK. By default, anonymized location and usage data is sent to Mapbox whenever the host app causes it to be gathered. The Mapbox Terms of Service require your app to provide users with a way to individually opt out of Mapbox Telemetry, which is provided automatically as part of the attribution control. If you hide the attribution control, you must provide an alternative opt out for your users to use.
Map styles
The Mapbox Android SDK is designed to work with the custom styles you create in Mapbox Studio, but also comes bundled with five professional styles that will look great in your app:
- Mapbox Streets: Our signature style. Read the blog post for more on the mobile-specific considerations in this style.
- Emerald: Great for transportation and outdoor terrain. Find out more about the data sources.
- Light and Dark: Light- and dark-colored styles that are great for data overlays. Use them for day and night modes, underlays for bright data atop, and more.
- Satellite and Satellite Streets: The best-looking, most accurate, and most up-to-date satellite imagery available anywhere. Check out our blog for the latest on our cutting-edge techniques and data.
- Hybrid: Unobtrusive labels and roads atop the Satellite style for easy wayfinding.
To use a custom style, paste your style URL into your MapView's mapbox:style_url attribute in your activity's layout file. If you would like to change the map style later on, call MapboxMap.setStyleUrl() with the new style and your map will update.
Attribution
You must comply with the licensing terms of any map data in your application, including Mapbox Streets or other Mapbox maps if used. A small attribution control will be displayed on the map view automatically. The attribution control may be moved or removed as necessary, so long as the required attribution is reasonably provided in your app.
For more information on Mapbox’s attribution requirements, click here.
Supported Android versions
The Mapbox Android SDK is supported for apps running Android API 15 (Ice Cream Sandwich MR1) and above. To ensure that it works in your app, please set minSdkVersion in the App Manfifest to no lower than 15.
<uses-sdk android:minSdkVersion="15"
android:targetSdkVersion="integer"
android:maxSdkVersion="integer" />Include Mapbox Android Services in your application
An open source toolset for building applications that need directions, geocoding, or static map imagery. Two libraries are at your disposal: a Java library compatible with any Java application and an Android library intended to be used specifically for Android applications.
Mapbox Android Services (MAS)
This guide will take you through the process of adding Mapbox Android Services to your app. It assumes you have a Java IDE (like Android Studio) with the Android SDK installed, an application project open, and general familiarity with building User Interfaces in Android.
This library needs one core permission added to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET" />Directions
The MapboxDirections object handles requests to and responses from the Mapbox Directions API. For example, to get driving directions from San Francisco to San Jose:
// San Francisco
final Position origin = Position.fromCoordinates(-122.416667, 37.783333);
// San Jose
final Position destination = Position.fromCoordinates(-121.9, 37.333333);
MapboxDirections client = new MapboxDirections.Builder()
.setOrigin(origin)
.setDestination(destination)
.setProfile(DirectionsCriteria.PROFILE_DRIVING)
.setAccessToken("<your access token here>")
.build();Once the client object has been created, you can launch a synchronous request to the Mapbox Directions API (remember not do this in the main UI thread):
Response<DirectionsResponse> response = client.execute();Or an asynchronous request (you need to provide your own Callback<DirectionsResponse>):
client.enqueueCall(callback)The DirectionsResponse object contains the full response from the Mapbox Directions API, including route geometry, turn-by-turn steps, distance, and more (see the Mapbox Directions API documentation for more). For example, to get the distance and duration for the sample route queried above:
DirectionsRoute route = response.body().getRoutes().get(0);
route.getDistance();
route.getDuration();Geocoder
The MapboxGeocoding object handles requests to and responses from the Mapbox Geocoding API. For example, to make a forward geocoding request with a proximity parameter:
// position used for proximity
Position position = Position.fromCoordinates(-73.98572, 40.74843);
MapboxGeocoding client = new MapboxGeocoding.Builder()
.setAccessToken("<your access token here>")
.setLocation("Empire State Building")
.setProximity(position)
.build();To make a reverse geocoding request (turn a pair of lat/lon coordinates into a meaningful place name) and restrict the results to points of interest (POI):
// the position which you'd like to get info about
Position position = Position.fromCoordinates(-73.98572, 40.74843);
MapboxGeocoding client = new MapboxGeocoding.Builder()
.setAccessToken("<your access token here>")
.setCoordinates(position)
.setType(GeocodingCriteria.TYPE_POI)
.build();Once the client object has been created, you can launch a synchronous request (remember not do this in the main UI thread):
Response<GeocodingResponse> response = client.execute();Or an asynchronous request (you need to provide your own Callback):
client.enqueueCall(callback)Static Image
Static maps are standalone images that look like an embedded map without interactivity or controls. The MapboxStaticImage object handles requests to and responses from the Mapbox Static API. To get a static image of the Empire State Building:
MapboxStaticImage staticImage = new MapboxStaticImage.Builder()
.setAccessToken("<your access token here>")
.setUsername("mapbox")
.setStyleId(Constants.MAPBOX_STYLE_STREETS)
.setLon(-73.98572) // Image center longitude
.setLat(40.74843) // Image center Latitude
.setZoom(16)
.setBearing(45)
.setPitch(60)
.setWidth(500) // Image width
.setHeight(500) // Image height
.setRetina(true) // Retina 2x image will be returned
.build();Once the staticImage object has been created, get the url:
staticImage.getUrl().toString()Request the image by doing the following:
Note: You could also use a third-party library such as Picasso or Volley to handle the image request.
new DownloadImageTask((ImageView) findViewById(R.id.imageView))
.execute(staticImage.getUrl().toString());
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView imageView;
public DownloadImageTask(ImageView imageView) {
this.imageView = imageView;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap bitmap = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
bitmap = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
}Need help?
Our Help page is filled with how-to references and guides so you can master our tools.