Search code examples
servicecolorsopenlayers-3direction

How to draw different colors polylines using yours direction service in openalyers3


I am drawing the polylines on the using yours direction service as shown in the sample below

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
   <!-- <link rel="stylesheet" href="http://openlayers.org/en/v3.2.1/css/ol.css" type="text/css">-->
</head>
<body>
<div id="map" class="map"></div>
<link rel="stylesheet" href="http://openlayers.org/en/v3.12.1/css/ol.css" type="text/css">
<script src="http://openlayers.org/en/v3.12.1/build/ol.js"></script>


<script>
    var image = new ol.style.Circle({
        radius: 5,
        fill: null,
        stroke: new ol.style.Stroke({color: 'red', width: 1})
    });
    var styles = {
        'Point': new ol.style.Style({
            image: image
        }),
        'LineString': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'green',
                width: 3
            })
        }),
        'MultiLineString': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'rose',
                width: 1
            })
        }),
        'MultiPoint': new ol.style.Style({
            image: image
        }),
        'MultiPolygon': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'yellow',
                width: 1
            }),
            fill: new ol.style.Fill({
                color: 'rgba(255, 255, 0, 0.1)'
            })
        }),
        'Polygon': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'blue',
                lineDash: [4],
                width: 3
            }),
            fill: new ol.style.Fill({
                color: 'rgba(0, 0, 255, 0.1)'
            })
        }),
        'GeometryCollection': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'magenta',
                width: 2
            }),
            fill: new ol.style.Fill({
                color: 'magenta'
            }),
            image: new ol.style.Circle({
                radius: 10,
                fill: null,
                stroke: new ol.style.Stroke({
                    color: 'magenta'
                })
            })
        }),
        'Circle': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'red',
                width: 2
            }),
            fill: new ol.style.Fill({
                color: 'rgba(255,0,0,0.2)'
            })
        })
    };

    var styleFunction = function(feature, resolution) {
        return styles[feature.getGeometry().getType()];
    };

    var geojsonObject = {
        "type": "LineString",
        "crs": {
            "type": "name",
            "properties": {
                "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
            }
        },
        "coordinates":
                [

                    [103.984865, 1.350197]
                    ,[103.985188, 1.350903]
                    ,[103.985376, 1.351149]
                    ,[103.985477, 1.351341]
                    ,[103.986155, 1.352857]
                    ,[103.986195, 1.352982]
                    ,[103.986248, 1.353248]
                    ,[103.986393, 1.353593]
                    ,[103.986564, 1.353550]
                    ,[103.985175, 1.350160]
                    ,[103.985138, 1.350069]
                ],  "properties": {
            "distance": "21.452372",
            "description": "To enable simple instructions add: 'instructions=1' as parameter to the URL",
            "traveltime": "1228"
        }
    };
    //console.log(geojsonObject.coordinates);
    var routeGeom = new ol.geom.LineString(geojsonObject.coordinates).transform('EPSG:4326','EPSG:3857');
    var routeFeature = new ol.Feature({
        geometry:routeGeom
    })
    var extentToZoom = routeGeom.getExtent();
    console.log(extentToZoom);

    console.log(routeFeature);
    var vectorSource = new ol.source.Vector({
        features: [routeFeature]
    });

    //vectorSource.addFeature(new ol.Feature(new ol.geom.Circle([5e6, 7e6], 1e6)));

    var vectorLayer = new ol.layer.Vector({
        source: vectorSource,
        style: styleFunction
    });

    var map = new ol.Map({
        layers: [
            new ol.layer.Tile({
                source: new ol.source.XYZ({
                            urls : ["http://b.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png","http://b.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png","http://b.basemaps.cartocdn.com/light_all//{z}/{x}/{y}.png"]


                        })
            }),
            vectorLayer
        ],
        target: 'map',
        controls: ol.control.defaults({
            attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
                collapsible: false
            })
        }),
        view: new ol.View({
            center: ol.proj.fromLonLat([103.986908, 1.353199]),
            rotation: 68*Math.PI/180,
            zoom: 18
        })
    });
    map.getView().fit(extentToZoom,map.getSize())
</script>

