Add Custom Marker to Google Maps in Android using Jetpack Compose
In this article, we will take a look at How to use a custom icon as a marker on google maps in our android application.
Many android applications use maps to display the location. We can get to see they use custom marker icons like a delivery boy image or an icon to display a marker on the map.
fun ComposeMapMapMarker() {
val singapore = LatLng(1.35, 103.87)
val singapore2 = LatLng(2.50, 103.87)
val cameraPositionState: CameraPositionState = rememberCameraPositionState {
position = CameraPosition.fromLatLngZoom(singapore, 11f)
}
Box(Modifier.fillMaxSize()) {
GoogleMap(cameraPositionState = cameraPositionState){
MapMarker(
position = singapore,
title = "Your Title 1",
context = LocalContext.current,
iconResourceId = R.drawable.pin
)
MapMarker(
position = singapore2,
title = "Your Title 2",
context = LocalContext.current,
iconResourceId = R.drawable.pin
)
}
}
}
We need to add our custom marker inside our drawable folder like below:
Now we are creating a Composable function for showing markers on a map, which we call as MapMarker
@Composable
fun MapMarker(
context: Context,
position: LatLng,
title: String,
@DrawableRes iconResourceId: Int
) {
val icon = bitmapDescriptorFromVector(
context, iconResourceId
)
Marker(
state = MarkerState(position = position),
title = title,
icon = icon,
)
}
MapMarker takes four parameters:
- Context
- Marker Position
- Marker Title
- Custom Icon for Marker
The Jetpack Compose Marker()function takes icon as BitmapDescriptor object. So we need to convert our drawable icon into a BitmapDescriptor object. We have created a function for this, which we call as bitmapDescriptorFromVector().
fun bitmapDescriptorFromVector(
context: Context,
vectorResId: Int
): BitmapDescriptor? {
// retrieve the actual drawable
val drawable = ContextCompat.getDrawable(context, vectorResId) ?: return null
drawable.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
val bm = Bitmap.createBitmap(
drawable.intrinsicWidth,
drawable.intrinsicHeight,
Bitmap.Config.ARGB_8888
)
// draw it onto the bitmap
val canvas = android.graphics.Canvas(bm)
drawable.draw(canvas)
return BitmapDescriptorFactory.fromBitmap(bm)
}
..
Now just replace the Marker function with MapMarker function:
ComposeMapMapMarker()
..
After all the above changes, run the app, it should look this:
GET source code on Github:
..
..
Comments
Post a Comment