Michael Wolf Hoffman
Michael Wolf Hoffman

Reputation: 377

Add styling to KML Layer using Here Maps

I am loading several KML files from the array below using Here maps js. Below, the KmlObjs contain the path to the KML files, the color I would like the polylines to be, and their opacity.

Currently, each file renders blue polylines. This must be the default.

Is there a way for me dynamically style the polylines from the KML file?

   var dataSet = [
            new KmlObj('./kml/footway.kml', 'green', 100),
            new KmlObj('./kml/path.kml', 'red', 100),
            new KmlObj('./kml/track_central.kml', 'black', 50),
            new KmlObj('./kml/track_north_2.kml', 'black', 50),
            new KmlObj('./kml/track_northeast1.kml', 'black', 50),
            new KmlObj('./kml/track_northeast2.kml', 'black', 50),
            new KmlObj('./kml/track_south.kml', 'black', 50),
            new KmlObj('./kml/track_southeast.kml', 'black', 50),
        ]

        function loadKmlLayer() {
            dataSet.forEach(set => {
                var reader = new H.data.kml.Reader(set.path);
                reader.parse();
                layer = reader.getLayer();

              //  ADD STYLING TO THE LAYER BEFORE IT'S ADDED TO THE MAP ? 
                map.addLayer(layer);

        loadKmlLayer();

Upvotes: 0

Views: 498

Answers (1)

DevBab
DevBab

Reputation: 879

Try this:

// create a group to put all objects
kmlGroup = new H.map.Group();
map.addObject(kmlGroup);

then read kml file and when ready, do the processing:

let reader = new H.data.kml.Reader('file to read.kml');
reader.parse();

reader.addEventListener('statechange', async function () {

    // Wait till the KML document is fully loaded and parsed
    if (this.getState() === H.data.AbstractReader.State.READY) {

        // get all parsed objects
        var objects = reader.getParsedObjects();

        // if first object is a group
        if (objects[0] instanceof H.map.Group)
            objects = objects[0];

        // iterate through each object
        objects.forEach((obj, i, group) => {

            if (obj instanceof H.map.Marker) {
                // process points
            } else if (obj instanceof H.map.Polygon) {
                // light red filling with yellow border
                obj.setStyle({
                    strokeColor: 'rgba(255, 255, 0, 1)',
                    fillColor: 'rgba(255, 0, 0, 0.4)',
                    lineWidth: 2
                });
                kmlGroup.addObject(obj);

            } else if (obj instanceof H.map.Polyline) {
                obj.setStyle({
                    strokeColor: 'rgba(0, 185, 100, 1)'
                });

            } else console.log("obj type", obj.type);


        }, true, this);

    }
});

Upvotes: 2

Related Questions