</body>
</html>

But know i want to draw different color line ie,for example in the sample i want the first line in green and the next line in blue(know it is in green itself) likewise there are too many plots i want to plot it in different colors

Using multiString i am able to do it but for the sample above i dont know how to start with please point me to a sample or guide me how to do


Solution

  • Add an attribute to each LineString feature you are adding, and in your styles array, add a style with the color you want, and in style function, use the attribute to select the relevant style from that array. Here I edited your code,

     <!DOCTYPE html>
        <html>
        <head lang="en">
        <meta charset="UTF-8">
        <title></title>
       <!-- <link rel="stylesheet" href="http://openlayers.org/en/v3.2.1/css/ol.css"        type="text/css">-->
    </head>
    <body>
    <div id="map" class="map"></div>
    <link rel="stylesheet" href="http://openlayers.org/en/v3.12.1/css/ol.css" type="text/css">
    <script src="http://openlayers.org/en/v3.12.1/build/ol.js"></script>
    
    
    <script>
        var styles = {
            'greenRoute': new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: 'green',
                    width: 3
                })
            }),
            'redRoute': new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: 'red',
                    width: 3
                })
            })
        };
    
        var styleFunction = function(feature, resolution) {
            return styles[feature.get("fName")];
        };
    
        var geojsonObject = {
            "type": "LineString",
            "crs": {
                "type": "name",
                "properties": {
                    "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
                }
            },
            "coordinates":
                    [
    
                        [103.984865, 1.350197]
                        ,[103.985188, 1.350903]
                        ,[103.985376, 1.351149]
                        ,[103.985477, 1.351341]
                        ,[103.986155, 1.352857]
                        ,[103.986195, 1.352982]
                        ,[103.986248, 1.353248]
                        ,[103.986393, 1.353593]
                        ,[103.986564, 1.353550]
                        ,[103.985175, 1.350160]
                        ,[103.985138, 1.350069]
                    ],  "properties": {
                "distance": "21.452372",
                "description": "To enable simple instructions add: 'instructions=1' as parameter to the URL",
                "traveltime": "1228"
            }
        };
        //console.log(geojsonObject.coordinates);
        var routeGeom = new ol.geom.LineString(geojsonObject.coordinates).transform('EPSG:4326','EPSG:3857');
        var redRouteGeom = new ol.geom.LineString([
                        [103.984865, 1.350197]
                        ,[103.985188, 1.350903]
                        ,[103.985138, 1.350069]
                    ]).transform('EPSG:4326','EPSG:3857');
        var routeFeature = new ol.Feature({
            geometry:routeGeom,
            fName: "greenRoute"
        })
        var redRoute = new ol.Feature({
            geometry:redRouteGeom,
            fName: "redRoute"
        })
        var extentToZoom = routeGeom.getExtent();
        console.log(extentToZoom);
    
        console.log(routeFeature);
        var vectorSource = new ol.source.Vector({
            features: [routeFeature,redRoute]
        });
    
        //vectorSource.addFeature(new ol.Feature(new ol.geom.Circle([5e6, 7e6], 1e6)));
    
        var vectorLayer = new ol.layer.Vector({
            source: vectorSource,
            style : styleFunction
        });
    
        var map = new ol.Map({
            layers: [
                new ol.layer.Tile({
                    source: new ol.source.XYZ({
                                urls : ["http://b.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png","http://b.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png","http://b.basemaps.cartocdn.com/light_all//{z}/{x}/{y}.png"]
    
    
                            })
                }),
                vectorLayer
            ],
            target: 'map',
            controls: ol.control.defaults({
                attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
                    collapsible: false
                })
            }),
            view: new ol.View({
                center: ol.proj.fromLonLat([103.986908, 1.353199]),
                rotation: 68*Math.PI/180,
                zoom: 18
            })
        });
        map.getView().fit(extentToZoom,map.getSize());
        var select_interaction = new ol.interaction.Select();
    
    
        select_interaction.on("select", function (e) { 
        // do something. e.element is the feature which was added
        var evt= e.selected;
        });
        map.addInteraction(select_interaction);
    </script>
    
    </body>
    </html>