1

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)

dusanz
  • 13
  • 1
  • 4
  • 2
    If you are copying OpenLayers examples you either need to copy the data to your own server or use the full OpenLayers path `url: 'https://openlayers.org/en/latest/examples/data/geojson/countries.geojson',` – Mike Dec 22 '18 at 11:35
  • Using a local copy of the geojson file: http://www.geocodezip.com/OL_5.3.0_countriesGeoJson.html – geocodezip Dec 22 '18 at 19:40
  • Using full OpenLayers path url works. Thanks. I have data copied on my drive, will stick around bit more to get them work – dusanz Dec 23 '18 at 09:24
  • I gave a plus on the question because it showed me how to put a geojson on the map. I'm just trying to port over something from Leaflet which is also on rails and the geojson is generated from data in the app. Now I just need to get to finding how to put a selector since the data has years associated with it. – Greg Dec 13 '19 at 05:15

1 Answers1

0

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
Ardahan Kisbet
  • 641
  • 1
  • 13
  • 33