Search code examples
openlayers-5

How to style a layer


I am trying to put image icons on my nodes in an openlayers 5 layer, but can't seem to get it right. I load an osm file and everything is ok, but i get a small circle instead of the icon.

I've searched online and all i can find is how to change a feature icon, not all features of a layer.

Part of my osm file

<?xml version='1.0' encoding='UTF-8'?>
<osm version='0.6' upload='false' generator='JOSM'>
  <node id='-102236' lat='37.1556611' lon='-8.5700716'>
    <tag k='vpa_cod' v='784' />
    <tag k='vpa_linha' v='11,38,' />
  </node>
</osm>

Declaration of layer

new VectorLayer({
          source: new VectorSource({
            url: './assets/layers/111_.osm',
            format: new OSMXML(),
            formatOptions: {
                extractStyles: true,
                extractAttributes: true,
                maxDepth: 2
                },

                style: new Style({
                  image: new Icon( ({
                    anchor: [0, 0],
                    anchorXUnits: 'fraction',
                    anchorYUnits: 'fraction',
                    src: 'assets/images/icons/11.svg',
                    scale : 0.35
                  }))
                })
          })
        })

I want to have an icon on my nodes, but only get small circles.


Solution

  • style should be a property of the layer, not the source

    new VectorLayer({
              source: new VectorSource({
                url: './assets/layers/111_.osm',
                format: new OSMXML(),
                formatOptions: {
                    extractStyles: true,
                    extractAttributes: true,
                    maxDepth: 2
                }
              }),
              style: new Style({
                image: new Icon({
                  anchor: [0, 0],
                  anchorXUnits: 'fraction',
                  anchorYUnits: 'fraction',
                  src: 'assets/images/icons/11.svg',
                  scale : 0.35
                })
              })
            })