MarkerView
The MarkerView Plugin for Android provides a simplified way to add map markers that are Android views.
Install the MarkerView plugin
To start developing an application using the MarkerView Plugin, you'll need to add the appropriate dependencies inside your build.gradle
file. This dependency includes the Maps SDK for Android. You can find all dependencies given below on MavenCentral.
Add the dependency
- Start Android Studio.
- Open up your application's
build.gradle
. - Make sure that your project's
minSdkVersion
is API 14 or higher. - Under dependencies, add a new build rule for the latest
mapbox-android-plugin-markerview-v9
. - Click the Sync Project with Gradle Files near the toolbar in Studio.
repositories {
mavenCentral()
}
dependencies {
implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-markerview-v9:0.4.0'
}
Initialize the plugin
The plugin includes a manager class for adding and removing markers. The MarkerViewManager
class requires initialized MapboxMap
and MapView
objects to be created. You should create a MarkerViewManager
object within onMapReady()
to be sure that the markers can be added to a successfully built map.
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap mapboxMap) {
MarkerViewManager markerViewManager = new MarkerViewManager(mapView, mapboxMap);
}
});
mapView?.getMapAsync { mapboxMap ->
val markerViewManager = MarkerViewManager(mapView, mapboxMap)
}
Adding a marker
The plugin is all about Android views, so you'll need to first create whatever view that you want to use for the marker image. Once you've constructed the view, use it to create a MarkerView
class and then eventually pass the MarkerView
object to the MarkerViewManager
.
MarkerView markerView = new MarkerView(new LatLng(LAT,LONG), customView);
markerViewManager.addMarker(markerView);
val marker = MarkerView(LatLng(LAT.toDouble(),LONG.toDouble()), customView)
marker?.let {
markerViewManager?.addMarker(it)
}
Removing a marker
The MarkerViewManager
can also remove a specific MarkerView
.
markerViewManager.removeMarker(markerView);
marker?.let {
markerViewManager?.removeMarker(it)
}
Destroying the manager
Don't forget to destroy your MarkerViewManager
object. The destruction should happen in onDestroy()
if you're using an activity. It should happen in the onDestroyView()
method of a fragment.
Activity:
@Override
protected void onDestroy() {
super.onDestroy();
markerViewManager.onDestroy();
mapView.onDestroy();
}
override fun onDestroy() {
super.onDestroy()
markerViewManager?.onDestroy()
mapView.onDestroy()
}
Fragment:
@Override
public void onDestroyView() {
super.onDestroyView();
markerViewManager.onDestroy();
mapView.onDestroy();
}
override fun onDestroyView() {
super.onDestroyView()
markerViewManager?.onDestroy()
mapView.onDestroy()
}