WebGIS常用代码

一.普通代码

#openLayers

1.坐标转换

ol.proj.transform(coordinate, source, destination)

ol.proj.transform(coordinate, 'EPSG:4326', 'EPSG:3857')

2.根据坐标创建点要素图层
复制代码
 1 function videoPoint(getVideoPointURL) {
 2         setTimeout(function () {
 3             var vectorLayer = getLayerByTitle('视频监测点');
 4             var vectorSource = new ol.source.Vector();
 5             vectorLayer.setSource(vectorSource);
 6             $.get(getVideoPointURL, function (points) {
 7                 for (var i in points) {
 8                     var lng = points[i].x;
 9                     var lat = points[i].y;
10                     if (lng && lat) {
11                         var dic_values = points[i];
12                         var newFeature = new ol.Feature();
13                         var x = parseFloat(lng);
14                         var y = parseFloat(lat);
15                         var newcoordinates = ol.proj.transform([x, y],
16                             'EPSG:4326',
17                             'EPSG:3857');
18                         //地图添加坐标点
19                         newFeature.setGeometry(new ol.geom.Point(newcoordinates));
20                         newFeature.setProperties(dic_values);
21                         vectorSource.addFeature(newFeature);
22                     }
23                 }
24             }, "json");
25         }, 1000);
26     }  
View Code
复制代码
3.c#数据转换

   double lastLon = Convert.ToDouble(lastLatLon.GetValue(0)); 

 4.添加地图
复制代码
 1 var createMap = function(divId) {
 2         var source, layer, map, zoomslider;
 3 
 4         source = new ol.source.OSM();
 5         layer = new ol.layer.Tile({
 6           source: source
 7         });
 8         map = new ol.Map({
 9           layers: [layer],
10           target: divId,
11           view: new ol.View({
12             center: [0, 0],
13             zoom: 12
14           })
15         });
16         zoomslider = new ol.control.ZoomSlider();
17         map.addControl(zoomslider);
18         return map;
19       };
20  var map1 = createMap('map1');
View Code
复制代码
  5.将要素缩放到要素范围
 6.鼠标悬停获取坐标、弹窗的关键代码 
复制代码
 1  var flag = false;
 2 //鼠标悬停弹窗,显示该要素内容
 3 function hoverPop(evt) {
 4     // 获取像素区域 
 5     var pixel = map.getEventPixel(evt.originalEvent);//获取鼠标源坐标
 6     var hasFeature = map.hasFeatureAtPixel(evt.pixel, {
 7         layerFilter: function (layer) {
 8             var dics = layer.getProperties();
 9             if (dics["title"] == '文保点' || dics["title"] == '视频监测点') {
10                 return true;
11             }
12         }
13     });
14 
15     if (hasFeature) {
16         map.forEachFeatureAtPixel(pixel, function (feature){
17             coodinate = evt.coordinate;
18             var htmlContent;
19             if (feature.get('LyrName') == "文保单位") {
20 
21               
22                 htmlContent = feature.get("Name");
23                 PopUp_overlay.show(coodinate, htmlContent);
24             }
25             else if (feature.get('LyrName') == '视频监测点图层') {
26                 if (flag) {
27                     return;
28                 }
29                 flag = true;
30                 var properties = feature.getProperties();
31                 var deviceID = properties.DeviceID;
32                 var pointId = properties.Solr_DevID;//太阳能的solar_DevID             
33                 if (deviceID) {
34                     //如果是新增设备
35                     if (pointId >= 0) {
36                         //如果有太阳能设备
37                         $.ajax({
38                             //获取设备电压电流等信息
39                             url: "/api/solar/collect",
40                             type: "get",
41                             data: { "DevId": pointId },
42                             success: function (data) {
43                                 console.log(data);
44                                 var dic_values = JSON.parse(data).Result[0];
45                                 var htmlContent = "";
46                                 //<button 
47                                 //type="button" onclick='displayDetail()'
48                                 //class='am-btn am-btn-primary'
49                                 //data-am-modal="{target: '#doc-modal-1', closeViaDimmer: 0, width: 718, height: 655}">
50                                 htmlContent += "<div class='map-content'><div class='map-title'> <div class='left-totle'><div class='name'><p>" + dic_values['point_name'] + "<br/><span class='status'>正常</span></p></div></div >";
51                                 htmlContent += "<div class='btn'></div></div>";
52                                 htmlContent += "<div  style='cursor:pointer;'onclick='displayEcharts(" + pointId + ")'><div class='item-box'><div class='item-div itemColor1'><img src='/Static/Map/img/ico1.png'><span>" + dic_values['蓄电池电量'] + "</span></div><div class='item-div itemColor2'><img src='/Static/Map/img/ico2.png'><span>" + dic_values['电池电压'] + "</span></div></div>";
53                                 htmlContent += "<div class='item-box'><div class='item-div itemColor3'><img src='/Static/Map/img/ico3.png'><span>" + dic_values['太阳能充电电流'] + "</span></div><div class='item-div itemColor4'><img src='/Static/Map/img/ico4.png'><span>" + dic_values['负载端输出电流'] + "</span></div></div></div>";
54                                 htmlContent += "<div style='cursor:pointer;'onclick='ViewSolorEngDetail(" + pointId + ")' class='item-div unusual'><span  class='viewDetail'>" + '查看详细信息' + "</span></div>";
55                                 console.log(flag + 'setfalse');
56                                 PopUp_overlay3.show(coodinate, htmlContent);
57 
58                             },
59                             error: function () {
60                                 flag = false;
61                             },
62                             datatype: "json"
63                         });
64 
65                     }
66 
67                     else {
68                         //如果没有太阳能设备
69                         htmlContent = feature.get("Name");
70                         PopUp_overlay.show(coodinate, htmlContent);
71                     }
72 
73                 }
74                 else {
75                     //原始摄像头设备
76                     htmlContent = feature.get("pointName");
77                     PopUp_overlay.show(coodinate, htmlContent);
78                 }             
79 
80             }
81 
82         })
83 
84 
85     } else {
86         //console.log("鼠标移出要素,隐藏弹窗");
87         PopUp_overlay.hide();
88         //PopUp_overlay3.hide();
89         flag = false;
90     }
91 
92 }
View Code
复制代码
 7.样式styles

