简体   繁体   English

在 OpenLayers 5.3.0 中加载外部 geojson 文件

[英]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.我在使用 ol 包在 OpenLayers 5.3.0 中加载外部 geojson 文件时遇到问题。 I installed it via npm.我是通过 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)在控制台中,我收到错误 404(未找到)

You need to import your GeoJsonLayer from local file.您需要从本地文件导入 GeoJsonLayer。 Here it is what I've done:这是我所做的:

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

Then you can use you CountryLayer in url directly without quotes:然后你可以直接在 url 中使用你的 CountryLayer 而无需引号:

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;如果你不知道在哪里可以下载 countries.geojson 让我解释一下;

In Openlayers Vector Layer example you can see that it is gave its url as在 Openlayers Vector Layer示例中,您可以看到它的 url 为

url: 'data/geojson/countries.geojson'

So this means that there is a data/geojson folder in their page folder structure.所以这意味着在他们的页面文件夹结构中有一个 data/geojson 文件夹。 So you can check that url and get countries.geojson by going to this link below;因此,您可以通过转到下面的此链接来检查该 url 并获取 countries.geojson;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM