Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.7 kB
2
Indexable
Never
class CustomMarker(

    private val context: Context,
    private val mapView: MapView?,
    label: String?,
    position: GeoPoint?
) : Marker(mapView) {
    private val labelText: String = label ?: ""
    private val paintText: Paint = Paint()
    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

    }
    override fun draw(canvas: Canvas?, mapView: MapView?, shadow: Boolean) {
        super.draw(canvas, mapView, shadow)

        if (!shadow && labelVisible && !labelText.isNullOrBlank()) {
            val positionPixels = mapView?.projection?.toPixels(this.position, null)
            positionPixels?.let {
                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() + 35
                backgroundDrawable?.bounds = Rect(left, top, right, bottom)
                if (canvas != null) {
                    backgroundDrawable?.draw(canvas)
                }
                canvas?.drawText(labelText, labelx, labely - paintText.ascent(), paintText)

            }
        }else{
            labelVisible = false
//            Log.d("", "hideLabel:caled00000 ")
        }
    }
    // Method to show the label

    fun showLabel() {
        labelVisible = true
        mapView?.invalidate()
    }
    // Method to hide the label
    fun hideLabel() {
//        Log.d("", "hideLabel:caled ")
        labelVisible = false
        mapView?.invalidate()
    }

}