如何使用OpenLayers 4.6.4向OSM地图添加图标/标记

3
我希望有人能指导我正确的方向。我正在尝试使用OpenLayers 4.6.4在OSM地图上添加多个标记/图标。
以下代码可以正常渲染地图:
    <script src="https://openlayers.org/en/v4.6.4/build/ol.js"></script>
    <script type='text/javascript'>
        var map = new ol.Map({
            target: 'mapdiv',
            layers: [
                new ol.layer.Tile({
                    source: new ol.source.OSM()
                })
            ],
            view: new ol.View({
                center: ol.proj.fromLonLat([-0.1526069, 51.4790309]),
                zoom: 14
            })
        });
    </script>

我尝试在OpenLayers网站上搜索添加标记的信息,但是它指出标记已经不推荐使用! 我只想在地图上添加一些针或标记以显示站点位置。
我还尝试了其他版本的OpenLayers 2.13.1、2.14和3.0,但没有成功。
非常感谢您的帮助。
1个回答

8

旧标记已经被弃用。您应该使用几何图标样式。您需要的是图标符号示例

document.addEventListener("DOMContentLoaded", function() {
  var iconFeature1 = new ol.Feature({
    geometry: new ol.geom.Point(ol.proj.fromLonLat([-0.1526069, 51.4790309]), ),
    name: 'Somewhere',
  });

  var iconFeature2 = new ol.Feature({
    geometry: new ol.geom.Point(ol.proj.fromLonLat([-0.1426069, 51.4840309])),
    name: 'Somewhere else'
  });

  // specific style for that one point
  iconFeature2.setStyle(new ol.style.Style({
    image: new ol.style.Icon({
      anchor: [0.5, 46],
      anchorXUnits: 'fraction',
      anchorYUnits: 'pixels',
      src: 'https://upload.wikimedia.org/wikipedia/commons/thumb/9/93/Map_marker_font_awesome.svg/200px-Map_marker_font_awesome.svg.png',
    })
  }));




  const iconLayerSource = new ol.source.Vector({
    features: [iconFeature1, iconFeature2]
  });

  const iconLayer = new ol.layer.Vector({
    source: iconLayerSource,
    // style for all elements on a layer
    style: new ol.style.Style({
      image: new ol.style.Icon({
        anchor: [0.5, 46],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        src: 'https://openlayers.org/en/v4.6.4/examples/data/icon.png'
      })
    })
  });


  const map = new ol.Map({
    target: 'map',
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM(),
      }),
      iconLayer
    ],
    view: new ol.View({
      center: ol.proj.fromLonLat([-0.1526069, 51.4790309]),
      zoom: 14
    })
  });
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.5/ol.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.5/ol-debug.js"></script>

<div id="map" class="map"></div>


感谢你的回复和指导,伙计。非常感激。 - ridgedale

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接