openlayers入門開發系列之地圖模態層篇
阿新 • • 發佈:2018-12-08
本篇的重點內容是為了到達自己想要的區域高亮效果,利用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); }