Drawing a Polygon on the Map in Android

Rıdvan Özcan
6 min readApr 10, 2023

--

Polygon on the Mapbox Map

Android app development has become increasingly popular in recent times. Integration of maps is a fundamental feature for many applications to enable users to perform various functions on the maps. This article will discuss how to draw a polygon on the map using Mapbox SDK in Android applications. Mapbox SDK allows developers to create customizable maps in their Android applications, providing users with a better experience. A brief overview of Mapbox SDK will be provided, and the step-by-step process of drawing a polygon on the map will be explained in this article.

How to install Android Studio:

  1. First, go to the Android Studio website: https://developer.android.com/studio
  2. Click the “Download Android Studio” button and choose the correct version for your operating system.
  3. Once the download is complete, open the installation file and click “Next”.
  4. Wait for all the required components to be installed.
  5. On the “Android Studio Setup Wizard” screen, click “Next” and then accept the license agreement.
  6. The installation process may take a few minutes as it installs all the required components.
  7. Once the installation is complete, click “Finish”.
  8. When you first open Android Studio, you will see the “Welcome to Android Studio” screen. Here, you can create a new project or open an existing one.
  9. Before you can start using Android Studio, remember that you need to be connected to an Android emulator or a physical Android device.

By following these steps, you can successfully install Android Studio.

Mapbox Android SDK Installation

Before installing the SDK, you need to gather the appropriate credentials. The SDK requires two pieces of sensitive information from your Mapbox account. If you don’t have a Mapbox account: sign up and navigate to your Account page. You need:

  • A public access token: From your account’s tokens page, you can either copy your default public token or click the Create a token button to create a new public token.
  • A secret access token with the Downloads: Read scope.
  1. From your account’s tokens page, click the Create a Token button.
  2. From the token creation page, give your token a name and make sure the box next to the Downloads: Read scope is checked.
  3. Click the Create Token button at the bottom of the page to create your token.
  4. The token you’ve created is a secret token, which means you will only have one opportunity to copy it somewhere secure.

You should not expose these access tokens in publicly-accessible source code where unauthorized users might find them. Instead, you should store them somewhere safe on your computer and take advantage of Gradle properties to make sure they’re only added when your app is compiled. Once this configuration step has been completed, you will be able to reference your credentials in other parts of your app.

To avoid exposing your secret token, add it as an environment variable:

  1. Find or create a gradle.properties file in your Gradle user home folder. The folder can be found at «USER_HOME»/.gradle. Once you have found or created the file, its path should be «USER_HOME»/.gradle/gradle.properties. You can read more about Gradle properties in the official Gradle documentation.
  2. Add your secret token to your gradle.properties file:
MAPBOX_DOWNLOADS_TOKEN=YOUR_SECRET_MAPBOX_ACCESS_TOKEN

There are many ways to configure your public access token. Many of the examples and code snippets on this site assume your token is stored in a file in your project with other string values. If you would like to manage your public access token this way, open your project’s R.strings.xml file and add the following string resource, replacing YOUR_MAPBOX_ACCESS_TOKEN with your public Mapbox API token:

<string name="mapbox_access_token">YOUR_MAPBOX_ACCESS_TOKEN</string>

If you plan to display the user’s location on the map or get the user’s location information you will need to add the ACCESS_COARSE_LOCATION permission in your application's AndroidManifest.xml. You also need to add ACCESS_FINE_LOCATION permissions if you need access to a precise location. You can check whether the user has granted location permission and request permissions if the user hasn't granted them yet using the PermissionsManager.

<manifest ... >
<!-- Always include this permission -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

<!-- Include only if your app benefits from precise location access. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</manifest>

Open up your project-level build.gradle file, and add the code below to declare the endpoint in the repositories block:

allprojects {
repositories {
maven {
url 'https://api.mapbox.com/downloads/v2/releases/maven'
authentication {
basic(BasicAuthentication)
}
credentials {
// Do not change the username below.
// This should always be `Mapbox` (not your username).
username = "mapbox"
// Use the secret token you stored in gradle.properties as the password
password = project.properties['MAPBOX_DOWNLOADS_TOKEN'] ?: ""
}
}
}
}

