在 OpenLayers 8.1 中,从 GeoJSON 手动将要素添加到 VectorSource 不会渲染要素

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

我创建了一个最小的示例来演示该问题。如果设置

const useGood = true
,GeoJSON 将按预期呈现,并以红色填充。如果您设置
const useGood = false
,代码会获取图层并将其设置在源上,但它们在地图上不可见。

我在这里缺少什么吗?我花了几个小时尝试调试这个;两种情况下的源和图层看起来都相同。

最小复制代码:

import './style.css';
import { Map, View } from 'ol';
import VectorLayer from 'ol/layer/Vector';
import TileLayer from 'ol/layer/Tile';
import VectorSource from 'ol/source/Vector';
import Style from 'ol/style/Style';
import Fill from 'ol/style/Fill';
import GeoJSON from 'ol/format/GeoJSON';
import OSM from 'ol/source/OSM';

const useGood = false

const URL = 'sample.json'

const style = new Style({
  fill: new Fill({
    color: [255, 0, 0]
  })
})

const source = new VectorSource({
  format: new GeoJSON({})
})

const badLayer = new VectorLayer({
  visible: true,
  source,
  style: function() {
    return style
  }
})

const goodLayer = new VectorLayer({
  visible: true,
  source,
  style: function() {
    return style
  }
})

const map = new Map({
  target: 'map',
  layers: [
    new TileLayer({
      source: new OSM()
    }),
  ],
  view: new View({
    center: [0, 0],
    zoom: 2
  })
});

if (useGood) {
  map.addLayer(goodLayer)
  source.setUrl(URL)
} else {
  map.addLayer(badLayer)
  const response = await fetch(URL)

  if (response.status !== 200) {
    throw new Error(`failed to fetch ${URL}, status ${response.status} ${response.statusText}`)
  }

  const json = await response.json()

  const format = new GeoJSON({})

  const features = format.readFeatures(json)

  source.addFeatures(features)
}
openlayers
1个回答
0
投票

@Mike 是对的。我需要手动设置投影信息,但是,我错误地将

featureProjection
设置为 GeoJSON 的值,而不是地图的值。

示例修复,使用我的默认地图投影:

const features = format.readFeatures(json, {
  featureProjection: 'EPSG:3857'
})
© www.soinside.com 2019 - 2024. All rights reserved.