3

I'm displaying various ships on a map and I have made real sized polygons to represent them. These are not visible at lower zooms, so I wanted to also add icons representing each ship. The icon is a small arrow that indicates each ship's heading.

var ships = {...};

var shipIcons = {
    "id": "shipIcons",
    "type": "symbol",
    "source": {
        "type": "geojson",
        "data": {
            "type": "FeatureCollection",
            "features": []
        }
    },
    "layout": {
        "icon-image": "arrow",
        "icon-rotate": 0,
        "icon-rotation-alignment": "map",
        "icon-allow-overlap": true
    }
};

for(var key in ships){
    shipIcons.source.data.features.push(
        {
            "type": "Point",
            "geometry": {
                "type": "Point",
                "coordinates": [ships[key].long, ships[key].lat]
            }
        }
    );
}

map.addLayer(shipIcons);

Is it possible for me to create a unique rotation for each icon? I'd rather not create a layer for each as there may be many ships.

1

It took awhile, but I finally figured it out.

You can set a "properties" object in each feature and call it from the layout. In this case, the JSON in the loop would be...

{
    "type": "Point",
    "properties": {
        "rotate": Number(ships[key].Heading)
    },
    "geometry": {
        "type": "Point",
        "coordinates": [ships[key].long, ships[key].lat]
    }
}

and the "icon-rotate" field would be...

"icon-rotate": ["get", "rotate"],

This could obviously have more use cases beyond just "icon-rotate".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.