4.4 KiB
Annotation: Marker
This guide will show you how to add Markers in the map.
Annotation is an overlay on top of a Map. In package
org.maplibre.android.annotations, it has the following subclasses:
A Marker shows an icon image at a geographical location. By default, marker uses a provided image as its icon.
Or, the icon can be customized using IconFactory to generate an Icon using a provided image.
For more customization, please read the documentation about MarkerOptions.
In this showcase, we continue the code from the Quickstart,
rename Activity into JsonApiActivity,
and pull the GeoJSON data from a free and public API.
Then add markers to the map with GeoJSON:
- In your module Gradle file (usually
<project>/<app-module>/build.gradle), addokhttpto simplify code for making HTTP requests.
dependencies {
...
implementation 'com.squareup.okhttp3:okhttp:4.10.0'
...
}
-
Sync your Android project the with Gradle files.
-
In
JsonApiActivitywe add a new variable forMapLibreMap. It is used to add annotations to the map instance.
--8<-- "MapLibreAndroidTestApp/src/main/java/org/maplibre/android/testapp/activity/annotation/JsonApiActivity.kt:top"
- Call
mapview.getMapSync()in order to get aMapLibreMapobject. AftermaplibreMapis assigned, call thegetEarthQuakeDataFromUSGS()method to make a HTTP request and transform data into the map annotations.
--8<-- "MapLibreAndroidTestApp/src/main/java/org/maplibre/android/testapp/activity/annotation/JsonApiActivity.kt:mapAsync"
- Define a function
getEarthQuakeDataFromUSGS()to fetch GeoJSON data from a public API. If we successfully get the response, calladdMarkersToMap()on the UI thread.
--8<-- "MapLibreAndroidTestApp/src/main/java/org/maplibre/android/testapp/activity/annotation/JsonApiActivity.kt:getEarthquakes"
- Now it is time to add markers into the map.
- In the
addMarkersToMap()method, we define two types of bitmap for the marker icon. - For each feature in the GeoJSON, add a marker with a snippet about earthquake details.
- If the magnitude of an earthquake is bigger than 6.0, we use the red icon. Otherwise, we use the blue one.
- Finally, move the camera to the bounds of the newly added markers
- In the
--8<-- "MapLibreAndroidTestApp/src/main/java/org/maplibre/android/testapp/activity/annotation/JsonApiActivity.kt:addMarkers"
- Here is the final result. For the full contents of
JsonApiActivity, please visit source code of our Test App.