wfgeo
wfgeo

Reputation: 3098

Trying to display a GeoJSON on Openlayers 3

I am trying to display a geojson file on an openlayers map. The openlayers map is already working, however I cannot figure out how to display the features from the geojson file. The example on their website is unfortunately not very helpful, as it is simply the geojson object being written directly into the file and then accessed later. I wish to take the features from a separate geojson file and display them on the map.

This is what I have so far, copied directly from the example:

var vectorSource = new ol.source.Vector({
    features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
});

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

var map = new ol.Map({
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM()
        }),
        vectorLayer
    ],
    target: 'map',
    controls: ol.control.defaults({
        attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
            collapsible: false
        })
    }),
    view: new ol.View({
        center: [0, 0],
        zoom: 2
    })

});

What I need to know is how do I "open" the file and get the features from the geojson file (currently located at the url ..\public\geojson\federal_ridings.geojson) in place of the variable geojsonObject which is already there?

Upvotes: 1

Views: 508

Answers (1)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59328

To add GeoJSON layer from external file replace:

var vectorSource = new ol.source.Vector({
    features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
});

with

var vectorSource = new ol.source.Vector({
    url: '..\public\geojson\federal_ridings.geojson',
    format: new ol.format.GeoJSON()
});

ol.format.GeoJSON documentation

Make sure federal_ridings.geojson is a valid JSON file

Demo

Upvotes: 1

Related Questions