UNPKG

les-openlayers

Version:

//its、openlayers、its openlayers二次封装,一个入口API 接入各种地图

1,619 lines (1,600 loc) 61.4 kB
import ol from 'openlayers' import $ from 'jquery' import "openlayers/css/ol.css" import "./css/its-openlayer.css" class Map { // 构造地图对象 constructor(options, id) { this.paras = $.extend({ projection: 'EPSG:4326', center: [118.81260, 32.06187], zoom: 10, minZoom: 10, maxZoom: 18, textZoom: 14, id: id, target: id, status: false, url: 'https://services.arcgisonline.com/arcgis/rest/services/ESRI_Imagery_World_2D/MapServer', logo: '', popupId: (new Date()).getTime() + parseInt(Math.random() * 1000), href: '', }, options); this.layer = {}; this.group = {}; this.init(this.paras); } init(options) { var self = this; $('#' + this.paras['target']).addClass('grab'); this.map = new ol.Map({ interactions: ol.interaction.defaults({ doubleClickZoom: false // 双击缩放是否触发 }), controls: ol.control.defaults().extend([ new ol.control.OverviewMap({ view: new ol.View({ projection: 'EPSG:4326' }) }), // new ol.control.ScaleLine({ // //设置度量单位为米 // units: 'metric', // target: 'scalebar', // className: 'ol-scale-line' // }) ]), target: options.target, view: new ol.View(options), loadTilesWhileAnimating: true, logo: { src: options.logo, href: options.href } }); // //添加地图图层(初始化三个图层) this.addLayer(options, options.id); this.addVector({ zIndex: 12, }, 'defaultLayer'); this.addVector({ zIndex: 11, lineDash: [10, 10] }, 'defaultDraw'); this.addOverlay('<div></div>', { zIndex: 3000, offset: [0, -10], autoPan: true, lngLat: undefined, id: 'defaultPopup' }); // this.addOverlay('<div class="popup-swap"><div class="popup-title"></div><div class="popup-content"></div><div class="popup-footer"></div><div class="popup-close"></div></div>', { // zIndex: 9000, // offset: [0, -10], // lngLat: undefined, // autoPan: true, // id: this.paras.popupId, // class: 'its-popup', // callback () { // //监听关闭按钮 // $('#overlay-'+self.paras.popupId+' .popup-close').click(function () { // self.closePopup2(); // }); // } // }); this.addOverlay('', { zIndex: 3000, lngLat: undefined, offset: [10, 10], id: 'defaultTooltip' }); this.event(); } //获取区域的中心点 getAreaCenter(coord) { var extent = ol.extent.boundingExtent(coord); var center = ol.extent.getCenter(extent); return center; } //添加服务图层(后续增加热力图、等图层0-5层分配给服务图层) addLayer(options, id) { if (!this.layer[id]) { var source = ""; switch (options.source) { //加载arcgis发布的在线服务 case "tile": source = new ol.source.TileArcGISRest({ projection: options.projection || 'EPSG:4326', url: options.url }); break; //加载通云下载谷歌地图瓦片 case "amap-google": source = new ol.source.XYZ({ tileUrlFunction(tileCoord) { var z = tileCoord[0]; var x = tileCoord[1]; var y = -tileCoord[2] - 1; var result = '', zIndex = 0; for (; zIndex < z; zIndex++) { result = "L" + (z < 10 ? ("0" + z) : z) + "/R" + y + "/C" + x; } return options.url + result + '.png'; } }); break; //加载arcgissever发布的ARCGIS online/Bing Maps/Google Maps离线瓦片 case "arcgis": source = new ol.source.XYZ({ tileUrlFunction(tileCoord) { var x = 'C' + zeroFill(tileCoord[1], 8, 16); var y = 'R' + zeroFill(-tileCoord[2] - 1, 8, 16); var z = 'L' + zeroFill(tileCoord[0], 2, 10); return options.url + z + '/' + y + '/' + x + '.png'; }, projection: 'EPSG:3857' }); break; //加载一个使用太乐地图下载器下载的谷歌离线瓦片 case "google": source = new ol.source.XYZ({ url: options.url + '{z}/{x}/{y}.png' // projection: options.projection || 'EPSG:3857', }); break; case "amap": source = new ol.source.XYZ({ url: options.url }); break; case "wms": source = new ol.source.TileWMS({ url: options.url, projection: options.projection || "EPSG:3857", serverType: 'geoserver', params: { 'FORMAT': "image/png", 'VERSION': "1.1.1", 'TILED': true, 'STYLES': "", 'LAYERS': options.layerName, 'exceptions': "application/vnd.ogc.se_inimage", } }); break; //加载一个使用太乐地图下载器下载的谷歌离线瓦片 case "mineMap": { source = new ol.source.XYZ({ crossOrigin: 'anonymous', attributions: '11', tileSize: 512, url: options.url + '/t/{z}/{x}/{y}' }) var source1 = new ol.source.XYZ({ crossOrigin: 'anonymous', attributions: '11', tileSize: 512, url: options.url + '/{z}/{x}/{y}' }) this.layer[id + "1"] = new ol.layer.Tile({ source: source1 }); this.map.addLayer(this.layer[id + "1"]); if (options.traffic) { var source2 = new ol.source.XYZ({ attributions: '11', tileSize: 256, url: 'http://www.trafficeye.com.cn/dtmimg/{z}/R13/C26/{z}-{x}-{y}.png' }) this.layer[id + "2"] = new ol.layer.Tile({ source: source2 }); this.map.addLayer(this.layer[id + "2"]); } } break; //加载一个使用太乐地图下载器下载的谷歌离线瓦片 case "amap": this.addAmapSource(); source = new ol.source.AMap({ mapType: "sat" }) ; break; case "tumeng": source = new ol.source.XYZ({ url: options.url + ':25033/v3/tile?z={z}&x={x}&y={y}', projection: 'EPSG:3857', }); var source1 = new ol.source.XYZ({ url: options.url + ':25003/v3/tile?z={z}&x={x}&y={y}', projection: 'EPSG:3857' }) this.layer[id + "0"] = new ol.layer.Tile({ source: source1 }); this.map.addLayer(this.layer[id + "0"]); break; case "arcgisTile": source = new ol.source.XYZ({ tileUrlFunction: function (tileCoord) { var z = parseInt(tileCoord[0]) - 11; var x = tileCoord[1]; var y = -tileCoord[2] - 1; var result = z + "/" + y + "/" + x; return options.url + result; }, projection: 'EPSG:4326' }); break; } var self = this; this.layer[id] = new ol.layer.Tile({ source: source, extent: options.extent, zIndex: options.zIndex || 0, opacity: options.opacity || 1, minZoom: options.minZoom || self.paras.minZoom, maxZoom: options.maxZoom || self.paras.maxZoom, // crossOrigin: "anonymous", // wrap: false, }); //图层标识 this.layer[id].set('id', id); this.layer[id].set('status', true); //加入容器 this.map.addLayer(this.layer[id]); //初始化是否显示 // this.setLayerVisible(options.status || true, id); // if (!!options.callback) { // options.callback(); // } } else { /* console.warn('变量冲突');*/ } } // /* addKML (id) { var layer = '0'; var esrijsonFormat = new ol.format.EsriJSON(); var vectorSource = new ol.source.Vector({ loader(extent, resolution, projection) { var serviceUrl = "http://192.168.22.28:6080/arcgis/rest/services/nanjing_pathline/FeatureServer/"; var url = serviceUrl + layer + '/query/?f=json&' + 'returnGeometry=true&spatialRel=esriSpatialRelIntersects&geometry=' + encodeURIComponent('{"xmin":' + extent[0] + ',"ymin":' + extent[1] + ',"xmax":' + extent[2] + ',"ymax":' + extent[3] + ',"spatialReference":{"wkid":102100}}') + '&geometryType=esriGeometryEnvelope&inSR=102100&outFields=*' + '&outSR=102100'; $.ajax({url: url, dataType: 'jsonp', success(response) { if (response.error) { /!* alert(response.error.message + '\n' + response.error.details.join('\n'));*!/ } else { var features = esrijsonFormat.readFeatures(response, { featureProjection: projection }); if (features.length > 0) { vectorSource.addFeatures(features); } } }}); } strategy: ol.loadingstrategy.tile(ol.tilegrid.createXYZ({ tileSize: 512 })) }); this.layer[id] = new ol.layer.Vector({ source: vectorSource, style(feature) { var classify = feature.get('activeprod'); return styleCache[classify]; } }); this.map.addLayer(this.layer[id]); }*/ //添加GeoJson图层(6-10层分配给JSON格式图层) addGeoJSON(options, id) { var self = this; this.group[id] = {}; this.layer[id] = new ol.layer.Vector({ zIndex: options.zIndex || 14, source: new ol.source.Vector({ url: options.url, format: new ol.format.GeoJSON() }), minZoom: options.minZoom || self.paras.minZoom, maxZoom: options.maxZoom || self.paras.maxZoom, opacity: options.opacity || 1, id: id, style(feature, resolution) { var style = self.getObjData(feature); if (!self.group[id][style.id]) { feature.set('type', 'line'); feature.set('group', id); feature.set('status', true); feature.set('hover', options.hover || function () { }); feature.set('out', options.out || function () { }); feature.set('dbclick', options.dbclick || function () { }); feature.set('click', options.click || function () { }); feature.set('textZoom', 18); switch (options.level) { case '1': feature.set('minZoom', 15); break; case '2': feature.set('minZoom', 16); break; case '3': feature.set('minZoom', 17); break; default: feature.set('minZoom', 20); } style.textZoom = style.textZoom || options.textZoom || self.paras.textZoom; style.minZoom = style.minZoom || options.minZoom || self.paras.minZoom; style.maxZoom = style.maxZoom || options.maxZoom || self.paras.maxZoom; style.fontSize = '12px'; style.borderWidth = 3; self.group[id][style.id] = feature; } style = self.getObjData(feature); return [self.setStyle(style)] } }); this.map.addLayer(this.layer[id]); this.setLayerVisible(options.status || true, id); if (!!options.callback) { options.callback(); } } addAmapSource() { ol.source.AMap = function (options) { var options = options ? options : {}; var attributions; if (options.attributions !== undefined) { attributions = option.attributions; } else { attributions = [ol.source.AMap.ATTRIBUTION]; } var url; if (options.mapType == "sat") { //url = 'http://33.140.0.195:25033/v3/tile?x={x}&y={y}&z={z}.png' url = 'http://33.140.0.195:25033/appmaptile?style=6&x={x}&y={y}&z={z}' //url ="http://webst0{1-4}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}"; } else { url = "http://webrd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}"; } ol.source.XYZ.call(this, { crossOrigin: 'anonymous', //跨域 cacheSize: options.cacheSize, projection: ol.proj.get('EPSG:3857'), // urls:urls, url: url, wrapX: options.wrapX !== undefined ? options.wrapX : true }); } ol.inherits(ol.source.AMap, ol.source.XYZ); ol.source.AMap.ATTRIBUTION = new ol.Attribution({ html: '&copy; <a class="ol-attribution-amap" ' + 'href="http://ditu.amap.com/">' + '高德地图</a>' }); } //添加要素图层 addVector(options, id) { if (!this.layer[id]) { var self = this; if (!!options.zIndex && (options.zIndex <= 10 || options.zIndex > 4000)) { console.log('ERROR:层级初始化级别10-3000'); } else { var source = new ol.source.Vector(); this.group[id] = {}; this.layer[id] = new ol.layer.Vector({ source: source, zIndex: options.zIndex || 20, minZoom: options.minZoom || self.paras.minZoom, maxZoom: options.maxZoom || self.paras.maxZoom, style(feature, resolution) { // TODO: 这个地方,只要图层显示出来,就可以动态的获得特征!!可以做很多处理! // console.log(feature, 'feature...'); var style = self.getObjData(feature); // console.log(style, 'style'); // options.changeCallback && options.changeCallback(style); style.textZoom = style.textZoom || options.textZoom || self.paras.textZoom; // TODO: 这个地方,可以设置 —— 在[minZoom, maxZoom]的层级下显示元素 style.minZoom = style.minZoom || options.minZoom || self.paras.minZoom; style.maxZoom = style.maxZoom || options.maxZoom || self.paras.maxZoom; style.tape = style.tape; return [self.setStyle(style)] } }); this.layer[id].set('id', id); this.layer[id].set('status', true); this.map.addLayer(self.layer[id]); this.setLayerVisible(options.status || true, id); if (!!options.addEvent) { source.on('addfeature', function (e) { options.addEvent(e.feature); }); } if (!!options.callback) { options.callback(); } } } else { /*console.log('ERROR:图层id重复使用');*/ } } //添加覆盖物图层 addOverlay(container, options, group) { $('#' + this.paras['target']).append('<div class="' + (options.class || "") + '" id="overlay-' + options.id + '"></div>'); $('#overlay-' + options.id).append(container); this.layer[options.id] = new ol.Overlay({ id: options.id, autoPan: options.autoPan || false, element: document.getElementById('overlay-' + options.id), position: options.lngLat || [0, 0], offset: options.offset || [0, 0], autoPanAnimation: { duration: 250 //当超出地图边界时,为了全部可见,地图移动的速度. 单位为毫秒(ms) }, stopEvent: options.stopEvent, //overlay是否屏蔽所有事件,默认是屏蔽 positioning: 'bottom-center', zIndex: options.zIndex || 0 }); this.layer[options.id].set('id', options.id); this.map.addOverlay(this.layer[options.id]); if (!!group) { if (!this.group[group]) { this.group[group] = {}; } this.group[group][options.id] = this.layer[options.id]; } //回调 if (!!options.callback) { options.callback(); } } //添加事件 addEvent(name, event) { map[name] = event; } //设置标签颜色 setTooltipStyle(className) { $('#overlay-defaultTooltip').attr('class', className); return this; } //增加工具栏 addTool(callback) { $('#' + this.paras.target).append('<div class="mapTool"></div>'); if (!!callback) { callback(); } } //设置标签内容 setTooltipText(text, id) { if (!id) { id = 'defaultTooltip'; } $('#overlay-' + id).empty().append(text); return this; } //设置标签坐標 setTooltipPosition(coord) { this.layer['defaultTooltip'].setPosition(coord); return this; } //打开弹框 openPopup(feature, content, callback) { var self = this; var coord; this.closePopup(); content = content || {}; if (!feature) { return false; } else { var data = this.getObjData(feature); if (data.type == 'icon' || data.type == 'point') { coord = data.lngLat; } else { coord = self.mapTool().pgcentroid(data.lngLat, data.type); } /*coord = this.mapTool().pgcentroid(data, feature.S.type);*/ this.layer['defaultPopup'].setPosition(coord); //预先定义一个会出现宽度不能自适应居中,插件自身局限性导致,这样效率低,后续有时间自己写个弹框 $('#overlay-defaultPopup').popover({ 'placement': 'top', 'animation': false, 'html': true, 'title': content.title || '', 'content': content.content || '' }); $('#overlay-defaultPopup').popover('show'); $('.popover').append('<div class="popover-close">&times;</div>'); $('.popover-close').click(function () { self.closePopup(); }); callback = callback || function () { }; callback(); this.refresh(data.group); } } //关闭弹框 closePopup() { $('#overlay-defaultPopup').popover('destroy'); return this; } //打开弹框 openPopup2(feature, content, callback) { $('.popup-footer span').remove(); var self = this; var elem = $(this.layer[this.paras.popupId].N.element); elem.removeClass('zoomInDown animated'); content = content || {}; var data = content; if (!!feature) { data = this.getObjData(feature) || feature; content = $.extend(data, content); if (data.type == 'icon' || data.type == 'point' || data.type == 'canvas') { content.coord = content.coord || data.lngLat; } else { content.coord = self.mapTool().pgcentroid(data.lngLat, data.type); } } if (!!content.popup) { content.title = content.popup ? content.popup.title || content.name : ''; content.content = content.popup && content.popup.content ? content.popup.content : ""; content.footer = content.popup && content.popup.footer ? content.popup.footer : ""; content.callback = content.popup.callback || function () { }; } elem.find('.popup-title').html(content.title); elem.find('.popup-content').html(content.content); var html = ''; var footer = elem.find('.popup-footer'); footer.empty(); if (typeof (content.footer) == 'object') { var footer = content.footer; for (var i in footer) { html = '<span class="' + footer[i]["class"] + '">' + footer[i]["label"] + '</span>'; elem.find('.popup-footer').append(html); if (!!footer[i]['callback']) { if (footer[i]["class"].indexOf('btn-click') > -1) { $('.popup-footer span').unbind().click(function () { footer[$(this).index()]['callback'](data); }); } if (footer[i]["class"].indexOf('btn-dbclick') > -1 && !!footer[i]['callback']) { $('.popup-footer span').unbind().dblclick(function () { footer[$(this).index()]['callback'](data); }); } } } } /* var w = elem.width(); elem.css({ 'width': w + 'px' });*/ /* var w = elem.width(); elem.css({ 'width': w + 'px' });*/ setTimeout(function () { self.layer[self.paras.popupId].setPosition(content.coord); elem.addClass('zoomInDown animated'); callback && callback(feature); }, 200); } setOffsetPopup2(offset) { this.layer[this.paras.popupId].setOffset(offset); } setContentPopup2(content) { var elem = $(this.layer[this.paras.popupId].N.element); elem.find('.popup-content').html(content); } setLngLatPopup2(lngLat) { this.layer[this.paras.popupId].setPosition(lngLat); } setWidthPopup2(w) { var elem = $(this.layer[this.paras.popupId].N.element); elem.css({ 'width': w + 'px' }); } //关闭弹框 closePopup2() { this.layer[this.paras.popupId].setPosition(undefined); return this; } destoryPopup2() { this.layer[this.paras.popupId].setPosition(undefined); var elem = $(this.layer[this.paras.popupId].N.element); elem.find('.popup-title').html(''); elem.find('.popup-content').html(''); elem.find('.popup-footer').html(''); return this; } //添加要素 addFeature(options, id) { var self = this; if (!!id) { if (!self.layer[id]) { self.addVector(options, id); self.group[id] = {} } else { /* console.warn('Warning:' + id + '变量重复使用');*/ } } else { id = 'defaultLayer'; } var feature, geometry; var data = options.data; for (var i in data) { var n = data[i]; feature = n; switch (options.type) { case 'icon': geometry = new ol.geom.Point(n.lngLat); break; case 'canvas': geometry = new ol.geom.Point(n.lngLat); break; case 'point': geometry = new ol.geom.Point(n.lngLat); break; case 'line': geometry = new ol.geom.LineString(n.lngLat); break; case 'circle': geometry = new ol.geom.Circle(n.lngLat[0], n.lngLat[1] / 1000); break; case 'polygon': geometry = new ol.geom.Polygon([n.lngLat]); break; default: { console.log('ERROR:参数错误或者当前版本不支持' + options.type + '类型'); return false; } } feature.geometry = geometry; feature = new ol.Feature(feature); feature.set('type', options.type); feature.set('tape', n.tape || options.tape || 0); feature.set('id', n.id || i); feature.set('group', id); feature.set('status', true); feature.set('hover', options.hover || n.hover || function () { }); feature.set('out', options.out || n.out || function () { }); feature.set('dbclick', options.dbclick || n.dbclick || function () { }); feature.set('click', options.click || n.click || function () { }); self.group[id][n.id || i] = feature; if (!!n.group) { if (!self.group[id][n.group]) { self.group[id][n.group] = []; } self.group[id][n.group].push(feature); } self.layer[id].getSource().addFeature(feature); self.layer[id].getSource().refresh(); //更新图层 } if (!!options.callback) { options.callback(feature); } return this; } //地图增加事件 addMapEvent(event, func) { map[event] = func; } addCircle(options, id) { var self = this; if (!this.layer[id] && !id) { id = 'defaultRipple'; } var circle = []; var data = options.data; var line = []; for (var i in data) { var canvas = document.createElement('canvas'); var ctx = canvas.getContext("2d"); var raduis = data[i].raduis || 30; canvas.height = canvas.width = raduis * 2; ctx.beginPath(); ctx.arc(raduis, raduis, raduis, 0, Math.PI * 2, true); // 绘制 ctx.fillStyle = data[i].outColor || '#c9e6b4'; ctx.fill(); ctx.beginPath(); ctx.moveTo(raduis, raduis); ctx.fillStyle = data[i].innerColor || '#96da6d'; ctx.arc(raduis, raduis, raduis * 0.8, 0, Math.PI * 2, false); // 口(顺时针) ctx.fill(); ctx.font = (data[i].fontSize || (raduis * 0.5)) + "px Arial"; ctx.textAlign = "center"; ctx.strokeText(data[i].text || '', raduis, raduis + raduis * 0.2); circle.push($.extend({ canvas: canvas, id: i, type: 'canvas' }, data[i])); if (!!options.line) { line.push(data[i]["lngLat"]); } } this.addFeature($.extend(options, { data: circle, type: 'canvas' }), id); if (line.length > 0) { console.log(728); this.addFeature({ type: 'line', data: [{ lngLat: line, borderColor: options.lineColor || '#000', borderWidth: options.lineWidth || 4, id: 'ddddadasdas' }, { lngLat: line, borderColor: options.lineColor || '#96da6d', lineDash: options.lineDash || [15, 20], borderWidth: options.lineWidth || 4, id: 'ddsassddasd' }] }, id); } } //聚合 addCluster(options, id) { var self = this; if (!!id) { if (!self.layer[id]) { self.addVector(options, id); self.group[id] = {} } else { } } else { id = 'defaultLayer'; } var data = options.data; var features = []; for (var i in data) { var f = new ol.Feature(new ol.geom.Point(data[i]["lngLat"])); f.set('desc', data[i]); f.set('name', data[i]['name']); f.set('lngLat', data[i]["lngLat"]); f.set('coord', data[i]["lngLat"]); f.set('type', options.type); f.set('tape', data[i].tape || options.tape || 0); f.set('id', data[i].id || i); f.set('group', id); f.set('status', true); f.set('hover', options.hover || data[i].hover || function () { }); f.set('out', options.out || data[i].out || function () { }); f.set('dbclick', options.dbclick || data[i].dbclick || function () { }); f.set('click', options.click || data[i].click || function () { }); f.set('zIndex', options.zIndex || data[i].zIndex); features.push(f) self.group[id][data[i].id || i] = f; } var source = new ol.source.Vector({ features: features, zIndex: options.zIndex || 0 }); var clusterSource = new ol.source.Cluster({ distance: options.distance || 100, source: source, zIndex: options.zIndex || 0 }); this.layer[id] = new ol.layer.Vector({ source: clusterSource, style: function (feature, resolution) { var f = feature.get('features'); var size = f.length; if (size == 1) { var d = self.getObjData(f[0]).desc; d["textBaseline"] = "middle"; d["offsetY"] = "0"; // TODO: 1. 这边做了修改 var zoom = self.getZoom(); d.minZoom = !!d.minZoom ? d.minZoom : self.paras.minZoom; d.maxZoom = !!d.maxZoom ? d.maxZoom : self.paras.maxZoom; if (zoom < d.minZoom || zoom > d.maxZoom) { return null; } else { return self.setStyle(d); } } else { var d = self.getObjData(f[0]).desc; // if(d['type'] == 'icon'){ // return [new ol.style.Style({ // image: new ol.style.Icon({ // src: d.icon, // }), // text: new ol.style.Text({ // text: size.toString(), // fill: new ol.style.Fill({ // color: d.textColor // }), // font: '14px Helvetica', // textAlign: 'center', //位置 // textBaseline:'bottom', //基准线 // offsetY: '-14' // }) // })] // } else { // TODO: 2. 这边做了修改 var zoom = self.getZoom(); d.minZoom = !!d.minZoom ? d.minZoom : self.paras.minZoom; d.maxZoom = !!d.maxZoom ? d.maxZoom : self.paras.maxZoom; if (zoom < d.minZoom || zoom > d.maxZoom) { return null; } else { return [new ol.style.Style({ image: new ol.style.Circle({ radius: 14, // TODO: 显示的 stoke: new ol.style.Stroke({ color: '#fff' }), fill: new ol.style.Fill({ // color: '#e4393c' color: '#0032FF' }), }), text: new ol.style.Text({ text: size.toString(), fill: new ol.style.Fill({ color: '#fff' }), font: '14px Helvetica' }), zIndex: options.zIndex || d.zIndex })]; } // } } }, zIndex: options.zIndex || 0 //TODO: 要给聚合层设置zIndex, 否则会被其他图层盖住 }); this.map.addLayer(this.layer[id]); this.layer[id].set('status', true); } //新增扩散(使用前打开) addRipple(options, callback) { if (!this.layer['defaultRipple']) { this.addVector({ zIndex: 0 }, 'defaultRipple'); } var self = this; var raduis = options.raduis || 100; var canvas = document.createElement('canvas'); var ctx = canvas.getContext("2d"); canvas.width = raduis * 2; canvas.height = raduis * 2; var ball = $.extend({ type: 'canvas', raduis: 0, speed: 0.8, backgroundColor: 'red', borderColor: 'red', textZoom: this.paras.maxZoom }, options); ball.draw = function () { ctx.beginPath(); ctx.arc(raduis, raduis, ball.raduis, 0, Math.PI * 2, true); ctx.strokeStyle = ball.backgroundColor; ctx.stroke(); }; ball.render = function () { if (ball.raduis + 0.5 >= raduis) { ball.raduis = 0; } else { ball.raduis += ball.speed; } var prev = ctx.globalCompositeOperation; ctx.globalCompositeOperation = 'destination-in'; ctx.globalAlpha = ball.opactiy || 0.96; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.globalCompositeOperation = prev; ball.draw(); self.refresh('defaultRipple'); window.requestAnimationFrame(ball.render); }; ball.canvas = canvas; this.addFeature({ type: 'canvas', data: [ball] }, 'defaultRipple'); this.group.defaultRipple[ball.id].setStyle(this.setStyle(ball)); ball.render(); return this; } getRipple(id) { return this.getObjData(this.group['defaultRipple'][id]); } removeRipple(id) { var feat = this.group.defaultRipple[id]; if (!!feat) { this.layer.defaultRipple.getSource().removeFeature(feat); delete this.group.defaultRipple[id]; // console.log('删除成功'); } else { console.log(id + '不存在'); } return this; } isExistRipple(id) { var feat = this.group['defaultRipple'][id]; return !!feat; } toggleRipple(id) { if (!!id) { var feat = this.group.defaultRipple[id]; if (!!feat) { var status = this.getObjData(feat).status; if (!!status) { feat.set('status', false); this.layer.defaultRipple.getSource().removeFeature(feat); delete this.group.defaultRipple[id]; } else { feat.set('status', true); this.layer.defaultRipple.getSource().addFeature(feat); } } else { console.log(id + '不存在'); } } else { this.toggleLayer('defaultRipple'); } return this; } //获取鼠标点击处的元素 getFeatureAtPixel(coordinate) { const features = []; const pixel = this.getPixelFromCoordinate(coordinate); this.map.forEachFeatureAtPixel(pixel, function (feature) { features.push(feature); }); return features; } //获得视图 getView() { return this.map.getView(); } //获得当前经纬度对对应的地图上的像素坐标 getPixelFromCoordinate(coordinate) { return this.map.getPixelFromCoordinate(coordinate); } //当前级别 getZoom() { return this.getView().getZoom(); } setZoom(zoom) { this.getView().setZoom(zoom); return this; } //最大级别 getMaxZoom() { return this.getView().getMaxZoom(); } setMaxZoom(maxZoom) { this.getView().setMaxZoom(maxZoom); return this; } //最小级别 getMinZoom() { return this.getView().getMinZoom(); } setMinZoom(minZoom) { this.getView().setMinZoom(minZoom); return this; } //获取当前中心点 getCenter() { return this.getView().getCenter(); } //设置当前中心点 setCenter(coord) { return this.getView().setCenter(coord); return this; } //获取旋转角度 getViewRotation() { return this.getView().getRotation(); } //设置旋转角度 setRotation(deg) { this.getView().setRotation(deg); return this; } //获取分辨率 getResolution() { return this.getView().getResolution(); } //设置分辨率 setResolution(resolution) { this.getView().setResolution(resolution); return this; } //获取对象数据 getObjData(obj) { return obj.N; } //获取要素状态 getFeatureStatus(obj) { return obj.N.status; } //设置对象数据 setObjData(obj, data) { var style = $.extend(this.getObjData(obj), data); obj.N = style; this.refresh(style.group); return this; } //获取对象 getObj(data) { return this.group[data.group][data.id]; } //获取要素 getFeature(id, group) { if (!group) { group = 'defaultLayer'; } return !!this.group[group] ? this.group[group][id] : null; } //獲取要素坐标 getFeatureLngLat(feat) { return feat.getGeometry().getCoordinates(); } //设置要素坐标 setFeatureLngLat(feat, lngLat) { feat.getGeometry().setCoordinates(lngLat); } //设置要素坐标 setCircleFeatureLngLat(feat, lngLat) { feat.getGeometry().setCenter(lngLat); } //设置要素坐标 setCircleFeatureRadius(feat, radius) { feat.getGeometry().setRadius(radius); } //获取图层层级 getLayerZindex(id) { if (!!id) { return this.layer[id].getZIndex(); } } //图层层级 setLayerZindex(id, zIndex) { if (!!id) { this.layer[id].setZIndex(zIndex); return this; } } //设置要素样式 setFeatStyle(feature, style) { feature.setStyle(this.setStyle(style)); return this; } //修改要素ID通过ID setFeatureIdByData(pid, id, group) { if (!!this.group[group][pid] && !this.group[group][id]) { this.group[group][id] = this.group[group][pid]; delete this.group[group][pid]; } else { /* console.log('确定id是否重复或者不存在');*/ } } setFeatureData(feature, data) { var getData = this.getObjData(feature); var groupName = getData.group; feature.N = $.extend(feature.N, data); // delete this.group[groupName][getData.id]; this.group[groupName][data.id] = feature; this.refresh(groupName); } //获取图层状态 getLayerVisable(id) { return this.layer[id].getVisible(); } //设置图层显隐 setLayerVisible(flag, id) { if (!id) { id = 'defaultLayer'; } if (!!this.layer[id]) { this.layer[id].set('status', flag); this.layer[id].setVisible(flag); } return this; } //是否显示 isShow(id) { if (!id) { id = 'defaultLayer'; } var zoom = this.getZoom(); var minZoom = this.layer[id].get('minZoom') || this.paras.minZoom; var maxZoom = this.layer[id].get('maxZoom') || this.paras.maxZoom; var status = this.layer[id].get('status'); if (zoom <= maxZoom && zoom >= minZoom && !!status) { this.layer[id].setVisible(true); } else { this.layer[id].setVisible(false); } } //显隐某图层 toggleLayer(id) { id = id || 'defaultLayer'; var status = this.layer[id].get('status'); console.log(!status); this.layer[id].set('status', !status); this.isShow(id); return !status; } getLayerStatus(id) { return this.layer[id].get('status'); } //设置图层透明度 setLayerOpacity(opacity, id) { if (!id) { id = 'defaultLayer'; } this.layer[id].setOpacity(opacity); return this; } //改变要素 setFeature(id, style, group) { var feat = this.group[group || 'defaultLayer'][id]; var group = this.group[group || 'defaultLayer']; if (!!group) { var feat = group[id]; if (!!feat) { var getData = this.getObjData(feat); getData = $.extend(getData, style); this.setObjData(feat, getData); } else { /*console.log('ERROR:' + id + '不存在');*/ } } else { /*console.log('ERROR:' + group + '组不存在');*/ } } //图层是否存在 isExistLayer(id) { return !!this.layer[id]; } //要素是否存在 isExistFeat(id, group) { if (!group) { group = 'defaultLayer'; } var feature = this.group[group][id]; return !!feature; } //获取某图层最近的要素 getClosetFeature(lngLat, layer) { if (!layer) { layer = 'defaultLayer'; } var feat = this.layer[layer].getSource().getClosestFeatureToCoordinate(lngLat); return feat; } //清除某要素 clearFeature(id, group) { if (!group) { group = 'defaultLayer'; } if (!!this.group[group]) { var feature = this.group[group][id]; if (!!feature) { this.layer[group].getSource().removeFeature(feature); delete this.group[group][id]; } else { console.log('id要素不存在'); } } } clearAllFeature(group) { var groups = this.group[group]; for (var i in groups) { this.layer[group].getSource().removeFeature(groups[i]); } this.group[group] = {}; } //刪除图层 removeLayer(id) { if (this.isExistLayer(id)) { this.map.removeLayer(this.layer[id]); delete this.group[id]; delete this.layer[id]; } } //刪除覆盖物 removeOverlay(id) { this.map.removeOverlay(this.layer[id]); this.group[id] = null; this.layer[id] = null; } //显隐图层 toggleOverlay(id) { var overlaye = this.map.getOverlayById(id); var display = document.getElementById(overlaye.N.element.id); if (display.style.display == "none") { display.style.display = "inline-block"; } else { display.style.display = "none"; } } getOverlayById(id) { return this.map.getOverlayById(id); } setOverlayPosition(id, coord) { this.map.getOverlayById(id).setPosition(coord); } setOverlayerContent(id, content) { $('#overlay-' + id).html(content); } setOverlayerContentById(id, content) { $('#' + id).html(content); } //返回JQ对象 getJq(id) { return $(id) } //刷新要素图层 refresh(id) { if (!id) { id = 'defaultLayer'; } if (!!this.layer[id]) { this.layer[id].getSource().refresh(); } } render() { this.map.render(); $('#' + this.paras.id).click(); return this; } setStyle(styles) { var styles = styles || {}; var self = this; var zoom = self.getZoom(); // console.log(zoom+"==="+styles.textZoom); // console.log('当前地图层级为:', zoom); if (zoom < styles.textZoom) { styles.fontSize = '0'; } else { styles.fontSize = '10'; } if (zoom < styles.minZoom || zoom > styles.maxZoom) { styles.opacity = 0; styles.fontSize = '0'; } else { styles.opacity = styles.opacity || 1; } if (styles.type == 'icon') { return new ol.style.Style({ image: new ol.style.Icon({ src: styles.icon || 'http://221.6.32.82:250/img/page/common/logo.png', anchor: styles.anchor || [0.5, 0.5], //中心点相对距离 anchorOrigin: styles.anchorOrigin || 'top-left', //anchor一起用的相对位置 offset: styles.offset || [0, 0], offsetOrigin: styles.offsetOrigin || 'top-left', //偏移位置 opacity: styles.opacity, scale: 1 + (self.getZoom() - self.paras.zoom) * Math.abs(styles.tape), rotation: styles.deg || 0, size: styles.size || [32, 32], color: !!styles.fillColor ? self.mapTool().oxToRgb(styles.fillColor, 1) : undefined }), text: new ol.style.Text({ textAlign: styles.position || 'center', //位置 textBaseline: styles.baseLine || 'bottom', //基准线 font: styles.fontSize + ' sans-serif' || self.paras.zoom + 'px sans-serif', //文字样式 fill: new ol.style.Fill({ color: self.mapTool().oxToRgb(styles.textColor || '#fff', styles.opacity || 1) }), scale: 1 + (self.getZoom() - self.paras.zoom) * Math.abs(styles.tape / 2), rotation: styles.deg || 0, text: styles.name, stroke: new ol.style.Stroke({ color: styles.TextBorderColor || 'rgba(255,255,255,0)', width: styles.TextborderWidth || 0, lineDash: styles.TextlineDash }), offsetY: styles.TextY + (self.getZoom() - self.paras.zoom) * 2 || (self.getZoom() - self.paras.zoom) * Math.abs(styles.tape) * 20 + 24, backgroundFill: new ol.style.Fill({ color: styles.backgroundColor || 'rgba(255,255,255,0)' }), }), zIndex: styles.zIndex || 0 }); } else if (styles.type == 'canvas') { return new ol.style.Style({ image: new ol.style.Icon({ img: styles.canvas, imgSize: [styles.canvas.width, styles.canvas.height], opacity: styles.opacity, offset: styles.offset || [0, 0], }), text: new ol.style.Text({ textAlign: styles.position || 'center', //位置 textBaseline: styles.baseLine || 'middle', //基准线 font: '12px sans-serif' || self.paras.zoom + 'px sans-serif', //文字样式 fill: new ol.style.Fill({ color: self.mapTool().oxToRgb(styles.color || 'black', styles.opacity || 1) }), rotation: styles.deg || 0, text: styles.name || '', stroke: new ol.style.Stroke({ color: styles.TextBorderColor || '#6c0', width: styles.TextborderWidth || 1, lineDash: styles.TextlineDash || [0, 0] }), offsetY: styles.TextY + (self.getZoom() - self.paras.zoom) * 2 || 20 + (self.getZoom() - self.paras.zoom) * 2 }), zIndex: styles.zIndex || 0 }); } else { return new ol.style.Style({ image: new ol.style.Circle({ radius: styles.radius || 10, fill: new ol.style.Fill({ color: self.mapTool().oxToRgb(styles.color || '#fff', styles.opacity || 1) }), stroke: new ol.style.Stroke({ color: styles.circleBorderColor || 'black', width: styles.circleWidth || 1 }), opacity: styles.opacity, scale: styles.scale || self.getZoom() / self.paras.zoom }), fill: new ol.style.Fill({ color: self.mapTool().oxToRgb((styles.fillColor ? styles.fillColor : styles.backgroundColor) || '#fff', styles.opacity || 0.5) }), /*stroke: styles.opacity==0?null:new ol.style.Stroke({ color: styles.borderColor || '#6c0', width: styles.borderWidth || 2, lineDash: styles.lineDash || [0, 0] }),*/ stroke: new ol.style.Stroke({ color: styles.borderColor || '#fff', width: styles.borderWidth || 2, lineDash: styles.lineDash || [0, 0], fill: new ol.style.Fill({ color: this.mapTool().oxToRgb(styles.fillColor) }), }), text: new ol.style.Text({ textAlign: styles.position || 'center', //位置 textBaseline: styles.baseLine || 'hanging', //基准线 font: styles.fontSize + 'px sans-serif' || self.paras.zoom + 'px sans-serif', //文字样式 fill: new ol.style.Fill({ color: this.mapTool().oxToRgb(styles.textColor || 'black', styles.opacity || 1) }), stroke: new ol.style.Stroke({ color: styles.TextBorderColor || '#fff', width: styles.TextborderWidth || 0, lineDash: styles.TextlineDash || [0, 0] }), text: styles.name || '', rotation: styles.deg || 0, offsetY: styles.TextY + (self.getZoom() - self.paras.zoom) * 2 || 20 + (self.getZoom() - self.paras.zoom) * 2 }), zIndex: styles.zIndex }); } } mapTool() { var pi = 3.1415926535897932384626; var a = 6378245.0; var ee = 0.00669342162296594323; var tool = { //十六进制转RGB格式 oxToRgb(color, opacity) { color = color || '#fff'; var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/; var sColor = color.toLowerCase(); if (sColor && reg.test(sColor)) { if (sColor.length === 4) { var sColorNew = "#"; for (var i = 1; i < 4; i += 1) { sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1)); } sColor = sColorNew; } //处理六位的颜色值 var sColorChange = []; for (var i = 1; i < 7; i += 2) { sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2))); } sColorChange.push(opacity || 0.5); sColorChange = sColorChange.join(','); return 'rgba(' + sColorChange + ')'; } else { return sColor; } }, //圆请注明 pgcentroid(polygon, type) { if (!type || type == 'point' || type == 'icon' || type == 'canvas') { return polygon; } else if (type != 'circle') { if (typeof polygon == 'String') { var flag = polygon.split('|'); if (flag.length > 0) { polygon = this.lineStringToArray(polygon); } } var length = polygon.length; var p1 = 0, p2 = 0; for (var i in polygon) { p1 += polygon[i][0]; p2 += polygon[i][1]; } return [p1 / length, p2 / length]; } else { return polygon[0]; } }, //坐标字符串转成数组 stringToArray(str, format) { var str = str.split(format || ','); return [parseFloat(str[0]), parseFloat(str[1])]; }, lineStringToArray(str) { var str = str.split(','); var coord = []; for (var i in str) { coord.push(this.stringToArray(str[i], '|')); } return coord; }, gps84ToGcj02(lon, lat) { console.log("lat:" + lat + "lon:" + lon); if (this.outOfChina(lat, lon)) { return null; } var dLat = this.transformLat(lon - 105.0, lat - 35.0); var dLon = this.transformLon(lon - 105.0, lat - 35.0); var radLat = lat / 180.0 * pi; var magic = Math.sin(radLat); magic = 1 - ee * magic * magic; var sqrtMagic = Math.sqrt(magic); dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi); dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi); var mgLat = parseFloat(lat) + parseFloat(dLat); var mgLon = parseFloat(lon) + parseFloat(dLon); return [mgLon, mgLat]; } , transformLat(x, y) { var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x)); ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0; ret += (20.0 * Math.sin(y * pi) + 40.0 * Math.sin(y / 3.0 * pi)) * 2.0 / 3.0; ret += (160.0 * Math.sin(y / 12.0 * pi) + 320 * Math.sin(y * pi / 30.0)) * 2.0 / 3.0; return ret; }, transformLon(x, y) { var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x)); ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0; ret += (20.0 * Math.sin(x * pi) + 40.0 * Math.sin(x / 3.0 * pi)) * 2.0 / 3.0; ret += (150.0 * Math.sin(x / 12.0 * pi) + 300.0 * Math.sin(x / 30.0 * pi)) * 2.0 / 3.0; return ret; }, outOfChina(lat, lon) { if (lon < 72.004 || lon > 137.8347) { return true; } if (lat < 0.8293 || lat > 55.8271) { return true; } return false; } }; return tool; } locate(id, animate, group) { var self = this; var group = group || 'defaultLayer'; if (!!this.group[group][id]) { var data = this.getObjData(this.group[group][id]); this.animateMap({ type: animate.type || 0, center: self.mapTool().pgcentroid(data.lngLat, data.type), zoom: animate.zoom || self.getZoom(), duration: animate.time || 500, rotation: animate.rotate || 0 }); this.refresh(group); } return this; } locate2(id, animate, group) { var self = this; var group = group || 'defaultLayer'; if (!!this.group[group][id]) { var data = this.getObjData(this.group[group][id]); self.flyTo(self.mapTool().pgcentroid(data.lngLat, data.type), animate.callback || function () { }); } } //地图动画 animateMap(options) { var view = this.getView(); switch (options.type) { case 0: { view.animate({ center: options.center || view.getCenter(), zoom: options.zoom || view.getZoom(), duration: options.time || 1000, rotation: options.rotation || 0 }) } break; case 1: { view.animate({ center: options.center || view.getCenter(), duration: options.time || 1000, }); view.animate({ zoom: options.zoom || 9, duration: options.time || 1000, }, { zoom: options.zoom || view.getZoom(), duration: options.time || 1000, }); } break; case 2: { view.animate({ zoom: options.zoom - 2, center: options.center || view.getCenter(), duration: options.time || 1000 }); view.animate({ zoom: options.zoom, duration: options.time || 1000, }, { zoom: options.zoom + 2, duration: options.time || 1000, }); } break; } } flyTo(location, done) { var view = this.getView(); var duration = 2000; var zoom = view.getZoom(); var parts = 2; var called = false; function callback(complete) { --parts; if (called) { return; } if (parts === 0 || !complete) { called = true; done(complete); } } view.animate({ center: location, duration: duration }, callback); view.animate({ zoom: zoom - 1, duration: duration / 2 }, { zoom: zoom, duration: duration / 2 }, callback); } event() { var self = this; var click = new ol.interaction.Select({}); this.map.addInteraction(click); // 监听选中事件,然后在事件处理函数中改变被选中的`feature`的样式 var clickFeatures = click.getFeatures(); // click.on('select', function (event) { var feature = event.selected[0]; var d; var coord; if (!!feature && !self.paras.status) { var getData = self.getObjData(feature); d = getData; coord = getData.coord; if (!!getData.features) {