3

I'm trying to set red color on my polylines of my map with this code:

PolylineOptions rectOptions = new PolylineOptions();
rectOptions.color(R.color.colorPrimary);
String[][] lineInformation = ((MyApplication)getApplication()).getLineInformation(line);
for (int i=0; i<lineInformation.length; i++){
    rectOptions.add(new LatLng(Double.parseDouble(lineInformation[i][0]),Double.parseDouble(lineInformation[i][1])));
}

But it's not working, instead of showing the primaryColour of my app which is red, it's showing a dark color with some alpha.

I followed the official guide: https://developers.google.com/maps/documentation/android-api/shapes

NullPointerException
  • 36,107
  • 79
  • 222
  • 382

3 Answers3

6

Your problem is caused by confusion between a color resource identifier and a color value, both of which are ints.

Let's take a look at the documentation for PolylineOptions.color():

public PolylineOptions color (int color)

Sets the color of the polyline as a 32-bit ARGB color. The default color is black (0xff000000).

Since the documentation states that the input should be a "32-bit ARGB color", you can't just pass a color resource id; you have to manually resolve that to a color value first.

R.color.colorPrimary is an int with some auto-generated value, maybe something like 0x7f050042. Unfortunately, this can be interpreted as an ARGB color, and would be a partially-transparent, extremely dark blue. So the app doesn't crash, you just get an unexpected color on your polyline.

To get the correct color, use ContextCompat.getColor() to resolve your color resource id to a color value, and then pass the color value to the color() method:

Context c = /* some context here */
int colorPrimary = ContextCompat.getColor(c, R.color.colorPrimary);
rectOptions.color(colorPrimary);
Community
  • 1
  • 1
Ben P.
  • 52,661
  • 6
  • 95
  • 123
0

You can also use the predefined Java "Color" class, to get some standard colors and use it to pass to maps.

For example

PolylineOptions rectOptions = new PolylineOptions();
<p>rectOptions.color(Color.BLUE);</p>
Akshit Mehra
  • 747
  • 5
  • 17
0

Call this method for Draw Polyline and You can add any color for polyline

fun drawPolyline(color: Int, list: ArrayList<LatLng>, googleMap: GoogleMap,width:Float): Polyline {
        val options = PolylineOptions().width(width)
            .color(color)
            .geodesic(true)
        for (z in list.indices) {
            val point = list[z]
            options.add(point)
        }
        return googleMap.addPolyline(options)
    }
Safal Bhatia
  • 245
  • 2
  • 6