本篇的重点内容是为了到达自己想要的区域高亮效果,利用openlayers结合turf.js实现地图模态层功能,效果图如下:
实现思路
利用turf.js提供的difference相差函数,计算最大四至和裁剪区域的差值,这里的最大四至即:(-180,-90,180,90),由于底图是墨卡托投影坐标系的,所以我的代码实现过程中把经纬度转换墨卡托投影坐标;裁剪区域就是需要高亮的多边形,我这里是嘉兴市区域。
- 界面设计
//地图模态层 "<div style=‘height:25px;background:#30A4D5;margin-top:10px;width: 98%;margin-left: 3px;float: left;‘>" + "<span style=‘margin-left:5px;font-size: 13px;color:white;‘>地图模态层</span>" + "</div>" + ‘<div id="modalLayer" style="padding:5px;float: left;">‘ + ‘<input type="checkbox" name="modallayer" id="modallayer" style="width: 15px;height: 15px;vertical-align: middle;margin: auto;"/>‘ + ‘<label style="font-weight: normal;vertical-align: middle;margin: auto;">地图模态层</label>‘ + ‘</div>‘ +
- 点击事件
//地图模态层 $("#modalLayer input").bind("click", function () { if (this.checked) { DCI.modalLayer.Init(bmap.getMap()); } else { if(DCI.modalLayer.layer){ bmap.getMap().removeLayer(DCI.modalLayer.layer); DCI.modalLayer.layer = null; } } })
- 嘉兴市区域数据源,ggeojson格式的我这里,由于太长了,截图部分
var modalData = {"type":"FeatureCollection", "features": [{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[13463825.244668555,3637243.4277185723],[13464136.939242788,3636775.738240453],[13464537.689409656,3636827.702864958]……]]]},"properties":{"OBJECTID":2,"XZDM":"330411000000","XJMC":"嘉兴市"}}]}
- 核心实现代码
Init: function (map) { //经纬度转换墨卡托投影坐标 var xy1 = ol.proj.fromLonLat([-180, -90]); var xy2 = ol.proj.fromLonLat([180, 90]); var xy3 = ol.proj.fromLonLat([180, -90]); var xy4 = ol.proj.fromLonLat([-180, 90]); var boundCoord = [[[xy1[0],xy1[1]], [xy3[0],xy3[1]], [xy2[0],xy2[1]], [xy4[0],xy4[1]], [xy1[0],xy1[1]]]]; var zoneCoord = modalData.features[0].geometry.coordinates; var boundGeo = turf.polygon(boundCoord), zoneGeo = turf.polygon(zoneCoord); var modalJson = turf.difference(boundGeo, zoneGeo); var features = (new ol.format.GeoJSON()).readFeatures(modalJson); var vector = DCI.modalLayer.layer = new ol.layer.Vector({ renderMode: "image",//image, vector source: new ol.source.Vector({ features: features }), style: new ol.style.Style({ fill: new ol.style.Fill({ color: ‘rgba(0, 0, 0, 0.5)‘ }) }), zIndex: 999 }); map.addLayer(vector); //地图跳转范围 map.getView().setCenter([13442827.291, 3590017.907]); map.getView().setZoom(10); }
原文地址:https://www.cnblogs.com/giserhome/p/10088600.html
时间: 2024-10-09 13:31:28