Search code examples
openlayersopenlayers-5

Unable to Load Vanilla GeoJSON in Openlayers 5


I'm starting with some valid GeoJSON which I've built using https://geojson.io. My desire is to load it in an Openlayers 5 map.

I started with this tutorial, and attempted to use a remote source in place of a local one. The relevant block looks like the following:


var map = new Map({
  layers: [
    new TileLayer({
      source: new OSM()
    })
  ],
  target: "map",
  view: new View({
    center: [-13739617.939346, 6179221.917031],
    zoom: 11
  })
});

map.once("postrender", () => {
  axios.get(jsonUrl).then(({ data } = {}) => {
    const jsonSource = new VectorSource({
      features: new GeoJSON().readFeatures(data, {
        featureProjection: "EPSG:4326"
      })
    });

    const jsonLayer = new VectorLayer({
      source: jsonSource,
      style: jsonStyleFunction
    });

    map.addLayer(jsonLayer);
  });
});

When I fail to load, I was able to use console logs to determine that there the breaking point wasn't the get request. I was also able to see the there was the same number of featureChangeKeys_ in the jsonSource const as there were features in my JSON object:

featureChangeKeys_:
39: (2) [{…}, {…}]
41: (2) [{…}, {…}]
43: (2) [{…}, {…}]
45: (2) [{…}, {…}]
47: (2) [{…}, {…}]

Solution

  • The problem is that you are trying to load your data in a different coordinate reference system (CRS) than the map itself. By default, the map loads in the EPSG:3857 projection, while most GeoJSON is in EPSG:4326.

    You can test this out by "looking for Null Island". Pan your map to the latlong, (0, 0), and you might see a small point like the following:

    enter image description here

    If you see a small speck like above, then this is certainly the issue. To solve this, you can have Openlayers transform data on the fly by defining the featureProjection and dataProjection attribute as such:

    const jsonSource = new VectorSource({
          features: new GeoJSON().readFeatures(data, {
            dataProjection: "EPSG:4326",
            featureProjection: "EPSG:3857"
          })
        });