Oussama GHOUAGH
Oussama GHOUAGH

Reputation: 17

How can I change the style of the icons in a map with openlayer and a geoJson file

I have an issue using react-openlayers. From a GeoJson file I'm trying to read the IconPath in features -> properties to be able to display every marker with its own icon in the map.

From Hiram Hackenbacker post, I understand that I can use a predefined function iconStyleFunc(). like this :

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

Do you know how I can use this function ?

Thank you

Upvotes: 0

Views: 1129

Answers (1)

Mike
Mike

Reputation: 17872

iconStyleFunc isn't predefined, style can set to any function which the developer defines, in that case it was called iconStyleFunc. Unless the function always returns the same result style is set to the function, not the result of the function, i.e.

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

In that question the feature had an IconPath property and the function created a style appropriate for that. Instead of creating a new style on every call it is more efficient to cache styles based on properties used to create them. See this example https://openlayers.org/en/v4.6.5/examples/igc.html

So an improved answer to the question on icon styles would be

var iconStyleCache = {};
function iconStyleFunc(feature) {

    var zIndex = 1;

    var iconName = feature.get("IconPath") || "pinother.png";
    var iconStyle = iconStyleCache[iconName];

    if (!iconStyle) {

      iconStyle = new ol.style.Style({
        image: new ol.style.Icon(({
            anchor: [0.5, 36], 
            anchorXUnits: "fraction",
            anchorYUnits: "pixels",
            opacity: 1,
            src: "images/" + iconName,  
            zIndex: zIndex
        })),
        zIndex: zIndex
      });
      iconStyleCache[iconName] = iconStyle;

    }

    return iconStyle;

}

Upvotes: 1

Related Questions