Sagar Sagar - 3 months ago 36
JSON Question

How to get image source from geojson openlayers3

Need to pass different different images for json point. How to give image src url from json

Vector layer and style

vector = new ol.layer.Vector({
source: new ol.source.Vector({
projection : 'EPSG:4326',
format: new ol.format.GeoJSON(),
url: 'resources/multipoint.geojson'
}),
style: styleFunction1
});

var styleFunction1 = function(feature) {
return styles[feature.getGeometry().getType()];
};

var styles = {
'Point': [
new ol.style.Style({
image: new ol.style.Icon({
src: 'resources/icon.png',
anchor: [0.5, 1]
})
})],
'LineString': [new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'gray',
width: 5
})
})]
};


Json

{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"name": "Missing Person",
"ref":" Ref 5684"
},
"geometry": {
"type": "Point",
"coordinates": [-0.12755, 51.507222]
}
},
{
"type": "Feature",
"properties": {
"name": "Wanted",
"category": "cat1",
"ref":" Ref 56124"
},
"geometry": {
"type": "Point",
"coordinates": [-0.12755, 52.507222]
}
},
{
"type": "Feature",
"properties": {
"name": "Missing 1",
"ref":" Ref 1684"
},
"geometry": {
"type": "Point",
"coordinates": [-1.12755, 52.507222]
}
}
]
}


How to pass
src: 'resources/Blue_pointer.png',
from json

Answer

Change your style function to:

var styleFunction1 = function(feature) {
  var styles = {
    'Point': [
      new ol.style.Style({
        image: new ol.style.Icon({
          src: feature.get('src'),
          anchor: [0.5, 1]
        })
      })],
    'LineString': [
      new ol.style.Style({
        stroke: new ol.style.Stroke({
          color: 'gray',
          width: 5
        })
    })]
  };

  return styles[feature.getGeometry().getType()];
};

And add an image source to your JSON:

{
  "type": "Feature",
  "properties": {
      "name": "Missing Person",
      "ref":" Ref 5684",
      "src": "resources/some-img.png"
  },
  "geometry": {
    "type": "Point",
    "coordinates": [-0.12755, 51.507222]
  }
},