无法使用 OpenLayer 6 显示矢量图层



我正在制作一个开放层地图,以在 Vuejs 项目中添加一个包含本地 geojson 和 gpx 文件源的矢量层,但矢量层无法显示。 我在 Vue 之外进行了测试.js但我有同样的问题。

Voici le code :

// classes required to display the map
import Map from 'ol/Map'
import View from 'ol/View'
import TileLayer from 'ol/layer/Tile'
import OSM from 'ol/source/OSM'
// Feature format for reading and writing data in the GPX format.
import GPX from 'ol/format/GPX'
// Feature format for reading and writing data in the GeoJSON format.
import GeoJSON from 'ol/format/GeoJSON'
// Provides a source of features for vector layers.
import VectorSource from 'ol/source/Vector'
// Vector data that is rendered client-side.
import VectorLayer from 'ol/layer/Vector'
// Openstreet Map Standard
const openStreetMapLayer = new TileLayer({
source: new OSM(),
})
// Vector data source in GeoJSON format
const vectorGeoJSON = new VectorLayer({
source: new VectorSource({
url: 'data/pays.geojson',
format: new GeoJSON()
})
})
// Vector data source in GPX format
const vectorGPX = new VectorLayer({
source: new VectorSource({
url: 'data/capitales.gpx',
format: new GPX()
})
})
// declare the map 
new Map({
layers: [openStreetMapLayer, vectorGPX, vectorGeoJSON],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2
})
})

对于 geojson 文件,请收到此错误:

Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at getObject (JSONFeature.js:197)
at GeoJSON.JSONFeature.readFeatures (JSONFeature.js:53)
at VectorSource.<anonymous> (featureloader.js:94)

对于GPX文件,没有错误,但不会显示任何内容。

我试图添加一种样式,但结果保持不变。

我创建了一个简单的示例,其中包裹+开放层重现了问题

我查看了文档 + openlayers 示例,但我看不出是什么导致了我的代码中的问题?

是的,我已经尝试指定完整路径。 我也在.json中重命名,但它不起作用。 代码似乎是正确的,因为我尝试使用以下代码并且它可以工作。 我不明白为什么它不适用于本地文件。也许您需要在包裹甚至 webpack 或 vuejs 中添加配置?

这有效:

// Vector data source in GeoJSON format
const vectorGeoJSON = new VectorLayer({
source: new VectorSource({
url: 'https://raw.githubusercontent.com/sandix34/Openlayers-test-workshop/master/data/pays.geojson',
format: new GeoJSON()
})
})
// Vector data source in GPX format
const vectorGPX = new VectorLayer({
source: new VectorSource({
url: 'https://raw.githubusercontent.com/sandix34/Openlayers-test-workshop/master/data/capitales.gpx',
format: new GPX()
})
})

只需将data文件夹和内部文件复制到dist文件夹中即可。

出现此问题的原因是您的应用程序找不到data文件夹。npm run startlocalhost:1234上提供应用程序构建(dist文件夹(。问题是"localhost:1234 中是否有任何数据文件夹?"或"我可以通过 localhost:1234/data 访问我的数据吗?"。

如上所述,要解决此问题,您需要将整个data文件夹复制到dist文件夹中。

在 vue 中.js我将data文件夹移动到public文件夹,正确的相对路径是url: '../data/pays.geojson'.我用netlify部署了该应用程序,它可以工作。 感谢您的回答,帮助我找到了解决方案。

最新更新