①文字样式示例

复制代码
 1  var cityClusterStyle = new ol.style.Style({
 2         image: new ol.style.Circle({
 3             radius: 60,
 4 
 5             fill: new ol.style.Fill({
 6                 color: '#006e5f',
 7                 opacity: 0.8
 8             }),
 9             stroke: new ol.style.Stroke({
10                 color: '#fff',
11                 width: 1
12             })
13         }),
14         text: new ol.style.Text({ //文本样式
15             text: data.CityName + '\n' + data.Total + "个",
16 
17             font: '13px MicrosoftYahei',
18             overflow: true,
19             fill: new ol.style.Fill({
20                 color: 'white'
21             })
22             //stroke: new ol.style.Stroke({
23             //    color: 'black',
24             //    width: 3
25             //})
26         }),
27     })
View Code
复制代码

 

 8.OpenLayers引入V4.6.5

复制代码
 1 <head>
 2   <title>Modify Features</title>
 3   <link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
 4   
 5   <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
 6   <script src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
 7   <script
 8     src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
 9   <script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>
10  
11 </head>
View Code
复制代码

 

 9.openlayers调用arcmap发布的切片服务

  

复制代码
 // 瓦片地址
    var vectorUrl = "http://ip地址:端口号/arcgis/rest/services/vector/MapServer/tile/{z}/{y}/{x}";
    var vectorAnnoUrl = "http://ip地址:端口号/arcgis/rest/services/vector_anno_412/MapServer/tile/{z}/{y}/{x}";
    // 地图投影
    var projection = ol.proj.get("EPSG:4326");
    // 原点
    var origin = [-180.0, 90.0];
    // 分辨率  最小zoom为7,最大zoom为18
    var resolutions = [
        1.406250026231578,
        0.703125013115789,
        0.3515625065578945,
        0.17578125327894775,
        0.08789062663947399,
        0.043945313319736994,
        0.021972656659868472,
        0.010986328329934226,
        0.005493164164967124,
        0.0027465820824835504,
        0.0013732910412417797,
        6.866455206208899e-4,
        3.433227603104438e-4,
        1.716613801552224e-4,
        8.583069007761132e-5,
        4.291534503880566e-5,
        2.1457672519402802e-5,
        1.0728836259701401e-5,
        5.364418129850712e-6,
        2.682209064925356e-6,
        1.341104532462678e-6
    ];
    // 地图范围
    var fullExtent = [
        116,
        30,
        121,
        34
    ];
    var tileGrid = new ol.tilegrid.TileGrid({
        tileSize: 256,
        origin: origin,
        extent: fullExtent,
        resolutions: resolutions
    });
    // 瓦片数据源
    var tileVectorXYZ = new ol.source.XYZ({
        tileGrid: tileGrid,
        projection: projection,
        url: vectorUrl
    });

    var layer= new ol.layer.Tile({
                                source: tileVectorXYZ
                            }),
View Code
复制代码

 10.OpenLayers添加坐标生成面

  

复制代码
 1 <!DOCTYPE html>
 2 <html>
 3 
 4 <head>
 5     <title>OpenLayers根据坐标生成面</title>
 6     <link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
 7     <script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>
 8 </head>
 9 
10 <body>
11     <div id="map" style="height: 600px;"></div>
12     <div id="mouse-position"></div>
13     <script>
14 
15         var layers = [
16             //底图 openstreetmap
17             new ol.layer.Tile({
18                 source: new ol.source.OSM({
19                 }),
20             }),
21 
22         ];
23 
24         var map = new ol.Map({
25             layers: layers,
26             target: 'map',
27             view: new ol.View({
28                 projection: 'EPSG:4326',
29                 center: [117.2, 29.298],
30                 zoom: 14
31             }),
32             controls: ol.control.defaults({ attribution: false }).extend([
33                 new ol.control.Rotate(),
34                 new ol.control.ZoomSlider(),
35                 new ol.control.MousePosition({
36                     coordinateFormat: ol.coordinate.createStringXY(8),
37                     projection: 'EPSG:4326',
38                     className: 'custom-mouse-position',
39                     target: document.getElementById('mouse-position')
40                 }),
41                 // new ol.control.ScaleLine({
42                 //     units: "metric", //设置比例尺单位,有degrees、imperial、us、nautical或metric  
43                 //     target: document.getElementById('scale-line') //显示比例尺的目标容器  
44                 // }),
45             ]),
46         });
47 
48         var fStyle1 = new ol.style.Style({                                //图形样式
49             fill: new ol.style.Fill({
50                 color: 'green'
51             }),
52             stroke: new ol.style.Stroke({
53                 color: 'red',
54                 width: 2
55             }),
56             image: new ol.style.Circle({
57                 radius: 7,
58                 fill: new ol.style.Fill({
59                     color: 'red'
60                 })
61             })
62         });
63         var szDrawLayer = new ol.layer.Vector({
64             source: new ol.source.Vector()
65         });
66         map.addLayer(szDrawLayer);
67         var polygonArr = [[117.19040680, 29.30657959], [117.19804573, 29.28143120], [117.21598434, 29.29610825], [117.19040680, 29.30657959]];
68         //   for (var i = 0; i < point.length; i++) {
69         //       point[i] = ol.proj.transform(point[i], 'EPSG:4326', 'EPSG:3857');
70         //       dots1.push(point[i]);
71         //   }
72         var polygon = new ol.geom.Polygon([polygonArr]);//此处要注意将坐标数组放到数组中
73         var newFeature = new ol.Feature();   //画图形
74         newFeature.setGeometry(polygon);
75         newFeature.setStyle(fStyle1);                //给图形添加样式
76         szDrawLayer.getSource().addFeature(newFeature);                 //地图添加图形
77 
78     </script>
79 </body>
80 
81 </html>
View Code
复制代码

  参考网址:根据坐标点画图形

       OpenLayers - 创建多边形Polygon

