使用JSON设置标记的文本和颜色

时间:2017-11-13 13:41:52

标签: javascript json openlayers

当我将它们附加到地图时,我想用JSON数据为每个标记设置文本和颜色。这个示例代码很好。文本和颜色目前是静态的。我可以使用某些功能执行此操作,还是应该更改语法以使其正常工作?

const vectorSource = new ol.source.Vector();
const vectorLayer = new ol.layer.Vector({
  source: vectorSource,
  style: new ol.style.Style({
    image: new ol.style.Circle({
      radius: 18,
      fill: new ol.style.Fill({
        color: [0, 155, 0, 0.6]
      }),
      stroke: new ol.style.Stroke({
        color: [0, 200, 0, 0.9],
        width: 3
      })
    }),
    text: new ol.style.Text({
      text: "Test",
      scale: 1.2,
      fill: new ol.style.Fill({
        color: "#fff"
      }),
      stroke: new ol.style.Stroke({
        color: "0",
        width: 3
      })
    })
  })
})
vectorLayer.setZIndex(5);
const map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    ),
    vectorLayer
  ],
  target: "map",
  view: new ol.View({
    center: [0, 0],
     zoom: 5
  })
});
const addMarkers = (lat, long) => {
  if(lat && lat !== 0) {
    const point = new ol.geom.Point(ol.proj.transform([lat, long], "EPSG:4326", "EPSG:3857"));
    const iconFeature = new ol.Feature({
      geometry: point
    });
    vectorSource.addFeature(iconFeature);
  }
}
// Positions come from map.jade
positions.forEach(position => {
  let long = position.geolocation.longitude;
  let lat = position.geolocation.latitude;
  if (long !== 0 && long !== 999.9 && long !== "" &&  long !== undefined) {
    addMarkers(long, lat);  
  }
});

1 个答案:

答案 0 :(得分:0)

在ol.layer.Vector构造函数中,您可以传递函数,而不是传递ol.style.Style实例。

该函数将接收特征和分辨率,并返回ol.style.Style对象。

以下是一个示例:http://openlayersbook.github.io/ch06-styling-vector-layers/example-07.html

否则,您可以在addMarkers函数中使用ol.Feature.setStyle函数。