openLayers.util.js 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  1. (function() {
  2. window.map = {};
  3. window.OL = {};
  4. window.icons = [];
  5. window.infoWindows = [];
  6. window.markerLayer = null;
  7. window.drawLayer = null;
  8. window.trackPlayLayer = null;
  9. window.Geocoder = {};
  10. window.LocalSearch = {};
  11. window.select = null;
  12. /**
  13. * OpenLayers操作地图
  14. */
  15. OL = {
  16. /**
  17. * 全局变量
  18. */
  19. CONSTANT : {
  20. CONTAINER : "map",
  21. CURRENT_MAP_TYPE : "openStreetMap",
  22. CURRENT_MAP_JIUPIAN : 0,
  23. DEFAULT_ZOOM : 2,
  24. MIN_ZOOM : 1,
  25. MAX_ZOOM : 20,
  26. DEFAULT_LAT : 0,
  27. DEFAULT_LNG : 0,
  28. BASEPATH : null
  29. },
  30. /**
  31. * 初始化普通地图
  32. */
  33. initCommonMap : function() {
  34. window.infoWindows = [];
  35. var view = this.getView();
  36. var interactions = ol.interaction.defaults().extend([
  37. new ol.interaction.DragRotateAndZoom()
  38. ]);
  39. map = new ol.Map({
  40. view : view,
  41. // layers : [ mapLayer ],
  42. target : 'map',
  43. interactions : interactions,
  44. loadTilesWhileAnimating : true,/* 在动画期间加载图块 */
  45. loadTilesWhileInteracting : true/* 在与地图交互时会加载图块 */
  46. });
  47. window.map = map;
  48. OL.event.addListener_singleclick();
  49. /*动态点扩散效果*/
  50. // var point_overlay = new ol.Overlay({
  51. // element: document.getElementById('css_animation'),
  52. // positioning: 'center-center',
  53. // //position: [9871995.0, 4344069.0],
  54. // stopEvent: false
  55. // });
  56. // map.addOverlay(point_overlay);
  57. // //point_overlay.setPosition(map.getView().getCenter());
  58. // //point_overlay.setPosition(point.getCoordinates());
  59. },
  60. /**
  61. * 初始化地图(含操作控件)
  62. */
  63. initOpenLayersMap : function() {
  64. OL.initCommonMap(); // 初始化普通地图
  65. // 添加控件
  66. OL.control.addAttributControl();
  67. OL.control.addScaleLineControl();
  68. OL.control.addFullScreenControl();
  69. OL.control.addThumbnailsControl();
  70. OL.control.addRotationControl();
  71. OL.control.addLayerSwitcherControl();
  72. // OL.tools.addDraw();
  73. // OL.addChangeView();//添加地图切换
  74. markerLayer = new ol.layer.Vector({
  75. source : new ol.source.Vector({
  76. features : []
  77. })
  78. });
  79. map.addLayer(markerLayer);//添加marker图层
  80. markerLayer.setVisible(true);
  81. },
  82. /**
  83. * 初始化地图(含拖拽文件到地图)
  84. */
  85. initHistoricalTrackMap : function() {
  86. OL.initOpenLayersMap(); // 初始化地图(含操作控件)
  87. var styleFunction = function(feature, resolution) {
  88. var featureStyleFunction = feature.getStyleFunction();
  89. if (featureStyleFunction) {
  90. return featureStyleFunction.call(feature, resolution);
  91. } else {
  92. return defaultStyle[feature.getGeometry().getType()];
  93. }
  94. };
  95. var dragAndDropInteraction = new ol.interaction.DragAndDrop({
  96. formatConstructors: [
  97. // ol.format.GPX,
  98. // ol.format.IGC,
  99. // ol.format.TopoJSON,
  100. ol.format.GeoJSON,
  101. ol.format.KML
  102. ]
  103. });
  104. dragAndDropInteraction.on('addfeatures', function(event) {
  105. var vectorSource = new ol.source.Vector({
  106. features: event.features
  107. });
  108. map.addLayer(new ol.layer.Image({
  109. source: new ol.source.ImageVector({
  110. source: vectorSource,
  111. style: styleFunction
  112. })
  113. }));
  114. map.getView().fit(vectorSource.getExtent(), map.getSize());
  115. });
  116. map.addInteraction(dragAndDropInteraction);
  117. },
  118. getView : function() {
  119. var view = new ol.View({
  120. center : ol.proj.transform([ this.CONSTANT.DEFAULT_LAT, this.CONSTANT.DEFAULT_LNG ], 'EPSG:4326', 'EPSG:3857'),
  121. // center : new ol.geom.Point([ this.CONSTANT.DEFAULT_LAT,this.CONSTANT.DEFAULT_LNG ]).transform('EPSG:4326', 'EPSG:3857').getCoordinates(),
  122. // center : [ 114.013351, 22.644093 ],
  123. zoom : this.CONSTANT.DEFAULT_ZOOM,
  124. minZoom: this.CONSTANT.MIN_ZOOM,
  125. maxZoom: this.CONSTANT.MAX_ZOOM
  126. });
  127. return view;
  128. },
  129. /**
  130. * 视野自适应
  131. */
  132. viewExtent : function(coordinates) {
  133. try{
  134. var extent = new ol.extent.boundingExtent(coordinates);
  135. map.getView().fit(extent, map.getSize());
  136. if(map.getView().getZoom()>18){
  137. map.getView().setZoom(16);
  138. }
  139. map.renderSync();
  140. }catch(err){
  141. console.log("Field of view adaptive Exception!");
  142. }
  143. },
  144. /**
  145. * 点越界处理
  146. */
  147. ifOutBoundsPantoCenter : function(point){
  148. var extent = map.getView().calculateExtent(map.getSize());
  149. alert(ol.extent.containsCoordinate(extent, point.getCoordinates()));
  150. // 不在extent之内则做相应的处理
  151. // if(!ol.extent.containsCoordinate(extent, point.getCoordinates())){
  152. map.getView().fit(point, map.getSize());
  153. // if(map.getView().getZoom()<12){
  154. map.getView().setZoom(16);
  155. // }
  156. // map.getView().setCenter(point.getCoordinates());
  157. //map.render();
  158. map.renderSync();
  159. // }
  160. },
  161. /**
  162. * 设置地图中心点
  163. */
  164. setCenterAndZoom : function(point,zoom) {
  165. map.getView().setCenter(point.getCoordinates());
  166. if (zoom != null) {
  167. map.getView().setZoom(zoom);
  168. }
  169. map.render();
  170. },
  171. /**
  172. * 创建一个经纬度(坐标点)
  173. */
  174. getPoint : function(lat, lng) {
  175. // return new ol.geom.Point([ lat, lng ]);
  176. return new ol.geom.Point([ lng, lat ]).transform('EPSG:4326', 'EPSG:3857');
  177. },
  178. /**
  179. * 创建标记
  180. */
  181. createIcon : function(iconPath,scaleSize) {
  182. var icon = new ol.style.Style({
  183. image : new ol.style.Icon({
  184. src : iconPath,
  185. //size: [36, 36],
  186. //opacity: 0.75,//透明度
  187. scale: scaleSize?scaleSize:1,//缩放比例尺
  188. anchor : [ 0.5, 0.95 ]//坐标偏移量
  189. })
  190. });
  191. return icon;
  192. },
  193. /**
  194. * 查询标记图标
  195. */
  196. findIcon : function(id) {
  197. for (var i = 0; i < icons.length; i++) {
  198. var icon = icons[i];
  199. if (icon.id == id) {
  200. return icon;
  201. }
  202. }
  203. return null;
  204. },
  205. /**
  206. * 获取一个标记图标
  207. */
  208. getIcon : function(id,iconPath,scale) {
  209. var icon = OL.findIcon(id);
  210. if (icon == null) {
  211. icon = OL.createIcon(iconPath,scale);
  212. icon.id = id;
  213. icons.push(icon);
  214. }
  215. return icon;
  216. },
  217. /**
  218. * 查找标记
  219. */
  220. findMarker : function(id) {
  221. if(markerLayer){
  222. var marker = markerLayer.getSource().getFeatureById(id);
  223. return marker;
  224. }
  225. },
  226. /**
  227. * 获取一个标记
  228. */
  229. getMarker : function(id, point, iconStyle) {
  230. var marker = OL.findMarker(id);
  231. if (marker != null) {
  232. if (point != null) {
  233. marker.setGeometry(point);
  234. }
  235. if (iconStyle != null) {
  236. marker.setStyle(iconStyle);
  237. }
  238. }else{
  239. marker = OL.createMarker(id, point, iconStyle);
  240. }
  241. // OL.viewExtent([point.getCoordinates()]);//视野自适应
  242. return marker;
  243. },
  244. /**
  245. * 创建Marker标注
  246. */
  247. createMarker : function(id, point, iconStyle) {
  248. var marker = new ol.Feature({
  249. geometry : point,
  250. });
  251. marker.setId(id);
  252. marker.setStyle(iconStyle);
  253. if (typeof markerLayer !== 'undefined') {
  254. markerLayer.getSource().addFeature(marker);
  255. }
  256. return marker;
  257. },
  258. /**
  259. * 设置标记
  260. */
  261. setMarker : function(id, point, iconStyle) {
  262. var marker = OL.findMarker(id);
  263. if (marker != null) {
  264. if (point != null) {
  265. marker.setGeometry(point);
  266. }
  267. if (iconStyle != null) {
  268. marker.setStyle(iconStyle);
  269. }
  270. }
  271. // OL.viewExtent([point.getCoordinates()]);//视野自适应
  272. return marker;
  273. },
  274. /**
  275. * 移除一个标记
  276. */
  277. removeMarke : function(id) {
  278. var marker = OL.findMarker(id);
  279. if (marker != null) {
  280. markerLayer.getSource().removeFeature(marker);
  281. }
  282. },
  283. /**
  284. * 移除所有标记
  285. */
  286. removeAllMarke : function() {
  287. markerLayer.getSource().clear();
  288. },
  289. findCircle : function(id) {
  290. if(markerLayer){
  291. var circle = markerLayer.getSource().getFeatureById(id);
  292. return circle;
  293. }
  294. },
  295. getCircle : function(id, point, radius) {
  296. var circle = OL.findCircle(id);
  297. if (circle != null) {
  298. if (point != null) {
  299. circle.getGeometry().setCenter(point.getCoordinates());
  300. }
  301. if (radius != null) {
  302. circle.getGeometry().setRadius(radius);
  303. }
  304. }else{
  305. circle = OL.createCircle(id, point, radius);
  306. }
  307. return circle;
  308. },
  309. isShowCircle : function(id, isShow) {
  310. var circle = OL.findCircle(id);
  311. if (isShow) {
  312. circle.setStyle(OL.circleStyle());
  313. }else{
  314. circle.setStyle(new ol.style.Style());
  315. }
  316. },
  317. setCircle : function(id, point, radius) {
  318. var circle = OL.findCircle(id);
  319. if (circle != null) {
  320. if (point != null) {
  321. circle.getGeometry().setCenter(point.getCoordinates());
  322. }
  323. if (radius != null) {
  324. circle.getGeometry().setRadius(radius);
  325. }
  326. }
  327. return circle;
  328. },
  329. circleStyle : function() {
  330. var circleStyle = new ol.style.Style({
  331. image: new ol.style.Circle(),
  332. fill: new ol.style.Fill({//填充色
  333. color: 'rgba(91, 192, 222, 0.2)'
  334. }),
  335. stroke: new ol.style.Stroke({//边线颜色
  336. color: '#5BC0DE',
  337. width: 1
  338. })
  339. });
  340. return circleStyle;
  341. },
  342. /**
  343. * 创建圆
  344. */
  345. createCircle : function(id, point, radius) {
  346. var circle = new ol.Feature({//创建一个圆
  347. geometry: new ol.geom.Circle(point.getCoordinates(), radius)
  348. });
  349. circle.setId(id);
  350. circle.setStyle(OL.circleStyle());
  351. if (typeof markerLayer !== 'undefined') {
  352. markerLayer.getSource().addFeature(circle);
  353. }
  354. return circle;
  355. },
  356. removeCircle : function(id) {
  357. var circle = OL.findCircle(id);
  358. if (circle != null) {
  359. markerLayer.getSource().removeFeature(circle);
  360. }
  361. },
  362. /**
  363. * 获取一个信息窗体
  364. */
  365. getInfoWindow : function(id, point, htmlContent) {
  366. var infoWindow = OL.findInfoWindow(id);
  367. if (infoWindow == null) {
  368. infoWindow = OL.createInfoWindow(id, point, htmlContent);
  369. infoWindow.id = id;
  370. infoWindows.push(infoWindow);
  371. }else{
  372. infoWindow = OL.setInfoWindow(id, point, htmlContent);
  373. }
  374. return infoWindow;
  375. },
  376. /**
  377. * 设置信息窗体
  378. */
  379. setInfoWindow : function(id, point, htmlContent) {
  380. var infoWindow = OL.findInfoWindow(id);
  381. if (infoWindow != null) {
  382. if (point != null) {
  383. infoWindow.setPosition(point.getCoordinates());
  384. }
  385. if (htmlContent != null) {
  386. var content = document.getElementById('popup-content-' + id);
  387. if(content != undefined){
  388. content.innerHTML = htmlContent;
  389. }
  390. }
  391. }
  392. return infoWindow;
  393. },
  394. /**
  395. * 查询信息窗体
  396. */
  397. findInfoWindow : function(id) {
  398. for (var i = 0; i < infoWindows.length; i++) {
  399. var infoWindow = infoWindows[i];
  400. if (infoWindow.id == id) {
  401. return infoWindow;
  402. }
  403. }
  404. return null;
  405. },
  406. /**
  407. * 创建信息窗体
  408. */
  409. createInfoWindow : function(id, point, htmlContent) {
  410. var html = '<div id="popup-'+id+'" class="ol-popup" style="display:none;">';
  411. html += '<a href="javascript:void(0)" id="popup-closer-'+id+'" class="ol-popup-closer"></a>';
  412. html += '<div id="popup-content-'+id+'" style="width: 260px;">'+htmlContent+'</div>';
  413. html += '</div>';
  414. var viewport = map.getViewport();
  415. $(viewport).append(html);
  416. $("#popup-closer-" + id).click(function(even){
  417. $("#popup-" + id).hide();
  418. // $("#id").show();
  419. });
  420. var infoWindow = new ol.Overlay({
  421. element : document.getElementById('popup-' + id),
  422. autoPan: true,
  423. autoPanAnimation : {
  424. duration : 250
  425. }
  426. });
  427. map.addOverlay(infoWindow);
  428. infoWindow.setPosition(point.getCoordinates());
  429. return infoWindow;
  430. },
  431. /**
  432. * 移除信息窗体
  433. */
  434. removeInfoWindow : function(id) {
  435. for (var i = 0; i < infoWindows.length; i++) {
  436. var infoWindow = infoWindows[i];
  437. if (infoWindow.id == id) {
  438. // infoWindows[i].setVisible(false);
  439. // infoWindows[i].setMap(map);
  440. $("#popup-" + id).hide();
  441. }
  442. }
  443. },
  444. /**
  445. * 移除所有信息窗体
  446. */
  447. removeAllInfoWindow : function(isClear) {
  448. for (var i = 0; i < infoWindows.length; i++) {
  449. // infoWindows[i].setVisible(false);
  450. // infoWindows[i].setMap(map);
  451. $("#popup-" + infoWindows[i].id).hide();
  452. }
  453. if (isClear) {
  454. infoWindows = [];
  455. }
  456. }
  457. };
  458. /**
  459. * 操作工具
  460. */
  461. OL.tools = {
  462. /**
  463. * 视野自适应
  464. */
  465. fit : function(extent) {
  466. map.getView().fit(extent, map.getSize());
  467. },
  468. fit_geometry : function(geometry) {
  469. map.getView().fitGeometry(geometry, map.getSize());
  470. },
  471. fit_extent : function(extent) {
  472. map.getView().fitExtent(extent, map.getSize());
  473. },
  474. fit_layer : function(layer) {// 合适比例缩放居中
  475. try{
  476. var extent = layer.getSource().getExtent();
  477. // map.getView().fit(extent, map.getSize());
  478. map.getView().fitExtent(extent, map.getSize());
  479. map.renderSync();
  480. }catch(err){
  481. console.log("Field of view adaptive Exception!");
  482. }
  483. },
  484. /**
  485. * 绘制过程
  486. */
  487. addDrawInteraction : function(type) {
  488. if (drawVector != null) {
  489. map.removeLayer(drawVector);
  490. }
  491. if (draw != null) {
  492. map.removeInteraction(draw);
  493. }
  494. // 绘制工具
  495. draw = new ol.interaction.Draw({
  496. source : drawSource,
  497. type : type
  498. });
  499. map.addLayer(drawVector);
  500. map.addInteraction(draw);
  501. },
  502. /**
  503. * 测量两点的距离
  504. */
  505. distance : function(points) {
  506. var wgs84Sphere = new ol.Sphere(6378137);
  507. var sourceProj = map.getView().getProjection();
  508. var length = 0;
  509. for (var i = 0, ii = gis.length - 1; i < ii; ++i) {
  510. var c1 = ol.proj.transform(points[i], sourceProj, 'EPSG:4326');
  511. var c2 = ol.proj.transform(points[i + 1], sourceProj,
  512. 'EPSG:4326');
  513. length += wgs84Sphere.haversineDistance(c1, c2);
  514. }
  515. var output = 0;
  516. if (length > 100) {
  517. output = (Math.round(length / 1000 * 100) / 100) + ' ' + 'km';
  518. } else {
  519. output = (Math.round(length * 100) / 100) + ' ' + 'm';
  520. }
  521. // return map.getDistance(pointA, pointB); // 获取两点距离
  522. },
  523. /**
  524. * 轨迹回放
  525. */
  526. trackPlay : function(points, iconPath) {
  527. if(trackPlayLayer != undefined){
  528. trackPlayLayer.getSource().clear();
  529. }
  530. var lineString = new ol.geom.LineString(points,'XY').transform('EPSG:4326', 'EPSG:3857');
  531. for(var i=0;i<lineString.length;i++){
  532. lineString[i].forEachSegment(function(start, end) {
  533. var dx = end[0] - start[0];
  534. var dy = end[1] - start[1];
  535. var rotation = Math.atan2(dy, dx);
  536. // arrows
  537. styles.push(new Style({
  538. geometry: new Point(end),
  539. image: new Icon({
  540. src: 'https://openlayers.org/en/latest/examples/data/arrow.png',
  541. anchor: [0.75, 0.5],
  542. rotateWithView: true,
  543. rotation: -rotation
  544. })
  545. }));
  546. });
  547. }
  548. points = lineString.getCoordinates();
  549. var routeLength = points.length;
  550. var styles = {
  551. 'route' : new ol.style.Style({
  552. stroke : new ol.style.Stroke({
  553. width : 6,
  554. color : [ 0, 255, 0, 0.8 ]
  555. })
  556. }),
  557. 'startIcon' : new ol.style.Style({
  558. image:new ol.style.Circle({
  559. radius:7,
  560. snapToPixel:false,
  561. fill:new ol.style.Fill({ color:'#30C0FF'}),
  562. stroke:new ol.style.Stroke({
  563. color:'white',
  564. width:1
  565. })
  566. })
  567. }),
  568. 'endIcon' : new ol.style.Style({
  569. image:new ol.style.Circle({
  570. radius:7,
  571. snapToPixel:false,
  572. fill:new ol.style.Fill({ color:'red'}),
  573. stroke:new ol.style.Stroke({
  574. color:'white',
  575. width:1
  576. })
  577. })
  578. }),
  579. 'moveIcon' : new ol.style.Style({
  580. image : new ol.style.Icon({
  581. scale: 0.6,
  582. anchor : [ 0.5, 1 ],
  583. src : iconPath
  584. })
  585. })
  586. };
  587. // 轨迹图层
  588. var routeFeature = new ol.Feature({
  589. type : 'route',
  590. geometry : lineString
  591. });
  592. var startMarker = new ol.Feature({
  593. type : 'startIcon',
  594. geometry : new ol.geom.Point(points[0])
  595. });
  596. var endMarker = new ol.Feature({
  597. type : 'endIcon',
  598. geometry : new ol.geom.Point(points[routeLength - 1])
  599. });
  600. var moveMarker = new ol.Feature({
  601. type : 'moveIcon',
  602. geometry : new ol.geom.Point(points[0])
  603. });
  604. var playing = false;
  605. var animating = false;
  606. var speed, index, pauseM, originTime, pauseTime;
  607. // var speedInput = document.getElementById('speed');
  608. var searchButton = document.getElementById('search');
  609. var playOrpauseButton = document.getElementById('playOrpause');
  610. trackPlayLayer = new ol.layer.Vector({
  611. source : new ol.source.Vector({
  612. features : [routeFeature, startMarker, endMarker, moveMarker]
  613. // features : [routeFeature, moveMarker]
  614. }),
  615. style : function(feature) {
  616. if (animating && feature.get('type') === 'moveIcon') {
  617. return null;
  618. }
  619. return styles[feature.get('type')];
  620. }
  621. });
  622. map.addLayer(trackPlayLayer);
  623. OL.viewExtent(points);
  624. $("#spinner").change(function() {
  625. speed = speedSpinner.spinner("value");
  626. })
  627. var moveFeature = function(event) {
  628. var vectorContext = event.vectorContext;
  629. var frameState = event.frameState;
  630. if (animating) {
  631. var elapsedTime = frameState.time - originTime - pauseM;
  632. if(playing) {
  633. index = Math.round(speed * elapsedTime / 10000);
  634. }
  635. if (index >= routeLength) {
  636. alert("Play finished!");
  637. stopAnimation(true);
  638. return;
  639. }
  640. document.getElementById("historicalTrackScroll").scrollTop = (index-1)*41;
  641. if(index>0){
  642. $("#historyData-"+index).removeAttr("style");
  643. }
  644. $("#historyData-"+(index+1)).css({ "background-color": "#6EABFF" });
  645. var currentPoint = new ol.geom.Point(points[index]);
  646. var feature = new ol.Feature(currentPoint);
  647. //OL.ifOutBoundsPantoCenter(currentPoint);
  648. vectorContext.drawFeature(feature, styles.moveIcon);
  649. }
  650. map.render();
  651. };
  652. playOrpauseButton.onclick = function() {
  653. if (animating) {
  654. if (playing) {
  655. playing = false;
  656. pauseTime = new Date().getTime();
  657. } else {
  658. playing = true;
  659. pauseM += new Date().getTime() - pauseTime;
  660. }
  661. }else{
  662. searchButton.disabled=true;//按钮禁用
  663. animating = true;
  664. playing = true;
  665. pauseM = 0;
  666. originTime = new Date().getTime();
  667. speed = speedSpinner.spinner("value");
  668. moveMarker.setStyle(null);
  669. map.on('postcompose', moveFeature);
  670. map.render();
  671. }
  672. }
  673. function stopAnimation(ended) {
  674. searchButton.disabled=false;
  675. animating = false;
  676. playing = false;
  677. var coord = ended ? points[routeLength - 1] : points[0];
  678. (moveMarker.getGeometry()).setCoordinates(coord);
  679. map.un('postcompose', moveFeature);
  680. }
  681. },
  682. /**
  683. * 添加/修改/拖动 点、线、多边形、圆 drawType:Point,LineString,Polygon,Circle
  684. */
  685. addDraw : function(o_range,callback) {
  686. if(drawLayer != null){//清理缓存
  687. map.removeInteraction(select);
  688. //map.removeLayer(drawLayer);
  689. //map.renderSync();
  690. drawLayer.getSource().clear();
  691. drawLayer.getSource().refresh();//刷新
  692. //drawLayer.refresh({ force: true, active: true });//强制刷新
  693. }
  694. var o_circle = document.getElementById('Circle');
  695. var o_radius = document.getElementById('Radius');
  696. var o_polygon = document.getElementById('Polygon');
  697. var o_modify = document.getElementById('Modify');
  698. var o_draw = document.getElementById('Draw');
  699. var o_clear = document.getElementById('Clear');
  700. var source = new ol.source.Vector({
  701. wrapX : false
  702. });
  703. var drawFeature = null;
  704. //{"type":"Circle","latlng":[{"lng":0.0,"lat":0.0}],"radius":1000}
  705. if(parent.isJSON(o_range)){
  706. var rangeObj = JSON.parse(o_range);
  707. if (rangeObj.type == "Polygon") {
  708. var points = [];
  709. var latlng = rangeObj.latlng;
  710. for (var i = 0; i < latlng.length; i++) {
  711. points[i] = [];
  712. points[i][0] = latlng[i].lng;
  713. points[i][1] = latlng[i].lat;
  714. }
  715. var polygon = new ol.geom.Polygon([ points ]);
  716. polygon = polygon.clone().transform('EPSG:4326', 'EPSG:3857');
  717. drawFeature = new ol.Feature(polygon);
  718. } else if (rangeObj.type == "Circle") {
  719. try {
  720. var latlng = rangeObj.latlng;
  721. var radius = rangeObj.radius;
  722. var point = new ol.geom.Point([ latlng[0].lng,
  723. latlng[0].lat ]).transform('EPSG:4326', 'EPSG:3857');
  724. o_radius.value = radius;
  725. var drawCircle = new ol.geom.Circle(point.getCoordinates(), radius);
  726. drawFeature = new ol.Feature(drawCircle);
  727. } catch(err) {
  728. drawFeature = new ol.Feature(null);
  729. }
  730. }
  731. source.addFeature(drawFeature);
  732. }
  733. drawLayer = new ol.layer.Vector({
  734. source : source,
  735. style : new ol.style.Style({
  736. fill : new ol.style.Fill({
  737. color : 'rgba(255, 255, 255, 0.2)'
  738. }),
  739. stroke : new ol.style.Stroke({
  740. color : '#ff00ff',
  741. width : 2
  742. }),
  743. image : new ol.style.Circle({
  744. radius : 7,
  745. fill : new ol.style.Fill({
  746. color : '#ffcc33'
  747. })
  748. })
  749. })
  750. });
  751. map.addLayer(drawLayer);
  752. OL.tools.fit_layer(drawLayer);
  753. var draw, modify, drag;
  754. draw = new ol.interaction.Draw({
  755. source : source,
  756. type : ('none')
  757. });
  758. select = new ol.interaction.Select({
  759. condition : ol.events.condition.click,
  760. wrapX : false
  761. });
  762. modify = new ol.interaction.Modify({
  763. //condition: ol.events.condition.pointerMove,//鼠标移到featur上起作用
  764. features : select.getFeatures(),
  765. deleteCondition : function(event) {
  766. return ol.events.condition.shiftKeyOnly(event)
  767. && ol.events.condition.singleClick(event);
  768. }
  769. });
  770. drag = new ol.interaction.Translate({
  771. features : select.getFeatures(),
  772. cursor_ : 'pointer'
  773. });
  774. map.addInteraction(draw);
  775. map.addInteraction(select);
  776. map.addInteraction(modify);
  777. map.addInteraction(drag);
  778. draw.setActive(false);
  779. select.setActive(false);
  780. modify.setActive(false);
  781. drag.setActive(false);
  782. select.on('select', function(evt) {
  783. var selected = evt.selected;
  784. });
  785. modify.on('modifyend', function(evt) {
  786. evt.features.forEach(function(feature) {
  787. saveLatLngs(feature);
  788. });
  789. });
  790. drag.on('translateend', function(evt) {
  791. evt.features.forEach(function(feature) {
  792. saveLatLngs(feature);
  793. });
  794. });
  795. function saveLatLngs(feature) {
  796. var range = {};
  797. var latlng = [];
  798. var geometry = feature.getGeometry();
  799. var geometryType = geometry.getType();
  800. range.type = geometryType;
  801. if (geometryType == "Polygon") {
  802. var coordinates = geometry.getCoordinates()[0];
  803. for (var i = 0; i < coordinates.length; i++) {
  804. var coordinate = ol.proj.transform(coordinates[i],
  805. "EPSG:3857", "EPSG:4326");
  806. coordinate = ol.coordinate.format(coordinate, '{x},{y}', 6);
  807. var coo = coordinate.split(',');
  808. var point = {};
  809. point.lng = parseFloat(coo[0]);
  810. point.lat = parseFloat(coo[1]);
  811. latlng[i] = point;
  812. }
  813. // callback(points.substring(0, points.length - 1));
  814. } else if (geometryType == "Circle") {
  815. o_radius.value = Math.round(geometry.getRadius());
  816. var center = ol.proj.transform(geometry.getCenter(), "EPSG:3857", "EPSG:4326");
  817. center = ol.coordinate.format(center, '{x},{y}', 6);
  818. //callback("Circle|" + latlng + ";" + Math.round(geometry.getRadius()));
  819. var coo = center.split(',');
  820. var point = {};
  821. point.lng = parseFloat(coo[0]);
  822. point.lat = parseFloat(coo[1]);
  823. latlng[0] = point;
  824. range.radius = Math.round(geometry.getRadius());
  825. }
  826. range.latlng = latlng;
  827. callback(JSON.stringify(range));
  828. }
  829. o_circle.onclick = function() {
  830. draw.setActive(false);
  831. select.setActive(false);
  832. modify.setActive(false);
  833. drag.setActive(false);
  834. draw = new ol.interaction.Draw({
  835. source : source,
  836. type : 'Circle'
  837. });
  838. map.addInteraction(draw);
  839. draw.on('drawstart', function(evt) {
  840. clear();
  841. });
  842. draw.on('drawend', function(evt) {
  843. //circleRadius.spinner("value", parseInt(evt.feature.getGeometry().getRadius()));
  844. o_radius.value = parseInt(evt.feature.getGeometry().getRadius());
  845. saveLatLngs(evt.feature);
  846. draw.setActive(false);
  847. select.setActive(true);
  848. drag.setActive(true);
  849. });
  850. }
  851. $("#spinner").change(function() {
  852. var features = select.getFeatures().getArray();
  853. for (var i = 0; i < features.length; i++) {
  854. var geometry = features[i].getGeometry();
  855. var geometryType = geometry.getType();
  856. if (geometryType == "Circle") {
  857. var range = {};
  858. var latlng = [];
  859. range.type = "Circle";
  860. //geometry.setRadius(circleRadius.spinner("value"));
  861. geometry.setRadius(o_radius.value);
  862. range.radius = Math.round(geometry.getRadius());
  863. var center = ol.proj.transform(geometry.getCenter(),
  864. "EPSG:3857", "EPSG:4326");
  865. center = ol.coordinate.format(center, '{x},{y}', 6);
  866. var coo = center.split(',');
  867. var point = {};
  868. point.lng = parseFloat(coo[0]);
  869. point.lat = parseFloat(coo[1]);
  870. latlng[0] = point;
  871. range.latlng = latlng;
  872. callback(JSON.stringify(range));
  873. }
  874. }
  875. });
  876. o_polygon.onclick = function() {
  877. draw.setActive(false);
  878. select.setActive(false);
  879. modify.setActive(false);
  880. drag.setActive(false);
  881. draw = new ol.interaction.Draw({
  882. source : source,
  883. type : 'Polygon',
  884. maxPoints: 8
  885. });
  886. map.addInteraction(draw);
  887. draw.on('drawstart', function(evt) {
  888. clear();
  889. });
  890. draw.on('drawend', function(evt) {
  891. saveLatLngs(evt.feature);
  892. draw.setActive(false);
  893. select.setActive(true);
  894. modify.setActive(true);
  895. });
  896. }
  897. o_modify.onclick = function() {
  898. draw.setActive(false);
  899. drag.setActive(false);
  900. select.setActive(true);
  901. modify.setActive(true);
  902. }
  903. o_draw.onclick = function() {
  904. draw.setActive(false);
  905. modify.setActive(false);
  906. select.setActive(true);
  907. drag.setActive(true);
  908. }
  909. o_clear.onclick = function() {
  910. clear();
  911. }
  912. function clear() {
  913. drawLayer.getSource().clear();
  914. if (select) {
  915. select.getFeatures().clear();
  916. }
  917. //o_range.innerHTML = "";
  918. callback("");
  919. }
  920. },
  921. /**
  922. * 根据用户覆盖物的标识属性显示覆盖物
  923. */
  924. showOverlay : function(properties, value) {
  925. var overlay = this.getOverlayByNodeId(properties, value);
  926. overlay.show();
  927. },
  928. /**
  929. * 根据用户覆盖物的标识属性隐藏覆盖物
  930. */
  931. hideOverlay : function(properties, value) {
  932. var overlay = this.getOverlayByNodeId(properties, value);
  933. overlay.hide();
  934. },
  935. /**
  936. * 根据用户覆盖物的标识属性移除覆盖物
  937. */
  938. removeOverlay : function(properties, value) {
  939. var overlay = this.getOverlayByNodeId(properties, value);
  940. if (overlay)
  941. map.removeOverlay(overlay);
  942. },
  943. /**
  944. * 删除地图上所有覆盖物
  945. */
  946. removeAllOverlays : function() {
  947. map.clearOverlays();
  948. }
  949. // ,
  950. // asyncLoaded : function(url, callBack) {/* url为js的链接,callBack为回调函数 */
  951. // var script = document.createElement('script');
  952. // script.type = 'text/javascript';
  953. // /*
  954. // * if else 这几句话必须要写到这位置处,不能放最后,因为if中js加载中script.readyState存在好几种状态,
  955. // * 只有状态改变‘readystatechange’事件才会触发,但现在浏览器加载速度很快,当解析到该事件时JS有可能以加载完,
  956. // * 所以事件根本不会触发,所以要写到前面
  957. // */
  958. // if (script.readystate) {// 兼容IE
  959. // script.onreadystatechange = function() {// 状态改变事件才触发
  960. // if (script.readyState == 'loaded'
  961. // || script.readyState == 'complete') {
  962. // callBack();
  963. // script.onreadystatechange = null;
  964. // }
  965. // }
  966. // } else { //Others: Firefox, Safari, Chrome, and Opera
  967. // script.onload = function(e) {
  968. // callBack();
  969. // }
  970. // }
  971. // script.src = url;
  972. // document.body.appendChild(script);
  973. // }
  974. };
  975. /**
  976. * 探索处理
  977. */
  978. OL.search = {
  979. /**
  980. * 本地探索(含自动提示)
  981. */
  982. localSearch : function() {
  983. }
  984. };
  985. /**
  986. * OpenLayers控件
  987. */
  988. OL.control = {
  989. /**
  990. * 添加属性控件
  991. */
  992. addAttributControl : function() {
  993. map.addControl(new ol.control.Attribution());
  994. },
  995. /**
  996. * 添加鼠标定位控件
  997. */
  998. addMousePositionControl : function() {
  999. map.addControl(new ol.control.MousePosition({
  1000. undefinedHTML: 'outside',
  1001. projection: 'EPSG:4326',
  1002. coordinateFormat: function(coordinate) {
  1003. return ol.coordinate.format(coordinate, '{x}, {y}', 6);
  1004. }
  1005. })
  1006. );
  1007. },
  1008. /**
  1009. * 添加缩略图控件
  1010. */
  1011. addThumbnailsControl : function() {
  1012. map.addControl(new ol.control.OverviewMap({
  1013. // collapsed : false
  1014. }));
  1015. },
  1016. /**
  1017. * 添加旋转控件
  1018. */
  1019. addRotationControl : function() {
  1020. map.addControl(new ol.control.Rotate({
  1021. autoHide : false
  1022. }));
  1023. },
  1024. /**
  1025. * 添加比例尺控件
  1026. */
  1027. addScaleLineControl : function() {
  1028. map.addControl(new ol.control.ScaleLine());
  1029. },
  1030. /**
  1031. * 添加缩放控件
  1032. */
  1033. addZoomControl : function() {
  1034. map.addControl(new ol.control.Zoom());
  1035. },
  1036. /**
  1037. * 添加缩放滑动控件
  1038. */
  1039. addZoomSliderControl : function() {
  1040. map.addControl(new ol.control.ZoomSlider());
  1041. },
  1042. /**
  1043. * 添加缩放到当前视图滑动控件
  1044. */
  1045. addZoomToExtentControl : function() {
  1046. map.addControl(new ol.control.ZoomToExtent());
  1047. },
  1048. /**
  1049. * 添加全屏控件
  1050. */
  1051. addFullScreenControl : function() {
  1052. map.addControl(new ol.control.FullScreen());
  1053. },
  1054. /**
  1055. * 拖拽文件到地图,支持的格式包括 GeoJSON, GML, KML, GPX, OSMXML, TopoJSON 和 IGC
  1056. */
  1057. addDragAndDropControl : function() {
  1058. // var dragAndDropInteraction = new ol.interaction.DragAndDrop({
  1059. // formatConstructors: [
  1060. // ol.format.GeoJSON,
  1061. // ol.format.KML
  1062. // ]
  1063. // });
  1064. // var interactions = ol.interaction.defaults().extend([
  1065. // new ol.interaction.DragRotateAndZoom(),
  1066. // dragAndDropInteraction
  1067. // ]);
  1068. // dragAndDropInteraction.on('addfeatures', function(event){
  1069. // alert("989898");
  1070. // });
  1071. },
  1072. addLayerSwitcherControl : function() {
  1073. map.addControl(new ol.control.LayerSwitcher());
  1074. }
  1075. };
  1076. /**
  1077. * 地图事件
  1078. */
  1079. OL.event = {
  1080. addListener_singleclick : function() {// 响应单击事件
  1081. window.map.on("click", function(e) {
  1082. var feature = window.map.forEachFeatureAtPixel(e.pixel, function(
  1083. feature, layer) {
  1084. return feature;
  1085. });
  1086. if (feature) {
  1087. // alert("888=="+feature.getId()+"=="+feature.getGeometry());
  1088. var point = feature.getGeometry();
  1089. // OL.setInfoWindow(feature.get('id'),point,htmlContent);
  1090. $("#popup-" + feature.getId()).show();
  1091. }
  1092. });
  1093. },
  1094. addListener_click : function(mapObject, callback) {// 响应点击事件
  1095. var listener = mapObject.on('click', function(event) {
  1096. callback();
  1097. })
  1098. return listener;
  1099. },
  1100. addListener_dblclick : function(mapObject, callback) {// 响应双击事件
  1101. var listener = mapObject.on('dblclick', function(event) {
  1102. callback();
  1103. })
  1104. return listener;
  1105. },
  1106. addListener_dmouseup : function(mapObject, callback) {// 鼠标按上
  1107. mapObject.on('mouseup', function(event) {
  1108. callback();
  1109. });
  1110. },
  1111. addListener_mousedown : function(mapObject, callback) {// 鼠标按下
  1112. mapObject.on('mousedown', function(event) {
  1113. callback();
  1114. });
  1115. }
  1116. };
  1117. })();