11.GeoJSON 矢量切片

  

复制代码
 1 <!DOCTYPE html>
 2 <html>
 3 
 4 <head>
 5   <title>GeoJSON 矢量切片</title>
 6   <link rel="stylesheet" href="css/ol.css" type="text/css">
 7   <link rel="stylesheet" href="css/ol-ext.css" type="text/css">
 8 
 9 
10   <style>
11 
12   </style>
13   <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
14   <script src="scripts/jquery.min.js"></script>
15   <script
16     src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
17 
18   <script src="scripts/ol.js"></script>
19   <script src="scripts/ol-ext.js"></script>
20 
21 
22 </head>
23 
24 <body>
25   <div id="map" class="map"></div>
26   <script>
27     // 创建一个视图
28     var coordinate = [120.3993, 31.08125];
29     // var coor = ol.proj.transform(coordinate, 'EPSG:4326', 'EPSG:3857');
30 
31     var view = new ol.View({
32       center: coordinate,
33       zoom: 6,
34       minZoom: 0,
35       maxZoom: 25,
36       projection: 'EPSG:4326',
37     });
38 
39     var projection4326 = new ol.proj.Projection({
40       code: 'EPSG:4326',
41       units: 'degrees',
42       axisOrientation: 'neu'
43     });
44 
45     var BaseMapVectorLayerTile = new ol.layer.VectorTile({
46       title: "baseMap_Tile",
47       style: new ol.style.Style({
48         stroke: new ol.style.Stroke({
49           color: '#888888',//#38D0F0
50           width: 2
51         }),
52         fill: new ol.style.Fill({
53           color: 'white'
54         }),
55         text: new ol.style.Text({ //文本样式
56           font: 'bold 12px serif',
57           overflow: true,
58           fill: new ol.style.Fill({
59             color: '#000'
60           }),
61           stroke: new ol.style.Stroke({
62             color: '#fff',
63             width: 3
64           })
65         })
66       }),
67       projection: projection4326,
68       //矢量切片数据
69       source: new ol.source.VectorTile({
70         projeciton: projection4326,
71         format: new ol.format.GeoJSON(),
72         tileGrid: ol.tilegrid.createXYZ({
73           extent: ol.proj.get('EPSG:4326').getExtent(),
74           maxZoom: 25
75         }),
76         tilePixelRatio: 1,
77         //发出获取切片的请求
78         tileUrlFunction: function (tileCoord) {
79           return 'http://localhost:8080/geoserver/gwc/service/tms/1.0.0/test%3ACHN_adm1@EPSG%3A4326@geojson/' + (tileCoord[0] - 1)
80             + '/' + tileCoord[1] + '/' + (Math.pow(2, tileCoord[0] - 1) + tileCoord[2]) + '.geojson';
81         }
82       })
83     });
84     // 创建第一个地图
85     var map = new ol.Map({
86       layers: [
87         new ol.layer.Tile({ source: new ol.source.OSM() }),
88         BaseMapVectorLayerTile,
89       ],
90       view: view,
91       target: 'map'
92     });
93 
94   </script>
95 </body>
96 
97 </html>
View Code
复制代码

 12.缓冲区,最短距离

