Launch Google Maps from my app to show multiple markers based on longitude and latitude with different colored markers

45 Views Asked by At

I am trying to show multiple markers in the Google Maps application from my app with longitude and latitude, and I am also trying to change the color of the marker based on the type of marker I have to show.

private fun launchMaps(ticketLocationDetails:List<TicketLocationDetails>){
    try {
        val random = Random
        for (item in ticketLocationDetails) {
            val color = generateRandomColor(random)
            colorList[item.meter_serial_no] = color
        }
        val customMapUrl = constructCustomMapUrl(ticketLocationDetails)

        // Launch Google Maps app with the custom map URL
        val mapIntentUri = Uri.parse("geo:0,0?q=${customMapUrl}")
        val mapIntent = Intent(Intent.ACTION_VIEW, mapIntentUri)
        mapIntent.setPackage("com.google.android.apps.maps")
        mapIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(mapIntent)
    }catch (e:Exception){
        Toast.makeText(requireContext(),"unable to launch google maps application",Toast.LENGTH_SHORT).show()
        e.printStackTrace()
    }
}

private fun constructCustomMapUrl(ticketLocationDetails: List<TicketLocationDetails>): String {
    return if (ticketLocationDetails.isNotEmpty()) {
        val centerCoordinateItem = ticketLocationDetails[0]
        // Construct markers for each point
        val markers = ticketLocationDetails.mapIndexed { index, point ->
            "&markers=7Clabel:${index+1}%7C${point.latitude},${point.longitude}&label=${Uri.encode(point.meter_serial_no)}"
        }.joinToString("")

        // Construct the rest of the URL with parameters
        val center = "${centerCoordinateItem.latitude},${centerCoordinateItem.longitude}" // Example center coordinate
        val zoomLevel = 10
        "https://www.google.com/maps/@$center,$zoomLevel?${markers}"
    }else{
        ""
    }
}
1

There are 1 best solutions below

3
miguev On

If want to show a Google Maps with markers in different colors, generated dynamically from your code, you need to use the Google Maps Static API.

This will give you a static image (available in a few formats) and supports markers in any colors and 3 sizes:

Google Maps Static API image showing 3 markers of different colors and sizes.

Note URLs start with maps.googleapis.com/maps/api/staticmap

The URL format you have in your code, with URLs that start with www.google.com/maps/@ will take you to the Google Maps consumer application (maps.google.com) which is not an API and does not support any of the parameters the Maps Static API supports.

If you really want to send your users to Google Maps, using a supported API that won't break your applications (unpredictably and with no notice at all), use instead the Google Maps URLs (again, no support for markers).