Reading in local GeoJSON file for OpenLayers

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:

With one big exception: I need to load the GeoJSON file from the server instead of defining it in the top (so replace thevar 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?

var vectorLayer = new ol.layer.Vector({ source: new ol.source.Vector({ format: new ol.format.GeoJSON(), url: '' }), style: new{ image: new /** @type {} */ ({ radius: 20, fill: new{ color: '#ffff00' }) })) }) });

Just in case: an asynchronous method is one that returns immediately while the actual work continues in the background. This allows your program to continue to run while the request, which may take a long time, is blocking. In JavaScript, you usually pass in a function that will get called when the asynchronous task completes.

In your case,getDatais returning the return value ofgetJSONwhich appears to be nothing, and you're passing that value (nothing) intoreadFeatures.

Instead, you want to wait untilgetJSONsucceeds, then callreadFeatures:

var features; jQuery.getJSON("/json/studyCentroids.json", function(data) { features = new ol.format.GeoJSON().readFeatures( data ); alert(features); // success! }); alert(features); // undefined

I put the alerts in there to show when you can use the features variable and when you can't.

Note: I haven't used jQuery for this, nor tested the snippet.

Here's a quick way of loading the geoJSON directly when creating the ol.layer.Vector object:

function createLayerCountries() { return new ol.layer.Vector({ source: new ol.source.Vector({ //url: '', url: './countries.geojson', format: new ol.format.GeoJSON() }) }); }

url supports both remote and local files, the active line takes the geojson file from the same folder the page code is.

Watch the video: OpenLayers 5 for Windows 10 - Quick Start usando npm (October 2021).