2

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'
            }),
            }),
        })
0

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>
0

For me, your code works if I change the .geojson to .json (you can simply change this in your explorer) I also worked with local directory, using e.g. './world_countries.json'

Also be careful about using a style in the vectorlayer - if you specify one which has no entry for the type in your geojson, it will be invisible and there will be no error message...so for testing, simply use the vectorlayer without any style.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.