简体   繁体   English

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

[英]Set icons source from GeoJSON properties in OpenLayers

I'm trying to build a map with OpenLayers, from a GeoJSON file where I have a property iconUrl for each point.我正在尝试从一个 GeoJSON 文件中构建一个带有 OpenLayers 的 map,其中每个点都有一个属性 iconUrl。 I want that my style refers to that property, and I can't manage to do it.我希望我的风格是指该属性,但我无法做到。 I did it with Leaflet, you can see the goal here: https://idrissad.github.io/lyon_map/我用 Leaflet 做到了,你可以在这里看到目标: https://idrissad.github.io/lyon_map/

Here is my OL code:这是我的 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]
}

And:和:

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

The error I get is "Assertion failed:6 => A defined and non-empty src or image must be provided."我得到的错误是“断言失败:6 => 必须提供已定义且非空的 src 或图像。” I tried several options, without success.我尝试了几个选项,但没有成功。 My console.log shows me that the feature.get() works fine, I have my urls in the var iconUrl.我的 console.log 显示 feature.get() 工作正常,我的 url 在 var iconUrl 中。 Any clue?有什么线索吗?

As you also have fill and stroke is your style is it also being used for polygons?因为你也有填充和描边是你的风格,它也被用于多边形吗? If other features don't have an iconUrl that will cause the error.如果其他功能没有会导致错误的iconUrl Try modifying the style function so the image part is only set if there is an iconUrl尝试修改样式 function 以便仅在有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];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM