使用openlayer 6无法显示矢量层

时间:2019-12-18 14:33:39

标签: javascript vue.js openlayers-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文件,没有错误,但未显示任何内容。

我尝试添加样式,但结果保持不变。

我创建了一个简单的示例,其中包含包裹+ 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()
  })
})

2 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

在vue.js中,我将:focus-within文件夹移到了data文件夹中,正确的相对路径是public。我使用netlify部署了该应用程序,它可以正常工作。 感谢您的回答,这有助于我找到解决方案。