openlayers图标大小随zoom变化,icon动态变化 change:resolution

1,740 阅读1分钟

有两个思路;一个是动态样式,一个是事件监听更改样式。

change:resolution事件监听更改样式

1 map.getView().on('change:resolution',checkZoom);//checkZoom为调用的函数
 2 
 3 function checkZoom() {
 4     // alert("1");
 5     // var childId;
 6     console.log(map.getView().getZoom());
 7     if (map.getView().getZoom() == 11) {
 8         // console.log(vector.getSource().getFeatures()[0].getProperties().CODE);
 9         // childId = vector.getSource().getFeatures()[0].getProperties().CODE;
10         // vector.setVisible(false);
11         lastVectorShow();
12 
13     }
14 }

动态样式
stackoom.com/question/3q…
温馨提示:将鼠标放在语句上可以显示对应的英文。 或者 切换至中英文显示
我正在使用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>

openlayers openlayers-5
1 个回复
按投票数排序按时间排序

===============>>#1 票数: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;
    }
});