javascriptopenlayers-5

Load external geojson file in OpenLayers 5.3.0


I have a problem loading external geojson file in OpenLayers 5.3.0 with the ol package. I installed it via npm. Here's the code:

import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import GeoJSON from 'ol/format/GeoJSON';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
import {OSM, Vector as VectorSource} from 'ol/source';

const map = new Map({
  layers: [
    new TileLayer({
      source: new OSM()
    }),
    new VectorLayer({
      source: new VectorSource({
        url: 'data/geojson/countries.geojson',
        format: new GeoJSON()
      })
    })
  ],
  target: 'map',
  view: new View({
    center: [0, 0],
    zoom: 2
  })
});

The file does not show up on map. In console I receive an error 404(Not found)


Solution

  • You need to import your GeoJsonLayer from local file. Here it is what I've done:

    import CountryLayer from "../assets/countries.geojson";
    

    Then you can use you CountryLayer in url directly without quotes:

    const map = new Map({
      layers: [
        new TileLayer({
          source: new OSM()
        }),
        new VectorLayer({
          source: new VectorSource({
            url: CountryLayer,
            format: new GeoJSON()
          })
        })
      ],
      target: 'map',
      view: new View({
        center: [0, 0],
        zoom: 2
      })
    });
    

    If you don't know where you can download countries.geojson let me explain it;

    In Openlayers Vector Layer example you can see that it is gave its url as

    url: 'data/geojson/countries.geojson'
    

    So this means that there is a data/geojson folder in their page folder structure. So you can check that url and get countries.geojson by going to this link below;

    https://openlayers.org/en/latest/examples/data/geojson/countries.geojson