[GIS] Problems with calling GeoJson properties in OpenLayers3 (v3.1.1.)

geojsonopenlayers

I have a problem, property from GeoJson is not recognizable by OpenLayers3.
Debbuger says: Uncaught ReferenceError: feature is not defined on line futher below in OpenLayers3 code:

var icon = feature.get("icon");

GeoJson

{
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    12.231,
                    30.342
                ]
            },
            "properties": {
                "temperature": "21.1",
                "icon": "4"
            }
        },...

OpenLayers3 v.3.1.1.

var icon = feature.get("icon");
var styleTemperature = new ol.style.Style({
        image: new ol.style.Icon({
        src: 'http://prognoza.hr/metsimboli/' + icon + '.gif'
})
      });

var weatherLayer=new ol.layer.Vector({
        layer:'weather',
        visible: false,
        source: new ol.source.GeoJSON ({
                   projection: 'EPSG:4326',
                   url: 'path/to/geojson.geojson'
        }),
        style: styleTemperature
});

Can somebody suggest me something?

EDIT:

This part of the code works, but there is no added style to it, or should I say style is default:

var weatherLayer = new ol.layer.Vector({
        layer:'weather',
        source: new ol.source.GeoJSON ({
                projection: 'EPSG:3765',
                url: 'path/to/file.geojson'
        })
});

Best Answer

You should load your style using a style function (API reference) similar to this:

var vectorLayer = new ol.layer.Vector({
  source: new ol.source.Vector({
    url: 'path/to/file.geojson',
    format: new ol.format.GeoJSON()
  }),
  style: function(feature, resolution) {
    return new ol.style.Style({
        image: new ol.style.Icon({
            src: 'http://prognoza.hr/metsimboli/' + feature.get("icon") + '.gif'
        })
    });
  }
});

EDIT: JSFiddle Demo

Related Question