Search code examples
openlayers-3geojson

Openlayers 3 : How to change Geojson Icon src so it won't override other geojson types?


I'm able to change src of an icon when loading Point/MultiPoint Geojson, in this way:

 that.geojsonLayers[index]  = new that.openlayers.ol.layer.Vector({
      source: new that.openlayers.ol.source.Vector({
        format: new that.openlayers.ol.format.GeoJSON(),
        url: url         
      }),
      style: new that.openlayers.ol.style.Style({
        image: new that.openlayers.ol.style.Icon({
          src: 'http://mapmip.webiks.com/assets/Markers/marker-icon-blue.png'
        })
      })

but then I can't load other types of Geojson - Polygons are not being loaded at all, and Geometry Collection (which composed from icon and lines) is load only the icon.

What is the way to change the icon src so it won't override the other geojson type ?


Solution

  • You may use a style function to verify the geometry type you need to style. Setting an icon for styling a polygon is not correct. Check this

    1.Declare your style

    var myMultiStyle = {
    //here replace with your icon style
            'Point': new ol.style.Style({
              image: new ol.style.Circle({
                fill: new ol.style.Fill({
                  color: 'rgba(255,255,0,0.4)'
                }),
                radius: 5,
                stroke: new ol.style.Stroke({
                  color: '#ff0',
                  width: 1
                })
              })
            }),
            'LineString': new ol.style.Style({
              stroke: new ol.style.Stroke({
                color: '#f00',
                width: 3
              })
            }),
            'Polygon': new ol.style.Style({
             fill: new ol.style.Fill({
             color: 'rgba(0,255,255,0.5)'
             }),
             stroke: new ol.style.Stroke({
             color: '#0ff',
             width: 1
          })
        })
          };
    
    1. Create a style function

    function myStyleFunction(feature,resolution){ return myMultiStyle[feature.getGeometry().getType()]; }

    1. Asign the style function to your vector source

    that.geojsonLayers[index] = new that.openlayers.ol.layer.Vector({ source: new that.openlayers.ol.source.Vector({ format: new that.openlayers.ol.format.GeoJSON(), url: url
    }), style: myStyleFunction })

    Check this official example to see the result.