无法使用Openlayer 6显示矢量层

问题描述 投票:0回答:2

我正在openlayers地图上添加矢量层,并在Vuejs项目中添加本地geojson和gpx文件的源,但是无法显示矢量层。我在Vue.js之外进行了测试,但我遇到了同样的问题。

语音代码:

// 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的简单示例,再现了问题ici

我查看了doc + 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()
  })
})
javascript vue.js openlayers-6
2个回答
0
投票

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

发生此问题是因为您的应用程序找不到data文件夹。 npm run start为您在dist上的应用程序构建(localhost:1234文件夹)提供服务。问题是“ localhost:1234中是否有任何数据文件夹?”或“我可以通过localhost:1234 / data访问我的数据吗?”。

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.