I am building a location based android app and I want to draw a route user takes based on his speed. For example: 0-10kmh - Yellow polyline 10-20kmh - Red polyline
To draw polyline with colored segments you can use method like that:
private void showPolyline(List<ColoredPoint> points) {
if (points.size() < 2)
return;
int ix = 0;
ColoredPoint currentPoint = points.get(ix);
int currentColor = currentPoint.color;
List<LatLng> currentSegment = new ArrayList<>();
currentSegment.add(currentPoint.coords);
ix++;
while (ix < points.size()) {
currentPoint = points.get(ix);
if (currentPoint.color == currentColor) {
currentSegment.add(currentPoint.coords);
} else {
currentSegment.add(currentPoint.coords);
mGoogleMap.addPolyline(new PolylineOptions()
.addAll(currentSegment)
.color(currentColor)
.width(20));
currentColor = currentPoint.color;
currentSegment.clear();
currentSegment.add(currentPoint.coords);
}
ix++;
}
mGoogleMap.addPolyline(new PolylineOptions()
.addAll(currentSegment)
.color(currentColor)
.width(20));
}
where ColoredPoint
is:
class ColoredPoint {
public LatLng coords;
public int color;
public ColoredPoint(LatLng coords, int color) {
this.coords = coords;
this.color = color;
}
}
and mGoogleMap
is GoogleMap
object. For
List<ColoredPoint> sourcePoints = new ArrayList<>();
sourcePoints.add(new ColoredPoint(new LatLng(-35.27801,149.12958), Color.GREEN));
sourcePoints.add(new ColoredPoint(new LatLng(-35.28032,149.12907), Color.GREEN));
sourcePoints.add(new ColoredPoint(new LatLng(-35.28099,149.12929), Color.YELLOW));
sourcePoints.add(new ColoredPoint(new LatLng(-35.28144,149.12984), Color.YELLOW));
sourcePoints.add(new ColoredPoint(new LatLng(-35.28194,149.13003), Color.RED));
sourcePoints.add(new ColoredPoint(new LatLng(-35.28282,149.12956), Color.RED));
sourcePoints.add(new ColoredPoint(new LatLng(-35.28302,149.12881), Color.BLUE));
sourcePoints.add(new ColoredPoint(new LatLng(-35.28473,149.12836), Color.BLUE));
showPolyline(sourcePoints);
you got something like:
Also, for convert speed to color, you can use method like that:
public int speedToColor(float speed) {
int color = Color.TRANSPARENT;
if (speed < 5) {
color = Color.BLUE;
} else if (speed < 25) {
color = Color.GREEN;
} else if (speed < 50) {
color = Color.YELLOW;
} else {
color = Color.RED;
}
return color;
}