通过地图缩放更改图标大小

时间:2019-06-30 19:11:31

标签: openlayers openlayers-5

我正在使用20x20像素的图标显示在地图上,代码如下:

缩放地图时,图标看起来很小,如何通过缩放地图来更改图标大小?

 <link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
 <script src="https://openlayers.org/en/v4.6.5/build/ol.js" type="text/javascript"></script>

<script>
var baseMapLayer = new ol.layer.Tile({
    source: new ol.source.OSM()
  });

var view = new ol.View({
            center: ol.proj.fromLonLat([-74.0061,40.712]), 
            zoom: 17 //Initial Zoom Level
})

var map = new ol.Map({
    target: 'map',
    layers: [ baseMapLayer],
    view: view
});

// Make a new feature marker
var marker = new ol.Feature({
    name: 'Null Island',
    population: 4000,
    rainfall: 500,
    geometry: new ol.geom.Point(
      ol.proj.fromLonLat([-74.006,40.7127])  // new Point([0, 0])
    ),  // Cordinates of New York's Town Hall
});

// Style the marker
var iconStyle = new ol.style.Style({
    image: new ol.style.Icon(({
        color: '#ffcd46',
        crossOrigin: 'anonymous',
        src: 'http://127.0.0.1:8081/static/img/truck.png'
    }))
});

marker.setStyle(iconStyle);

// Make a source for the feature 
var vectorSource = new ol.source.Vector({
    features: [marker]
});
// Make a new layer
var markerVectorLayer = new ol.layer.Vector({
    source: vectorSource,
});

map.addLayer(markerVectorLayer);
</script>

1 个答案:

答案 0 :(得分:1)

您可以使用样式功能来实现,随着分辨率的变化而改变比例。分辨率可能会发生很大变化,因此您可能要改变分辨率的反比例平方根或立方根比例,然后进行实验以查看哪种适合您的应用程序。

如果在功能上设置,语法取决于OpenLayers的版本

OpenLayers 4:

marker.setStyle(function(resolution) {
    iconStyle.getImage().setScale(1/Math.pow(resolution, 1/3));
    return iconStyle;
});

OpenLayers 5:

marker.setStyle(function(feature, resolution) {
    iconStyle.getImage().setScale(1/Math.pow(resolution, 1/3));
    return iconStyle;
});

或者您可以在图层上设置样式,两种版本的语法都相同

var markerVectorLayer = new ol.layer.Vector({
    source: vectorSource,
    style: function(feature, resolution) {
        iconStyle.getImage().setScale(1/Math.pow(resolution, 1/3));
        return iconStyle;
    }
});