openlayers地图使用—跟随地图比例尺动态标绘大小的一种方式
预期:随着地图比例尺放大缩小,地图上的标绘随着变化尺寸
结果图
页面元素
<script src="https://cdn.bootcdn.net/ajax/libs/openlayers/8.1.0/dist/ol.min.js"></script><link href="https://cdn.bootcdn.net/ajax/libs/openlayers/8.1.0/ol.min.css" rel="stylesheet"><style>.olMap {width: 100%;height: 500px;}</style>
<div id="map" class="olMap"></div>
js代码
(1)绘制地图
var map = null; // 地图var vectorSource = null;//图源var feas = [];// features集合// 初始化地图function initMap() {// 矢量图层vectorSource = new ol.source.Vector();// 创建矢量图层 绘制标注const vLayer = new ol.layer.Vector({source: this.vectorSource})// 高德地图var gaodeMapLayer = new ol.layer.Tile({title: "高德地图",source: new ol.source.XYZ({url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}',wrapX: false})});//地图容器map = new ol.Map({target: 'map',layers: [gaodeMapLayer,vLayer],view: new ol.View({center: ol.proj.transform([103.23, 35.33], 'EPSG:4326', 'EPSG:3857'), //地图初始中心点zoom: 12,minZoom: 1,maxZoom: 29}),})}initMap();
绘制标绘
/*** @description: 绘制一些图片*/function drawSome(num) {console.log('绘制一些图片', num);// 清空之前所有绘制的featurevectorSource.clear()feas = []// 添加若干图片for (let i = 0; i < num; i++) {// 创建一个活动图标需要的Feature,并设置随机位置const r1 = Math.random();const r2 = Math.random();let rand1 = r1 / 100 + i / 1000 + i / 1000;let rand2 = r2 / 100 + i / 1000 + i / 1000;rand1 = r1 > 0.45 ? rand1 : -rand1;rand2 = r2 > 0.45 ? rand2 : -rand2;const feature = new ol.Feature({geometry: new ol.geom.Point(ol.proj.transform([103.23 + rand1, 35.33 + rand2], 'EPSG:4326', 'EPSG:3857'))})feature.setId(9999 + i);// 设置Feature的样式,使用图标feature.setStyle(new ol.style.Style({image: new ol.style.Icon({src: "./bg02.jpg",anchor: [0.5, 1],scale: getScaleImgae(3000)})}))feas.push(feature)vectorSource.addFeature(feature)}}// 绘制100个featuredrawSome(100)
动态调整标绘
// 调整feature的尺寸function reDrawFeatures() {// 添加若干图片for (let i = 0; i < feas.length; i++) {const feature = feas[i]// 设置缩放等级feature.getStyle().getImage().setScale(getScaleImgae(3000))}}// 计算不同比例尺下 距离在屏幕上的宽度pxfunction getLengthPixel(length) {return length / map.getView().getResolution()}// 计算不同比例尺下,一定长度的图片(比如要在地图上3000m长的图片),图片在屏幕上应该缩放的大小function getScaleImgae(length) {const info = { width: 800 }const scale = getLengthPixel(length) / info.widthreturn scale}// 定时重绘// 改进:在适当的时机重绘即可setInterval(() => {reDrawFeatures()// console.log(`当前缩放层级是${map.getView().getZoom()},当前分辨率是${map.getView().getResolution()}`);}, 300)
注意:feature使用的图片资源如下,保存后修改名称即可