class CustomMarker(
private val context: Context,
private val mapView: MapView?,
label: String?,
position: GeoPoint?
) : Marker(mapView) {
private var labelText: String = label ?: ""
private val paintText: Paint = Paint()
private var geopoint :GeoPoint? = position
private val paintBackground: Paint = Paint()
var labelVisible: Boolean = false
init {
title = labelText
setIcon(null) // You can set a custom icon if needed
position?.let { setPosition(it) }
paintText.color = android.graphics.Color.WHITE
paintText.textSize = 20f // Customize label text size
paintText.textAlign = Paint.Align.CENTER
paintBackground.color = Color.parseColor("#A6000000")
setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_TOP)
}
// Additional constructor to set the initial label visibility
constructor(
context: Context,
mapView: MapView?,
label: String?,
position: GeoPoint?,
initialLabelVisibility: Boolean
) : this(context, mapView, label, position) {
labelVisible = initialLabelVisibility
}
private val MIN_ZOOMLEVEL_TO_SHOW_LABEL = 20.0
// 23 ,24 more zoomin above 20 is zoomin
override fun draw(canvas: Canvas?, mapView: MapView?, shadow: Boolean) {
super.draw(canvas, mapView, shadow)
val currentZoomLevel = mapView?.zoomLevelDouble ?: 0.0
if(labelVisible){
//switchOn
if(currentZoomLevel >= MIN_ZOOMLEVEL_TO_SHOW_LABEL){
showLabel()
}else {
hideLabel()
}
}
if (!shadow && labelVisible && !labelText.isNullOrBlank()) {
if(labelVisible){
//switchOn
if(currentZoomLevel >= MIN_ZOOMLEVEL_TO_SHOW_LABEL){
showLabel()
}else {
hideLabel()
}
}
val positionPixels = mapView?.projection?.toPixels(this.position, null)
positionPixels?.let {
val customfont = ResourcesCompat.getFont(context,R.font.montserrat_semibold)
paintText.setTypeface(customfont)
val labelx = it.x.toFloat()
val labely = it.y.toFloat() - paintText.textSize - 15
val backgroundDrawable =
ContextCompat.getDrawable(context, R.drawable.rounded_background)
val left = (labelx - paintText.measureText(labelText) / 2).toInt() + -10
val top = (labely - paintText.textSize).toInt()
val right = (labelx + paintText.measureText(labelText) / 2).toInt() + 5
val bottom = labely.toInt() + 40
backgroundDrawable?.bounds = Rect(left, top, right, bottom)
if (canvas != null) {
backgroundDrawable?.draw(canvas)
}
canvas?.drawText(labelText, labelx, labely - paintText.ascent(), paintText)
}
}
else {
if(labelVisible){
//switchOn
if(currentZoomLevel >= MIN_ZOOMLEVEL_TO_SHOW_LABEL){
showLabel()
}else {
hideLabel()
}
}else{
if(currentZoomLevel >= MIN_ZOOMLEVEL_TO_SHOW_LABEL){
showLabel()
}else {
hideLabel()
}
}
// hideLabel()
}
}
fun showLabel() {
labelVisible = true
mapView?.invalidate()
}
fun hideLabel() {
labelVisible = false
mapView?.invalidate()
}
}