前面实现一篇openlayers版本的地图模态层效果:openlayers入门开发系列之地图模态层篇
本文实现的是arcgis api 3.x版本的地图模态层,效果图如下:
实现的核心思路跟openlayers那里是一致的,利用turf.js提供的difference相差函数,计算最大四至和裁剪区域的差值;不过跟openlayers不一样的地方是,这里arcgis api版本的大四至是地图的当前地图范围,通过监听地图的范围变化事件来动态获取。不用(-180,-90,180,90)是因为发现用(-180,-90,180,90)来跟裁剪区域相差运算时候,绘制的多边形显示,发现有点影响顺畅,绘制的多边形区域太大,所以想用地图当前范围extent来替代。
模拟数据源采用大连市的普兰店市区域
- 实现核心代码
if (typeof DCI == "undefined") { var DCI = {}; } DCI.modalLayer = { map: null,//地图对象 graphicslayer: null,//显示图层 highlightSymbol: null,//区域高亮样式颜色 isModal:false, /* *初始化加载函数 */ Init: function (map) { DCI.modalLayer.highlightSymbol = new esri.symbol.SimpleFillSymbol( esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol( esri.symbol.SimpleLineSymbol.STYLE_SOLID, new esri.Color([255, 0, 0, 0]), 3 ), new esri.Color([0, 0, 0, 0.5]) ); DCI.modalLayer.map = map; DCI.modalLayer.graphicslayer = new esri.layers.GraphicsLayer(); DCI.modalLayer.map.addLayer(DCI.modalLayer.graphicslayer);//将图层赋给地图 var obj = DCI.modalLayer.getRegionByNAME("普兰店市"); if (obj) { loadModalLayer(); } //地图范围变化事件 map.on("extent-change", function (evt) { if (DCI.modalLayer.isModal) { loadModalLayer(); } }); function loadModalLayer() { DCI.modalLayer.graphicslayer.clear(); var boundCoord = [[[map.extent.xmin, map.extent.ymin], [map.extent.xmax, map.extent.ymin], [map.extent.xmax, map.extent.ymax], [map.extent.xmin, map.extent.ymax], [map.extent.xmin, map.extent.ymin]]]; var zoneCoord = obj.geometry.rings; var boundGeo = turf.polygon(boundCoord), zoneGeo = turf.polygon(zoneCoord); var modalJson = turf.difference(boundGeo, zoneGeo); if (modalJson && modalJson.geometry && modalJson.geometry.coordinates.length > 0) { if (zoneCoord.length && zoneCoord.length > 1) { for (var i = 0; i < zoneCoord.length; i++) { modalJson.geometry.coordinates.push(zoneCoord[i]); } } var polygon = null; switch (modalJson.geometry.type) { case "Polygon": polygon = new esri.geometry.Polygon(modalJson.geometry.coordinates); polygon.setSpatialReference(map.spatialReference); var modalGraphic = new esri.Graphic(polygon, DCI.modalLayer.highlightSymbol); DCI.modalLayer.graphicslayer.add(modalGraphic); break; case "MultiPolygon": for (var j = 0; j < modalJson.geometry.coordinates.length > 0; j++) { polygon = new esri.geometry.Polygon(modalJson.geometry.coordinates[j]); polygon.setSpatialReference(map.spatialReference); var modalGraphic = new esri.Graphic(polygon, DCI.modalLayer.highlightSymbol); DCI.modalLayer.graphicslayer.add(modalGraphic); } break; } } } }, /** * 根据区域名称获取对应的区域模拟数据 */ getRegionByNAME: function (regionNAME) { var obj = {}; if (regionData && regionData.length>0) { for (var i = 0; i < regionData.length; i++) { var data = regionData[i]; if (data.attributes.NAME == regionNAME) { obj = data; break; } } } return obj; } }