简体   繁体   中英

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

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, ie

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM