如何在 OpenLayers 3 上添加标记给坐标

How to add markers on OpenLayers 3 giving coordinates

我需要在调用方法 addMarker(long, lat) 时在我的地图上添加一个标记。 我找到的唯一示例是 this OpenLayers 示例列表中的一个,但它只在特定位置添加了一个标记。

我需要能够在需要时随时调用我的方法并传递坐标(一般的想法是有一个简单的菜单,用户可以在其中输入经度和纬度并单击提交按钮并绘制标记在地图上)。

在示例中,如果我做对了,他们创建了一个要素及其样式,然后创建了一个图层来绘制图标并使用该图层初始化了地图。

var iconFeature = new ol.Feature({
  geometry: new ol.geom.Point(ol.proj.transform([-72.0704, 46.678], 'EPSG:4326', 'EPSG:3857')),
  name: 'Null Island',
  population: 4000,
  rainfall: 500
});

var iconStyle = new ol.style.Style({
  image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
    anchor: [0.5, 46],
    anchorXUnits: 'fraction',
    anchorYUnits: 'pixels',
    opacity: 0.75,
    src: 'data/icon.png'
  }))
});

iconFeature.setStyle(iconStyle);

var vectorSource = new ol.source.Vector({
  features: [iconFeature]
});

var vectorLayer = new ol.layer.Vector({
  source: vectorSource
});

var map = new ol.Map({
  layers: [new ol.layer.Tile({ source: new ol.source.OSM() }), vectorLayer],
  target: document.getElementById('map'),
  view: new ol.View2D({
    center: [0, 0],
    zoom: 3
  })
});

我相信我可以创建一系列功能,类似的东西(我看到的一个例子 here):

var iconFeatures=[];

var iconFeature = new ol.Feature({
  geometry: new ol.geom.Point(ol.proj.transform([-72.0704, 46.678], 'EPSG:4326',     
  'EPSG:3857')),
  name: 'Null Island',
  population: 4000,
  rainfall: 500
});

var iconFeature1 = new ol.Feature({
  geometry: new ol.geom.Point(ol.proj.transform([-73.1234, 45.678], 'EPSG:4326',     
  'EPSG:3857')),
  name: 'Null Island Two',
  population: 4001,
  rainfall: 501
});

iconFeatures.push(iconFeature);
iconFeatures.push(iconFeature1);

到目前为止,这是我的方法:

class map{
    private markerFeatures = [];

    //receive an array of coordinates
    public addMarkers(markers: Array<Marker>): void { 
        for (var i in markers) {
            var markFeature = new ol.Feature({
              geometry: new ol.geom.Point(ol.proj.transform([markers[i].long, markers[i].lat], 'EPSG:4326',     
              'EPSG:3857')),
              name: 'Null Island',
              population: 4000,
              rainfall: 500
            });

            this.markerFeatures.push(markFeature);
        }            
    }
} 

但是当我这样做时什么也没发生。

Obs:我创建了地图、图层并调用了方法。 我正在使用 OL v3.7

假设您有一个包含矢量源的图层,您只需要在 addMarkers 函数中再添加一个步骤:

myVectorSource.addFeatures(markerFeatures);