从 OpenLayers 中的 GeoJSON 属性设置图标源

Set icons source from GeoJSON properties in OpenLayers

我正在尝试使用 OpenLayers 从 GeoJSON 文件构建地图,其中每个点都有一个 属性 iconUrl。我希望我的风格指的是属性,但我做不到。我用 Leaflet 做到了,你可以在这里看到目标:https://idrissad.github.io/lyon_map/

这是我的OL代码:

function styleFunction(feature) {
  if (feature.get('iconUrl')) {
    var iconUrl = feature.get('iconUrl');
    console.log(iconUrl);
  }
  var defaultStyle = new ol.style.Style({
   fill: new ol.style.Fill({
    color: "green"
  }),
  stroke: new ol.style.Stroke({
   color: "green",
   width: 1.2
  }),
  image: new ol.style.Icon({
   scale: 0.1,
   src: iconUrl
  })
 })return [defaultStyle]
}

并且:

const data = new ol.layer.Vector({
  source: new ol.source.Vector({
   url:'data.geojson',
   format: new ol.format.GeoJSON
  }),
  style: styleFunction,
  visible: true
})

我收到的错误是“断言 failed:6 => 必须提供已定义且非空的 src 或图像。” 我尝试了几种选择,但没有成功。 我的 console.log 告诉我 feature.get() 工作正常,我的 url 在 var iconUrl 中。 有什么线索吗?

因为你也有填充和描边,你的风格是否也用于多边形?如果其他功能没有 iconUrl 会导致错误。尝试修改样式函数,以便仅在存在 iconUrl

时设置图像部分
function styleFunction(feature) {
  var iconUrl = feature.get('iconUrl');
  var defaultStyle = new ol.style.Style({
    fill: new ol.style.Fill({
    color: "green"
  }),
  stroke: new ol.style.Stroke({
   color: "green",
   width: 1.2
  }),
  image: iconUrl ? new ol.style.Icon({
   scale: 0.1,
   src: iconUrl
  }) : undefined
 });
 return [defaultStyle];
}