基于openlayers6的基本地图操作--3. 添加marker

  • marker的实质是点PointFeature,通过设置样式setStyle为自定义的图标。
  • 添加marker,同时添加label

引入需要的组件

import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import {Icon, Style} from 'ol/style';
import VectorSource from 'ol/source/Vector';
import {Vector as VectorLayer} from 'ol/layer';

创建marker

var iconFeature = new Feature({
  geometry: new Point([0, 0]),
  name: 'Null Island',
  population: 4000,
  rainfall: 500
});

设置style

var iconStyle = new Style({
  image: new Icon({
    anchor: [0.5, 0.5],
    anchorXUnits: 'fraction',
    anchorYUnits: 'pixels',
    crossOrigin: 'anonymous',
    src: url
  }),
  // 设置marker的label
  text: new Text({
     textAlign: 'center',
     textBaseline: 'top',
     // font: font,
     offsetX: 0,
     offsetY: 20,
     backgroundFill: new Fill({
       color: '#67C23A'
     }),
     padding: [0, 2, 0, 2],
     text: resolution < 1040 ? feature.get('index') : '',
     fill: new Fill({
         color: 'white'
     }),
  })
});

iconFeature.setStyle(iconStyle);

图层添加marker

var vectorSource = new VectorSource({
  features: [iconFeature]
});

var vectorLayer = new VectorLayer({
  source: vectorSource
});

map.addLayer(vectorLayer);
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容