复制代码
  1 <!DOCTYPE html>
  2 <html>
  3 
  4 <head>
  5   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  6   <title>Demo</title>
  7   <link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
  8   <style type="text/css">
  9     .search {
 10       font-size: 13px;
 11       border: 1px solid #999999;
 12     }
 13 
 14     .ls {
 15       line-height: 27px;
 16       padding-left: 7px;
 17     }
 18 
 19     .prompt {
 20       display: none;
 21       font-size: 13px;
 22       border: 1px solid #999999;
 23     }
 24 
 25     .statistics {
 26       display: none;
 27       font-size: 13px;
 28       border: 1px solid #999999;
 29       overflow-y: scroll;
 30       height: 150px;
 31     }
 32 
 33     .suggests {
 34       display: none;
 35       font-size: 13px;
 36       border: 1px solid #999999;
 37     }
 38 
 39     ;
 40 
 41     .lineData {
 42       display: none;
 43       font-size: 13px;
 44       border: 1px solid #999999;
 45     }
 46 
 47     .result {
 48       display: none;
 49       font-size: 12px;
 50       border: 1px solid #999999;
 51       line-height: 27px;
 52       padding-left: 7px;
 53     }
 54   </style>
 55 
 56   <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
 57   <script src="scripts/jquery.min.js"></script>
 58   <script
 59     <src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
 60   <script src="scripts/ol.js"></script>
 61   <script src="scripts/baidu.js"></script>
 62   <script src="scripts/turf.min.js"></script>
 63   <!-- <script src="scripts/baidu2.js"></script> -->
 64   <!-- <script src="http://api.tianditu.gov.cn/api?v=4.0&tk=8c664e845b4f2e2607407303ff82192f"></script> -->
 65 </head>
 66 
 67 <body>
 68   <!-- <div style="background:red" >嗯嗯</div>
 69   <button onclick="zoom([120.785799,31.343351])">缩放</button> -->
 70 
 71   <!-- <div id="tdtmap" style="height: 100px;"></div> -->
 72   <div id="map" style="width: 100%;height: 800px;"> </div>
 73   <div id="mouse-position"></div>
 74   <script>
 75     //自定义业务图层,定义于initData.js中
 76     function getLayerByTitle(title) {
 77       //先得到groupLayer,再在grouplayer里得到具体的layer,
 78       //第一个groupLayer是底图,第二个groupLayer是业务图层,这个函数获取的就是业务图层
 79       var groupLayers = map.getLayers().getArray();
 80       var layers = groupLayers[1].getLayers().getArray();
 81       for (var i = 0; i < layers.length; i++) {
 82         var dics = layers[i].getProperties();
 83         if (dics["title"] == title) {
 84           return layers[i];
 85         }
 86       }
 87       return null;
 88     }
 89 
 90     $(function () {
 91       var baiduImg = new ol.layer.Tile({
 92         source: new ol.source.XYZ({
 93           projection: 'baidu',
 94           maxZoom: 25,
 95           crossOrigin: 'anonymous',
 96           tileUrlFunction: function (tileCoord) {
 97             var x = tileCoord[1];
 98             var y = tileCoord[2];
 99             var z = tileCoord[0];
100 
101             // return "http://shangetu1.map.bdimg.com/it/u=x={x};y={y};z={z};type=sate&fm=46&udt=20130506";
102 
103             return "http://online3.map.bdimg.com/tile/?qt=vtile&x=" + x + "&y=" + y + "&z=" + z + "&styles=pl&udt=udt=20170908&scaler=1&p=1"
104 
105 
106             // return "http://api0.map.bdimg.com/customimage/tile?x=" + x
107             //   + "&y=" + y + "&z=" + z
108             //   + "&udt=20170908&scale=2&ak=ZUONbpqGBsYGXNIYHicvbAbM"
109             //   + "&styles=t%3Awater%7Ce%3Aall%7Cc%3A%23044161%2Ct%3Aland%7Ce%3Aall%7Cc%3A%23004981%2Ct%3Aboundary%7Ce%3Ag%7Cc%3A%23064f85%2Ct%3Arailway%7Ce%3Aall%7Cv%3Aoff%2Ct%3Ahighway%7Ce%3Ag%7Cc%3A%23004981%2Ct%3Ahighway%7Ce%3Ag.f%7Cc%3A%23005b96%7Cl%3A1%2Ct%3Ahighway%7Ce%3Al%7Cv%3Aoff%2Ct%3Aarterial%7Ce%3Ag%7Cc%3A%23004981%2Ct%3Aarterial%7Ce%3Ag.f%7Cc%3A%2300508b%2Ct%3Apoi%7Ce%3Aall%7Cv%3Aoff%2Ct%3Agreen%7Ce%3Aall%7Cv%3Aoff%7Cc%3A%23056197%2Ct%3Asubway%7Ce%3Aall%7Cv%3Aoff%2Ct%3Amanmade%7Ce%3Aall%7Cv%3Aoff%2Ct%3Alocal%7Ce%3Aall%7Cv%3Aoff%2Ct%3Aarterial%7Ce%3Al%7Cv%3Aoff%2Ct%3Aboundary%7Ce%3Ag.f%7Cc%3A%23029fd4%2Ct%3Abuilding%7Ce%3Aall%7Cc%3A%231a5787%2Ct%3Alabel%7Ce%3Aall%7Cv%3Aoff&t = 1505487396397";
110           },
111           tileGrid: new ol.tilegrid.TileGrid({
112             resolutions: bmercResolutions,
113             origin: [0, 0],
114             extent: ol.extent.applyTransform(extent, projzh.ll2bmerc),
115             tileSize: [256, 256]
116           })
117         })
118       });
119       ////声明矢量、影像底图和文字标注
120       tdtVectorLayer = new ol.layer.Tile({
121         //天地图矢量
122         source: new ol.source.XYZ({
123           title: "天地图路网",
124           url: "http://t{0-7}.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=926da4893299639547a460a3202028ad"
125         })
126       });
127       tdtVectorTxtLayer = new ol.layer.Tile({
128         //天地图矢量文字标注
129         source: new ol.source.XYZ({
130           title: "天地图矢量文字标注",
131           url: "http://t{0-7}.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=926da4893299639547a460a3202028ad"
132 
133         })
134       });
135 
136 
137       //比例尺
138       var controls = new Array();
139       var scaleLineControl = new ol.control.ScaleLine({
140         units: "metric",
141         target: document.getElementById('scale-line')
142       });
143       //坐标
144       var mousePosition = new ol.control.MousePosition({
145         coordinateFormat: ol.coordinate.createStringXY(8),
146         projection: 'EPSG:4326',
147         className: 'custom-mouse-position',
148         target: document.getElementById('mouse-position')
149       });
150       controls.push(scaleLineControl);
151       controls.push(mousePosition);
152       var plaImageLayer = new ol.layer.Tile({
153         title: "航拍影像",
154         source: new ol.source.TileWMS({
155           url: "http://10.10.10.156:8080/geoserver/test/wms?service=WMS",
156           params: {
157             'LAYERS': "test:companyTif"
158 
159             // 'TILED': true   //是否要将数据制作成切片,省略后返回的是一张完整图。
160           },
161 
162         })
163       });
164       var plaImageLayer2 = new ol.layer.Tile({
165         title: "航拍影像2",
166         source: new ol.source.TileWMS({
167           url: "http://192.168.100.10:8090/geoserver/Demo/wms",
168           params: {
169             'LAYERS': "Demo:shahuSciencePark",
170 
171             'TILED': true   //是否要将数据制作成切片,省略后返回的是一张完整图。
172           },
173 
174         })
175       });
176 
177       var url = 'http://192.168.100.10:8090/geoserver/gwc/service/tms/1.0.0/Demo%3AshahuSciencePark@CustomGridset3857@png/';
178       var url2 = 'http://192.168.100.10:8090/geoserver/gwc/service/tms/1.0.0/Demo%3AshaHuSciPark@My_EPSG%3A4326@png/';
179 
180       var projectionXYZ = new ol.proj.get("EPSG:4326");
181       var resolutions = [0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625, 0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625, 0.0006866455078125, 0.00034332275390625, 0.000171661376953125, 0.0000858306884765625, 0.00004291534423828125, 0.000021457672119140625, 0.000010728836059570312, 0.000005364418029785156, 0.000002682209014892578, 0.000001341104507446289, 6.705522537231445e-7, 3.3527612686157227e-7, 0.0000001676380634, 0.0000000838190317, 0.0000000419095159];
182 
183       //   console.log(resolutions)
184       var testLayer = new ol.layer.Tile({
185         // extent: [120.77529968315073,31.33954823551859,120.77920489456193,31.342946833599022],
186         source: new ol.source.XYZ({
187           projection: projectionXYZ,
188           maxZoom: 24,
189           minZoom: 0,
190           tileGrid: ol.tilegrid.createXYZ({
191             extent: projectionXYZ.getExtent()
192           }),
193           tileGrid: new ol.tilegrid.TileGrid({
194             extent: ol.proj.get('EPSG:4326').getExtent(),
195             origin: [-180, -90],
196             resolutions: resolutions,
197 
198           }),
199           tileUrlFunction: function (tileCoord) {
200             projection: new ol.proj.get('EPSG:4326');
201             var z = tileCoord[0];
202             var x = tileCoord[1];
203             var y = tileCoord[2];
204             return url2 + z + '/' + x + '/' + y + '.png'
205           }
206         })
207       });
208       var center = ol.proj.transform([120.77725228885632, 31.341247534558804], 'EPSG:4326', 'EPSG:3857');//ol.proj.transform([120.77725228885632, 31.341247534558804], 'EPSG:4326', 'EPSG:3857')
209       map = new ol.Map({
210         target: 'map',
211         layers: [
212           // tdtVectorLayer,
213           // tdtVectorTxtLayer,
214           // baidu,
215           baiduImg,
216           // plaImageLayer,
217           // plaImageLayer2,
218           testLayer,
219           // add_point_layer 
220         ],
221         // 设置显示地图的视图
222         view: new ol.View({
223           //这个百度的瓦片图层加载的是3857投影,所以map的center得转换一下坐标系,转成你要加载的图层要素的投影
224           center: center,
225           projection: 'EPSG:3857',//EPSG:3857
226           zoom: 17,
227           maxZoom: 25,
228           minZoom: 10
229         }),
230         controls: ol.control.defaults({
231         }).extend(controls)
232 
233       });
234 
235 
236       var pointsList = [[120.77568769, 31.34281585]];
237 
238       var turfPoint = turf.point(pointsList[0]);
239       var buffered = turf.buffer(turfPoint, 0.2, { units: 'kilometers' });
240       console.log("bufferd类型为:");
241       console.log(buffered)
242       console.log(typeof buffered)
243 
244       //创建数据geojson对象和数据源对象
245       var format = new ol.format.GeoJSON();
246       var source = new ol.source.Vector();
247       //读取geojson数据
248       var a = format.readFeature(turfPoint);
249 
250       // console.log(a);
251 
252       var b = format.readFeature(buffered);
253       console.log("json buffer")
254       console.log(b);
255       a.getGeometry().transform('EPSG:4326', 'EPSG:3857');
256       b.getGeometry().transform('EPSG:4326', 'EPSG:3857');
257       // console.log(b);
258       //将数据添加到数据源
259       source.addFeature(a);
260       // source.addFeature(b);
261 
262 
263       var polyonCoor = [[120.77529073, 31.34240350], [120.77845573, 31.34299911], [120.77912092, 31.34032343], [120.77608466, 31.33985609], [120.77529073, 31.34240350]];
264       console.log(polyonCoor)
265       var turfPolygon = turf.polygon([polyonCoor]);
266       var buffered2 = turf.buffer(turfPolygon, 0.2, { units: 'kilometers' });
267       var format2 = new ol.format.GeoJSON();
268       var source = new ol.source.Vector();
269       //读取geojson数据
270       var a = format2.readFeature(turfPolygon);
271 
272       var b = format2.readFeature(buffered2);
273       a.getGeometry().transform('EPSG:4326', 'EPSG:3857');
274       b.getGeometry().transform('EPSG:4326', 'EPSG:3857');
275       //将数据添加数据源的
276       source.addFeature(a);
277       source.addFeature(b);
278 
279 
280 
281       // 添加一个绘制的线使用的layer
282       var polygonLayer = new ol.layer.Vector({
283         source: source,
284         style: new ol.style.Style({
285           stroke: new ol.style.Stroke({
286             color: 'red',
287             size: 1
288           }),
289           fill: new ol.style.Fill({
290             color: 'rgba(255,0,0,0.2)'
291           }),
292           image: new ol.style.Circle({
293             radius: 6,
294             stroke: new ol.style.Stroke({
295               color: 'rgba(0,0,0,0.5)'
296             }),
297             fill: new ol.style.Fill({
298               color: 'rgba(255,0,0,1)'
299             })
300           })
301 
302         }),
303 
304       });
305       map.addLayer(polygonLayer);
306       var DefenseZoneLayer = new ol.layer.Vector({
307 
308         title: '防区',
309         visible: true,
310         source: null,
311         style: new ol.style.Style({
312           stroke: new ol.style.Stroke({
313             color: 'yellow',
314             size: 1
315           }),
316           fill: new ol.style.Fill({
317             color: 'rgba(255,255,0,0.2)'
318           }),
319           image: new ol.style.Circle({
320             radius: 6,
321             stroke: new ol.style.Stroke({
322               color: 'rgba(0,0,0,0.5)'
323             }),
324             fill: new ol.style.Fill({
325               color: 'rgba(255,0,0,1)'
326             })
327           })
328 
329         }),
330 
331       });
332       map.addLayer(DefenseZoneLayer);
333 
334       //点到线的最短距离
335       var line = turf.polygonToLine(turfPolygon);
336       console.log(line)
337       var snapped = turf.nearestPointOnLine(line, turfPoint, { units: 'kilometers' });
338       console.log(snapped);
339       console.log("在第" + snapped.properties.index + "个直线部分上找到最近的点");
340       console.log("最短距离为:" + snapped.properties.dist * 1000 + "");
341       console.log("沿着起点和最近点之间的线的距离:" + snapped.properties.location * 1000 + "");
342       // setTimeout(function(){
343       //   alert("在第"+snapped.properties.index+"个直线部分上找到最近的点\n"+"最短距离为:"+snapped.properties.dist*1000+"米\n"+"沿着起点和最近点之间的线的距离:"+snapped.properties.location*1000+"米");
344       // // alert("最短距离为:"+snapped.properties.dist*1000+"米");
345       // // alert("沿着起点和最近点之间的线的距离:"+snapped.properties.location*1000+"米");
346 
347       // },1000);
348 
349 
350       // polyonCoor=polyonCoor.transform('EPSG:4326', 'EPSG:3857');
351       var polygon1 = new ol.geom.Polygon([polyonCoor]);
352       polygon1.applyTransform(ol.proj.getTransform('EPSG:4326', 'EPSG:3857'));
353       var newFeature1 = new ol.Feature(polygon1);
354       newFeature1.setGeometry();
355       var vectorSource = new ol.source.Vector();
356       vectorSource.addFeature(newFeature1);
357       var layer = DefenseZoneLayer;
358       layer.setSource(vectorSource);
359 
360 
361     })
362 
363 
364   </script>
365 
366   <!-- <script src="scripts/homeMap.js"></script> -->
367 </body>
368 
369 </html>
View Code
复制代码

 

