Read Local GeoJSON File in OpenLayers – Detailed Guide

geojsonopenlayers

I am kinda new to OpenLayers and not (yet) very experienced in JavaScript.

I have a WordPress blog and I want to replicate and adjust the following script to my needs: http://jsfiddle.net/eqsrnjos/1/

With one big exception: I need to load the GeoJSON file from the server instead of defining it in the top (so replace the var geoJson).

However the most straight forward way does not seem to work for me:

function getData() {
return jQuery.getJSON("/json/studyCentroids.json");
}

var features = new ol.format.GeoJSON().readFeatures( getData() );

In Firebug I can see that the GeoJSON file is properly loaded, but it does not seem to appear for some reason?

Best Answer

var vectorLayer = new ol.layer.Vector({
    source: new ol.source.Vector({
        format: new ol.format.GeoJSON(),
        url: 'http://yourserver.com/yourgeojsonfile.js'
    }),
    style: new ol.style.Style({
        image: new ol.style.Circle( /** @type {olx.style.IconOptions} */ ({
            radius: 20,
            fill: new ol.style.Fill({
                color: '#ffff00'
            })
        }))
    })
});

http://jsfiddle.net/expedio/9hnjok8n/