[英]can' t display a vector layer using openlayer 6
我正在處理一個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 文件沒有錯誤但沒有顯示任何內容。
我嘗試添加樣式,但結果保持不變。
我創建了一個簡單的例子,用parcel + openlayers 重現問題ici
我查看了 doc + openlayers 示例,但沒有看到是什么導致了我的代碼中的問題?
是的,我已經嘗試指定完整路徑。 我也在.json
重命名,但它不起作用。 該代碼似乎正確,因為我嘗試使用以下代碼並且它有效。 我不明白為什么它不適用於本地文件。 也許您需要在parcel甚至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 start
在localhost:1234
上為您的應用程序構建( dist
文件夾)提供服務。 問題是“localhost:1234 中是否有任何數據文件夾?” 或“我可以通過 localhost:1234/data 訪問我的數據嗎?”。
要解決上面提到的這個問題,您需要將整個data
文件夾復制到dist
文件夾中。
在 vue.js 中,我將data
文件夾移動到public
文件夾,正確的相對路徑是url: '../data/pays.geojson'
。我用 netlify 部署了應用程序,它可以工作。 感謝您的回答,這幫助我找到了解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.