# ArcGIS API for JavaScript

01.arcgis api 加载gltf模型文件

  

复制代码
  1 <!DOCTYPE html>
  2 <html>
  3     <head>
  4       <meta charset="utf-8" />
  5       <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
  6       <!--
  7       ArcGIS API for JavaScript, https://js.arcgis.com
  8       For more information about the import-gltf sample, read the original sample description at developers.arcgis.com.
  9       https://developers.arcgis.com/ ... .html
 10       -->
 11       <title>Import glTF 3D Models - 4.13</title>
 12     
 13       <link rel="stylesheet" href="https://js.arcgis.com/4.19/esri/themes/light/main.css" />
 14          <script src="https://js.arcgis.com/4.19/"></script>
 15 
 16       <style>
 17         html,
 18         body,
 19         #viewDiv {
 20           padding: 0;
 21           margin: 0;
 22           height: 100%;
 23           width: 100%;
 24         }
 25       </style>
 26       <script>
 27         require([
 28           "esri/views/SceneView",
 29           "esri/Map",
 30           "esri/layers/TileLayer",
 31           "esri/layers/GraphicsLayer",
 32           "esri/Graphic",
 33           "esri/geometry/Point",
 34           "esri/geometry/Mesh",
 35           "esri/geometry/SpatialReference",
 36           "esri/widgets/Sketch/SketchViewModel"
 37         ], function(SceneView, Map, TileLayer, GraphicsLayer, Graphic, Point, Mesh, SpatialReference, SketchViewModel) {
 38           // load web scene from ArcGIS Online
 39           var map = new Map({
 40             basemap: "satellite"
 41           });
 42           var initialViewParams = {
 43             map: map,
 44             container: "viewDiv",
 45             zoom: 12, //当前缩放值
 46             center: [113.03, 23.03], //中心点位,
 47             qualityProfile: "high",
 48             highlightOptions: {
 49               fillOpacity: 0,
 50               color: [255, 0, 0, 0.8],
 51               haloOpacity: 0.8
 52             },
 53             camera: {
 54               position: [113.03, 23.03, 10000],
 55               tilt: 45,
 56               heading: 30
 57             }
 58           };
 59           var scenView = new SceneView(initialViewParams);
 60           const graphicsLayer = new GraphicsLayer();
 61         
 62           map.add(graphicsLayer);
 63     
 64           function createGltf(gltfUrl) {
 65             // geographic location where the origin of the model will be placed
 66             const location = new Point({
 67               x: 113.030446,
 68               y: 23.037887,
 69               z: 50
 70             });
 71             Mesh.createFromGLTF(location, gltfUrl)
 72               .then(function(geometry) {
 73                 console.log(geometry);
 74                 // add it to a graphic
 75                 const graphic = new Graphic({
 76                   geometry,
 77                   symbol: {
 78                     type: "mesh-3d", // autocasts as new MeshSymbol3D()
 79                     symbolLayers: [{
 80                       type: "fill", // autocasts as new FillSymbol3DLayer()
 81                       material: {
 82                         color: [255, 255, 255, 1]
 83                         //          colorMixMode: "tint"
 84                       }
 85                     }]
 86                   }
 87                 });
 88                 graphicsLayer.add(graphic);
 89               })
 90               .catch(console.error);
 91           }
 92           
 93           createGltf("bdyxhy.gltf")
 94         });
 95       </script>
 96     </head>
 97     
 98     <body>
 99     <div id="viewDiv">
