[GIS] Add a vector GeoJSON layer in OpenLayers 5.1.3

geojsonopenlayersvector-layer

I am trying to add a simple capitals GeoJSON vector layer to my map for basics learning, without managing to get it to work. I spent hours of roaming the documentation API. As follow is my script:

new ol.layer.Vector({
        source: new ol.source.Vector({
            url:'res/world_countries.geojson',
            format: new ol.format.GeoJSON({
                featureProjection: 'EPSG:3857'
            }),
            }),
        })

Best Answer

Normally, you don't need to set an option like featureProjection: 'EPSG:3857' in new ol.format.GeoJSON call. Why? Because by default, any GeoJSON should be using coordinates with EPSG:4326 (lon/lat for non specialists). If it's the case, it works "out of the box"

You may also have issues because you sample is using local url like file:// instead of http://. Look at this excellent tutorial to understand why and how to fix the issue https://developer.mozilla.org/en-US/docs/Learn/Common_questions/set_up_a_local_testing_server (PS: to display GeoJSON required "asynchronous requests" also know as Ajax, hence the link)

The following code pasted in an html file displays the countries in the browser (tested).

<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <link rel="stylesheet" href="https://openlayers.org/en/v5.1.3/css/ol.css" type="text/css">
    <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
    <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
    <script src="https://openlayers.org/en/v5.1.3/build/ol.js"></script>
  </head>
  <body>
    <div id="map" class="map"></div>
    <script>
      var map = new ol.Map({
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
        target: 'map',
        view: new ol.View({
          center: [0, 0],
          zoom: 2
        })
      });
      var vector = new ol.layer.Vector({
        source: new ol.source.Vector({
          url: 'https://openlayers.org/en/v5.1.3/examples/data/geojson/countries.geojson',
          format: new ol.format.GeoJSON()
        })
      });
      map.addLayer(vector);
    </script>
  </body>
</html>
Related Question