Google Maps v2 - draw route with different colors - Android

巧了我就是萌 提交于 2019-11-29 18:08:36

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!