100       
101     </div>
102     
103   </body>
104 
105 </html>
View Code
复制代码

 02.空间查询,属性查询  

属性查询:QueryTask,FindTask(只能属性。多个图层)

空间查询:IdentifyTask(多个图层),QueryTask(单个图层)

复制代码
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>查询</title>
    <link rel="stylesheet" href="https://js.arcgis.com/3.25/esri/css/esri.css">
    <script src="https://js.arcgis.com/3.25/"></script>
    <script src="../Scripts/jsapi_vsdoc12_v38.js"></script>
    <script src="../Scripts/jquery-1.7.1.js"></script>
    <style type="text/css">
        #map
        {
            width: 100%;
            height: 1000px;

        }
        #divShowResult
        {
            display:none;
            position: absolute;
            z-index:100;
            top:30px;
            right:30px
        }
    </style>

</head>
<body>
    <span>输入要查询的名称</span><input id="serach" type="text" name="name1" value=" " />
    <input type="button" name="name" id="attrSerach" value="属性查询 " />
    <input type="button" name="name" id="spaceSearch" value="空间查询 " />
    <input type="button" name="name" id="del" value="清除 " />
    <div id="map"></div>
    <div id="divShowResult"></div>
    <script type="text/javascript">
        require([
            "esri/map",
            "esri/layers/ArcGISDynamicMapServiceLayer",
            "esri/tasks/FindTask",
            "esri/tasks/FindParameters",
            "esri/tasks/IdentifyTask",
            "esri/tasks/IdentifyParameters",
            "esri/toolbars/draw",
            "esri/symbols/SimpleLineSymbol",
            "esri/symbols/SimpleFillSymbol",
            "esri/geometry/Extent",
            "esri/graphic",
            "dojo/on",

        ], function (Map, ArcGISDynamicMapServiceLayer, FindTask, FindParameters, IdentifyTask, IdentifyParameters,
            Draw, SimpleLineSymbol, SimpleFillSymbol, Extent, Graphic, on) {
            var map = new Map("map", {
                logo: false,
                center: [116.43228121152976, 40.20122178384614],

            });
            var serverUrl = "http://localhost:6080/arcgis/rest/services/Test/Qingdao/MapServer";
            var dyLayer = new ArcGISDynamicMapServiceLayer(serverUrl);
            map.addLayer(dyLayer);
            //绘图工具
            var draw = new Draw(map);            
            //属性查询
            function attrFinfd() {
                var findParameters = new FindParameters();
                findParameters.returnGeometry = true;
                findParameters.layerIds = [0, 1, 2, 3];
                findParameters.searchFields = ["name"];
                findParameters.searchText = $("#serach").val();
                findTask.execute(findParameters, showResult);
            };
            //查询工具
            var findTask = new FindTask(serverUrl)
            //属性查询渲染函数
            function showResult(result) {
                map.graphics.clear();
                //线符号
                var lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASH, new dojo.Color([0, 0, 255]), 3);
                //面符号
                var fillSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, lineSymbol);
                if (result.length == 0) {
                    alert("未查询到任何信息");
                    return;
                }
                else {
                    for (var i = 0; i < result.length; i++) {
                        //获得图形graphic
                        var graphic = result[i].feature;
                        console.log(graphic);
                        console.log(graphic.geometry.cache);
                        //console.log(graphic.geometry.cache._extent);
                        //赋予相应的符号
                        graphic.setSymbol(lineSymbol);
                        //将graphic添加到地图中,从而实现高亮效果
                        map.graphics.add(graphic);
                    }

                }

            }
            //属性查询
            $("#attrSerach").click(function () {
                if ($("#serach").val() == null) {
                    alert("请输入查询条件");
                    return;
                }
                
                attrFinfd();
                
            });
            //空间查询
            $("#spaceSearch").click(function () {
                draw.activate(esri.toolbars.Draw.POLYGON);
            });
            //绘图
            draw.on("draw-complete", function (resultDraw) {
                //得到绘图图形
                var geometry = resultDraw.geometry;
                //关闭绘图工具
                draw.deactivate();
                //执行空间查询
                identifyTask(geometry);
            });
            //清除
            $("#del").click(function () {

                $("#divShowResult").html = "";
                $("#divShowResult").hide();
                map.graphics.clear();
            });
            //空间查询
            function identifyTask(geometry) {
                //定义空间查询对象,注意他的参数是整个地图服务,而不是单个图层
                var identifyTask = new IdentifyTask("http://localhost:6080/arcgis/rest/services/Test/Qingdao/MapServer");
                //定义空间查询参数对象
                var params = new IdentifyParameters();
                //容差
                params.tolerance = 5;
                //是否返回几何信息
                params.returnGeometry = true;
                //空间查询的图层
                params.layerIds = [0,1,2,3];
                //空间查询的条件
                params.layerOption = IdentifyParameters.LAYER_OPTION_ALL;
                params.width = map.width;
                params.height = map.height;
                //空间查询的几何对象
                params.geometry = geometry;
                params.mapExtent = map.extent;
                //执行空间查询
                identifyTask.execute(params, showQueryResult);            
            }
            //空间查询展示
            function showQueryResult(idResults) {
                //创建线符号
                var lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASH, new dojo.Color([255, 0, 0]), 3);
                //创建面符号
                var fill = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, lineSymbol);
                if (idResults.length > 0) {
                    var htmls = "<table style=\"width: 100%\">";
                    htmls = htmls + "<tr bgcolor=\"#E0E0E0\"><td> 图层 </td><td> 名 称</td></tr>";
                    for (var i = 0; i < idResults.length; i++) {
                        var result = idResults[i];
                        //获得图形graphic
                        var graphic = result.feature;
                        //设置图形的符号
                        graphic.setSymbol(fill);
                        var namevalue = result.feature.attributes.Name;
                        if (i % 2 == 1) {
                            htmls = htmls + "<tr  bgcolor=\"#E0E0E0\"><td>" +
                            result.layerName + "</td><td>" + namevalue + "</td></tr>";
                        }
                        else {
                            htmls = htmls + "<tr><td>" + result.layerName + "</td><td>"
                            + namevalue + "</td></tr>";
                        }

                        map.graphics.add(graphic);
                    }
                    htmls = htmls + "</table>";
                    document.getElementById("divShowResult").innerHTML = htmls;
                    $("#divShowResult").show();
                }
                else {
                    document.getElementById("divShowResult").innerHTML = "";
                    $("#divShowResult").show();
                }
            }
        })
    </script>
