Fixed icon size in OpenLayers 3

久未见 提交于 2019-12-06 10:39:06

Yes, there is a solution. In a style function on the layer, you have to scale your icon size by a reference resolution divided by the render resolution.

To update the style even during user interaction, configure your layer with updateWhileInteracting: true and updateWhileAnimating: true. Here is the whole code:

var iconFeature = new ol.Feature(new ol.geom.Point([0, 0]));

var iconStyle = new ol.style.Style({
  image: new ol.style.Icon({
    anchor: [0.5, 46],
    anchorXUnits: 'fraction',
    anchorYUnits: 'pixels',
    src: 'https://openlayers.org/en/v4.3.2/examples/data/icon.png'
  })
});

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

var vectorLayer = new ol.layer.Vector({
  source: vectorSource,
  updateWhileAnimating: true,
  updateWhileInteracting: true,
  style: function(feature, resolution) {
    iconStyle.getImage().setScale(map.getView().getResolutionForZoom(3) / resolution);
    return iconStyle;
  }
});

var rasterLayer = new ol.layer.Tile({
  source: new ol.source.TileJSON({
    url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure',
    crossOrigin: ''
  })
});

var map = new ol.Map({
  layers: [rasterLayer, vectorLayer],
  target: 'map',
  view: new ol.View({
    center: [0, 0],
    zoom: 3
  })
});
html, body, #map {
  margin: 0;
  width: 100%;
  height: 100%;
}
<!DOCTYPE html>
<head>
  <link rel="stylesheet" href="https://openlayers.org/en/v4.3.2/css/ol.css">
  <script src="https://openlayers.org/en/v4.3.2/build/ol.js"></script>

</head>
<body>
  <div id="map" class="map"></div>
</body>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!