Open up your module-level build.gradle file. Make sure that your project’s minSdkVersion is at API 21 or higher.

android {
...
defaultConfig {
minSdkVersion 21
}
}

Under dependencies, add a new build rule for the latest Mapbox Maps SDK for Android.

dependencies {
implementation 'com.mapbox.maps:android:10.12.1'
implementation 'com.mapbox.mapboxsdk:mapbox-sdk-turf:5.7.0'
}

You can sync the project now.

Add a Mapbox Android Map

Open the activity you’d like to add a map to and use the code below.

mapView?.getMapboxMap()?.loadStyleUri(Style.MAPBOX_STREETS)  
mapView?.location?.updateSettings {
enabled = true
pulsingEnabled = true
}

Open the activity’s XML layout file and add the following:

<com.mapbox.maps.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
mapbox:mapbox_cameraTargetLat="40.7128"
mapbox:mapbox_cameraTargetLng="-74.0060"
mapbox:mapbox_cameraZoom="9.0" />

The MapView contains its lifecycle methods for managing Android's OpenGL lifecycle, which must be called directly from the containing Activity. 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 and call the respective MapView method. The following lifecycle methods must be overridden and include the matching MapView method. If you're using a fragment, call mapview.onDestroy() inside the fragment's onDestroyView() method rather than inside onDestroy().

override fun onStart() {
super.onStart()
mapView?.onStart()
}

override fun onStop() {
super.onStop()
mapView?.onStop()
}

override fun onLowMemory() {
super.onLowMemory()
mapView?.onLowMemory()
}

override fun onDestroy() {
super.onDestroy()
mapView?.onDestroy()
}

Add map successfully… :)

Add a Polygon to the Map

Create an instance of the Annotation API and get the polygon manager.

 private var mAnnotationApi: AnnotationPlugin? = null
private var mPolygonAnnotationManager: PolygonAnnotationManager? = null

mAnnotationApi = mMapView?.annotations
mPolygonAnnotationManager = mAnnotationApi?.createPolygonAnnotationManager(mMapView!!)

Create an instance of the location list of polygon corners.

private var mPointsList = ArrayList<ArrayList<Point>>()

mPointsList.add(ArrayList())

We create a button to define the vertices of the polygon. When we press this button, it will add a corner to the location of the center of the screen. If we drag the screen and press the button repeatedly so that there are 4 corners, we will draw the polygon. Each time we click the button, we will save the location to the mPointsList list we defined earlier.

We use drawPolygon() function to draw the polygon on the screen. We’ll call it every time we add a vertex.

binding.btnAddPoint.setOnClickListener {
mMapView?.getMapboxMap()?.cameraState?.center?.let {
mPointsList.first().add(it)

drawPolygon(mPointsList)
}
}
private fun drawPolygon(points: List<List<Point>>) {

mPolygonAnnotationManager?.deleteAll()

// Set options for the resulting fill layer.
val polygonAnnotationOptions: PolygonAnnotationOptions = PolygonAnnotationOptions()
.withPoints(points)
.withFillColor("#4eeeb1")
.withFillOpacity(0.4)

mPolygonAnnotationManager?.create(polygonAnnotationOptions)
}

We have completed our application :)

I would like to express my gratitude to all of you who have taken the time to read this article on how to draw a polygon on the map using Mapbox SDK in Android. I hope that you have found this article informative and helpful in your Android app development journey.

I would also like to encourage you to continue exploring the vast possibilities that Android Studio and Mapbox SDK offer, as they are powerful tools that can help you to create exciting and engaging apps.

Thank you once again for your time and attention. If you have any questions or feedback, please feel free to contact with me.

Best regards, Rıdvan Özcan

https://www.linkedin.com/in/ridvanozcan/

https://www.instagram.com/mr.softwareengineer/

--

--