</body>
</html>
View Code
复制代码

 03.编辑功能(4.18)

  popup里面加editor(地址是本地的,到sdk找)

  ArcGIS发布FeatureServer和在线编辑applyEdit

 

#Cesium

 01.Cesium隐藏地球

复制代码
1    // 隐藏地球
2             viewer.scene.skyBox.show = false;
3             viewer.scene.backgroundColor = Cesium.Color.WHITE;
4             viewer.scene.sun.show = false;
5             viewer.scene.moon.show = false;
6             viewer.scene.globe.show = false;
7             viewer.scene.skyAtmosphere.show = false;
View Code
复制代码

 

 

二.问题解决

1.Jquery事件绑定

jQuery提供了一个one()方法实现只绑定一次的事件

2.侧边栏动态产生的div,注册多个点击事件
3.滑动到预警会自动跳位置
4.overlay绑定值
复制代码
var htmls = '<div class="warnOverlay" data-name=" '+ dic_values['Name'] + '" onclick="showDevice(\'' + id + '\',' + isAssociateAlerm + ');"' + "style='width:27px;height:27px;'>" +
                                "<img src='@Url.Content("~/")Static/_3207/HomePage/Map/img/device_" + deviceClass + "_R.gif' style='width:27px;height:27px;max-width:100%;max-height:100%;cursor:pointer;'/>" +
                                "</div>";
                            warn_overlay.show(ol.proj.transform([x, y], 'EPSG:4326', 'EPSG:3857'), htmls);
                            allWarnings.push(warn_overlay);
