'PolylineOptions .color() not working
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
Solution 1:[1]
Your problem is caused by confusion between a color resource identifier and a color value, both of which are int
s.
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);
Solution 2:[2]
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>
Solution 3:[3]
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)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Community |
Solution 2 | Akshit Mehra |
Solution 3 | Safal Bhatia |