View Code
复制代码
 5.HTML绑定值
复制代码
 1 //绑定值
 2 var htmls = '<div class="warnOverlay" data-name=" '+ dic_values['Name'] + '" onclick="showDevice(\'' + id + '\',' + isAssociateAlerm + ');"' + "style='width:27px;height:27px;'>" +
 3                                 "<img src='@Url.Content("~/")Static/_3207/HomePage/Map/img/device_" + deviceClass + "_R.gif' style='width:27px;height:27px;max-width:100%;max-height:100%;cursor:pointer;'/>" +
 4                                 "</div>";
 5 //取值
 6 var name= $(this).attr('data-name');
 7 
 8 //可参考以下代码
 9 //语法非常简单。所有在元素上以data-开头的属性为数据属性。比如说你有一篇文章,而你又想要存储一些不需要显示在浏览器上的额外信息。请使用data属性:
10 <article
11   id="electriccars"
12   data-columns="3"
13   data-index-number="12314"
14   data-parent="cars">
15 ...
16 </article>
17 //在外部使用JavaScript去访问这些属性的值同样非常简单。你可以使用getAttribute()配合它们完整的HTML名称去读取它们,但标准定义了一个更简单的方法:DOMStringMap你可以使用dataset读取到数据。
18 
19 为了使用dataset对象去获取到数据属性,需要获取属性名中data-之后的部分(要注意的是破折号连接的名称需要改写为骆驼拼写法(如"index-number"转换为"indexNumber"))。
20 var article = document.querySelector('#electriccars');
21  
22 article.dataset.columns // "3"
23 article.dataset.indexNumber // "12314"
24 article.dataset.parent // "cars"
View Code
复制代码

 三.巧妙的代码

  1.表达式组合

复制代码
 1 // limit visualization to southeast U.S. counties
 2         var defExp = [
 3           "STATE = 'LA'",
 4           "STATE = 'AL'",
 5           "STATE = 'AR'",
 6           "STATE = 'MS'",
 7           "STATE = 'TN'",
 8           "STATE = 'GA'",
 9           "STATE = 'FL'",
10           "STATE = 'SC'",
11           "STATE = 'NC'",
12           "STATE = 'VA'",
13           "STATE = 'KY'",
14           "STATE = 'WV'"
15         ];
16 defExp.join(" OR ") // only display counties from states in defExp
17     //输出:STATE = 'LA' OR STATE = 'AL' OR STATE = 'AR' OR STATE = 'MS' OR STATE = 'TN' OR STATE = 'GA' OR STATE = 'FL' OR STATE = 'SC' OR STATE = 'NC' OR STATE = 'VA' OR STATE = 'KY' OR STATE = 'WV'
View Code
复制代码

 

posted @   Youse的二分口粮地  阅读(419)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程
点击右上角即可分享
微信分享提示