Angular2地图的使用、地图画线、高德底图切换、图标变换等

一、map.service文件

import { Injectable } from ‘@angular/core’;

 

import * as ol from ‘openlayers’;

import * as coordtransform from ‘coordtransform’;

 

import { DITU_SERVER_URL, CQ_DITU_SERVER, GEO_SERVER } from ‘../../app.constants’;

 

@Injectable()

export class MapService {

map: ol.Map;

defaultCenter = [106.499258, 29.535594];

type = ‘gaode’; // 地图类型

baseLayers = [];

features;

linesCache;

pointsCache;

rvSegId:string;

featureLayer = new ol.layer.Vector();

// 规划点样式

expectPointStyle = new ol.style.Style({

image: new ol.style.Icon({

// color: ‘#8959A8’,

// src: ‘https://openlayers.org/en/v4.1.1/examples/data/dot.png’

crossOrigin: ‘anonymous’,

src: ‘/images/icon/xun021.png’

})

});

// 规划线样式

expectLineStyle = new ol.style.Style({

stroke: new ol.style.Stroke({

color: ‘red’,

width: 10

})

});

// 巡河点样式

 

realPointStyle = new ol.style.Style({

image: new ol.style.Icon({

// color: ‘#9959A8’,

// src: ‘https://openlayers.org/en/v4.1.1/examples/data/dot.png’

crossOrigin: ‘anonymous’,

src: ‘/images/icon/xun021.png’

})

});

// 巡河线样式

realLineStyle = new ol.style.Style({

stroke: new ol.style.Stroke({

color: ‘blue’,

width: 10

})

});

 

/**

* 初始化地图

*/

init(rvSegId?:any) {

this.features = [];

this.linesCache = [];

this.pointsCache = [];

this.featureLayer = new ol.layer.Vector();

// let gaodeMap = new ol.layer.Tile({

// source: new ol.source.XYZ({

// url: DITU_SERVER_URL

// }),

// name: ‘gaode’,

// visible: true

// });

// this.baseLayers.push(gaodeMap);

 

var tdt_vec = new ol.layer.Tile({

name: ‘天地图矢量图’,

source: new ol.source.XYZ({

url: ‘http://t{0-6}.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}’,

projection: ‘EPSG:3857’

}),

visible: true

 

});

this.baseLayers.push(tdt_vec);

var tdt_cva = new ol.layer.Tile({

name: ‘天地图矢量图’,

source: new ol.source.XYZ({

url: ‘http://t{0-6}.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}’,

projection: ‘EPSG:3857’

}),

visible: true

});

this.baseLayers.push(tdt_cva);

 

let gridSetsParams = this.gridSetsParams(‘EPSG:4326’, 18, false); // 市资源共享交换平台的坐标系均为4326,最高缩放级别为18

let tileGrid = new ol.tilegrid.WMTS({

origin: gridSetsParams.origin,

resolutions: gridSetsParams.resolutions,

matrixIds: gridSetsParams.matrixIds

});

let vector = new ol.layer.Tile({

name: ‘vector’,

source: new ol.source.WMTS({

url: CQ_DITU_SERVER + ‘/8ca72f6bd53144f4859018c180843e18/af8551534a4b4b13ab60eac366ba44ef’,

layer: ‘ZHSQ_IMG1’,

style: ‘default’,

matrixSet: ‘CQMap_IMG’,

projection: ‘EPSG:4326’,

tileGrid: tileGrid,

format: ‘image/mixed’

}),

visible: false

});

 

this.baseLayers.push(vector);

 

if (this.map) {

this.map.getTargetElement().innerHTML = ”;

this.map = null;

}

//显示河段

if(rvSegId) {

this.rvSegId = rvSegId;

// this.rvSegId = ‘F3AE2B00000R500153001006’;

let rvSegGeoUrl = GEO_SERVER+’/cq/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=cq:tb_wr_rv_seg&maxFeatures=50&outputFormat=application%2Fjson&cql_filter=RV_SEG_ID=%27’+this.rvSegId+’%27&propertyName=GEOM’;

let vectorSource = new ol.source.Vector({

format: new ol.format.GeoJSON(),

url: rvSegGeoUrl

});

let rvSegVector = new ol.layer.Vector({

name:’rvSegVector’,

source: vectorSource,

// style: ‘classed rivers(different width)’

style: new ol.style.Style({

stroke: new ol.style.Stroke({

color: ‘#16a5ff’,

width: 10

})

})

});

this.baseLayers.push(rvSegVector);

}

this.map = new ol.Map({

target: ‘map’,

layers: this.baseLayers,

view: new ol.View({

center: ol.proj.transform(this.defaultCenter, ‘EPSG:4326’, ‘EPSG:3857’),

zoom: 14

})

});

 

this.map.addLayer(this.featureLayer);

}

 

/**

* 设置中心点

* @param center 中心点

*/

setCenter(center) {

if (!center) {

return;

}

 

if (this.type === ‘gaode’) {

center = coordtransform.wgs84togcj02(center[0], center[1]);

} else {

center = coordtransform.gcj02towgs84(center[0], center[1]);

}

 

this.map.getView().setCenter(ol.proj.transform(center, ‘EPSG:4326’, ‘EPSG:3857’))

}

 

/**

* 添加点

* @param point 点坐标

* @param style 点样式

*/

addPoint(points?, style?) {

if (!points) {

if (!this.pointsCache) {

return;

}

let arrPoints = this.pointsCache;

this.pointsCache = [];

arrPoints.forEach(objPoints => {

this.addPoint(objPoints.points, objPoints.style);

});

} else {

this.pointsCache.push({

points: points,

style: style

});

for (let i = 0; i < points.length; i++) {

let point = points[i];

if (this.type !== ‘gaode’) {

point = coordtransform.gcj02towgs84(point.longitude, point.latitude);

} else {

point = [point.longitude, point.latitude]

}

let pointFea = new ol.Feature({

geometry: new ol.geom.Point(ol.proj.fromLonLat(point))

});

 

pointFea.setStyle(this[style + ‘PointStyle’]);

this.features.push(pointFea);

}

 

this.updateFeatureLayer();

}

}

 

// addRvSeg(rvSegId?:any){

// // let layerSeg = new ol.layer.Vector({

// // source: new ol.source.Vector({

// // format: new ol.format.GeoJSON(),

// // url:`${GEO_SERVER}`+’/cq/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=cq:tb_wr_rv_seg&maxFeatures=50&outputFormat=application%2Fjson&cql_filter=RV_SEG_ID=’+rvSegId+’&propertyName=GEOM’

// // }),

// // style: ‘classed rivers(different width)’

// // });

// if(rvSegId) {

// this.rvSegId = rvSegId;

// }

// let feature = new ol.Feature(new ol.source.Vector({

// format: new ol.format.GeoJSON(),

// url:`${GEO_SERVER}`+’/cq/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=cq:tb_wr_rv_seg&maxFeatures=50&outputFormat=application%2Fjson&cql_filter=RV_SEG_ID=%27’+this.rvSegId+’%27&propertyName=GEOM’

// }));

// feature.setStyle(‘classed rivers(different width)’);

// this.features.push(feature);

// this.updateFeatureLayer();

// }

 

/**

* 添加线

* @param line 线坐标

* @param style 线样式

*/

addLine(lines?, style?) {

if (!lines) {

if (!this.linesCache) {

return;

}

 

let arrLines = this.linesCache;

this.linesCache = [];

arrLines.forEach(linesObj => {

this.addLine(linesObj.lines, linesObj.style);

});

} else {

this.linesCache.push({

lines: lines,

style: style

});

for (let i = 0; i < lines.length; i++) {

let arr = lines[i];

let pointList = [];

if(!arr){

continue;

}

for (let j = 0; j < arr.length; j++) {

let p = arr[j];

let point;

if (this.type !== ‘gaode’) {

point = coordtransform.gcj02towgs84(p.longitude, p.latitude);

} else {

point = [p.longitude, p.latitude]

}

pointList.push(ol.proj.fromLonLat(point));

}

let feature = new ol.Feature(new ol.geom.LineString(pointList));

feature.setStyle(this[style + ‘LineStyle’]);

this.features.push(feature);

}

 

this.updateFeatureLayer();

}

}

 

updateFeatureLayer() {

debugger

let source = this.featureLayer.getSource();

if (source) {

source.clear();

source.addFeatures(this.features);

} else {

this.featureLayer.setSource(new ol.source.Vector({

features: this.features

}));

}

}

 

/**

* 切换底图

* @param type 类型

*/

switchMap(type) {

if (this.type === type) {

return;

}

this.type = type;

this.baseLayers.forEach(layer => {

let name = layer.get(‘name’);

if (name === type) {

layer.setVisible(true);

} else {

layer.setVisible(false);

if(name === ‘rvSegVector’) {

layer.setVisible(true);

}

}

});

 

let center = this.map.getView().getCenter();

center = ol.proj.toLonLat(center);

this.setCenter(center);

 

this.features = [];

this.addLine();

this.addPoint();

}

 

/**

* 交互平台地图配置

* @param pro

* @param zoomStop

* @param matrixIdWithProCode

*/

gridSetsParams(pro, zoomStop, matrixIdWithProCode) {

pro = (typeof pro) === ‘string’ ? pro : pro.getCode();

let projection = ol.proj.get(pro); // 由WMTS服务的数据源创建图层,WMTS数据源参数手动设置

let projectionExtent = projection.getExtent();

let size = ol.extent.getWidth(projectionExtent) / 256;

let resolutions = new Array();

let matrixIds = new Array();

for (let z = 0; z <= zoomStop; ++z) {

resolutions[z] = size / Math.pow(2, z);

matrixIds[z] = matrixIdWithProCode ? (pro + ‘:’ + z) : z;

}

return {

origin: ol.extent.getTopLeft(projectionExtent),

resolutions: resolutions,

matrixIds: matrixIds

}

}

}

 

二、html  页面

<div class=”m-container”>

<div style=”width:100%” id=”map”></div>

<div class=”m-switch”>

<ul>

<!–高德的底图,绘制的线会漂移–>

<!–<li class=”baselayer-gaode” (click)=”switchMap(‘gaode’)” title=”高德地图”><span>高德地图</span></li>–>

<li class=”baselayer-tdt_vector” [ngClass]=”{‘current’: mapType===’天地图矢量图’}” (click)=”switchMap(‘天地图矢量图’)” title=”天地图矢量图”><span>天地图矢量图</span></li>

<li class=”baselayer-vector” [ngClass]=”{‘current’: mapType===’vector’}” (click)=”switchMap(‘vector’)” title=”重庆市矢量图”><span>重庆市矢量图</span></li>

</ul>

</div>

</div>

 

三、ts中调用

 

/**

* 描述:[TB_WR_RV_REC][巡河记录]表的查看详情组件

* @version:1.0.0

* @author: gc

* @创建时间: 2017-05-25 18:22:35

*/

import { Component, OnInit, OnDestroy } from ‘@angular/core’;

import { ActivatedRoute } from ‘@angular/router’;

import { Router } from ‘@angular/router’;

import { WrRvRec } from ‘./wrRvRec.model’;

import { WrRvRecService } from ‘./wrRvRec.service’;

import { MapService } from ‘../shared/map/map.service’;

import { API_URL, FILE_URL } from ‘../app.constants’;

import { SessionStorageService } from ‘ng2-webstorage’;

import { WrRvLogMgmtDialogComponent } from “./wrRvLog-management-dialog.component”;

import { WrRvRecModalService } from “./wrRvRec-modal.service”;

 

@Component({

selector: ‘jhi-wrRvRec-mgmt-detail’,

styles:[`

:host >>> .col-button{

text-align:center;

}

:host >>> .col-button button{

margin:0.5rem 0;

}

:host >>> .modal-body.table {

position: relative;

-webkit-box-flex: 1;

-webkit-flex: 1 1 auto;

-ms-flex: 1 1 auto;

flex: 1 1 auto;

padding: 0px;

}

`],

templateUrl: ‘./wrRvRec-management-detail.component.html’

})

export class WrRvRecMgmtDetailComponent implements OnInit, OnDestroy {

 

private subscription: any;

wrRvRec: any;

rvRec : any;

rvLine:any;

wrRvLogList : any;

private urlval :any = `${FILE_URL}`;

mapType:string = ‘天地图矢量图’;

 

constructor(

private wrRvRecModalService: WrRvRecModalService,

private wrRvRecService: WrRvRecService,

private route: ActivatedRoute,

private mapService: MapService,

private router: Router,//路由

private $sessionStorage: SessionStorageService,

) {

}

 

ngOnInit() {

this.subscription = this.route.params.subscribe(params => {

this.load(params[‘id’]);

});

}

 

/**

* 通过id获取列表对象

* @param id

*/

load (id) {

this.wrRvRecService.findByRecId(id).subscribe(wrRvRec => {

console.log(wrRvRec);

this.wrRvRec = wrRvRec;

this.rvRec = this.wrRvRec.rvRec;

this.rvLine = this.wrRvRec.rvLine;

if(this.rvLine != null && this.rvLine.linePList) {

this.rvRec.points = this.rvLine.linePList == null?’0′:this.rvLine.linePList.length;//巡查点数量

} else {

this.rvRec.points = ‘0’;

}

if(this.rvRec != null && this.rvRec.pids) {

this.rvRec.pids = this.rvRec.pids == null ?’0′:this.rvRec.pids.split(‘,’).length;//已经巡查点的数量

} else {

this.rvRec.pids = ‘0’;

}

if(this.rvRec != null && this.rvRec.wrRvLogList) {

this.rvRec.shangbao =this.rvRec.wrRvLogList == null?’0′: this.rvRec.wrRvLogList.length;//上报数量

} else {

this.rvRec.shangbao = ‘0’;

}

 

 

this.wrRvLogList = this.rvRec ==null || this.rvRec.wrRvLogList==null?[]:this.rvRec.wrRvLogList;

// p-lightbox标签用到的数组 可以放大显示图片

if (this.wrRvLogList) {

let index:number = 1;

for (let m = 0; m<this.wrRvLogList.length; m++) {

let ImageList: any = [];

if (this.wrRvLogList[m].wrRvFileList != null) {

for (let n=0; n<this.wrRvLogList[m].wrRvFileList.length; n++) {

if (this.wrRvLogList[m].wrRvFileList[n].tp == 1) {

let file: any = {};

file.source = this.urlval + this.wrRvLogList[m].wrRvFileList[n].flPath; // 实际图

file.thumbnail = this.urlval + this.wrRvLogList[m].wrRvFileList[n].thu; // 缩略图

file.title = ”;

 

ImageList.push(file);

}

}

}

this.wrRvLogList[m].ImageList = ImageList;

 

if(this.wrRvLogList[m].eventNm == null) { //巡查点名称为空的,自定义名称, 巡河上报问题1.2….

this.wrRvLogList[m].eventNm = ‘巡河上报问题’+index;

index +=1;

}

if(this.wrRvLogList[m].eventTpNm == null) {//部件类型为空

let description:string = this.wrRvLogList[m].description;

if(description != null && description !=”) {

if(description.indexOf(‘公示牌’)>-1) {

this.wrRvLogList[m].eventTpNm = ‘公示牌’;

}

if(description.indexOf(‘水面’)>-1) {

this.wrRvLogList[m].eventTpNm = ‘水面’;

}

if(description.indexOf(‘排污口’)>-1) {

this.wrRvLogList[m].eventTpNm = ‘排污口’;

}

if(description.indexOf(‘取水口’)>-1) {

this.wrRvLogList[m].eventTpNm = ‘取水口’;

}

if(description.indexOf(‘界桩界碑’)>-1) {

this.wrRvLogList[m].eventTpNm = ‘界桩界碑’;

}

if(description.indexOf(‘河岸’)>-1) {

this.wrRvLogList[m].eventTpNm = ‘河岸’;

}

}

}

}

}

//规划线路

let lines = this.rvLine== null || this.rvLine.tra==null ? [] : JSON.parse(this.rvLine.tra.toString());

let points = [];

if(this.rvLine != null && this.rvLine.linePList){

for(let i = 0; i<this.rvLine.linePList.length;i++){

let point:any = {};

point.longitude = this.rvLine.linePList[i].lon;

point.latitude = this.rvLine.linePList[i].lat;

points.push(point);

}

}

//巡河轨迹

let guiJiLines = this.rvRec== null || this.rvRec.tra==null ? [] : JSON.parse(this.rvRec.tra.toString());

let guiJipoints = [];

if(this.rvRec != null && this.rvRec.linePList){

for(let i = 0; i<this.rvRec.linePList.length;i++){

let point:any = {};

point.longitude = this.rvRec.linePList[i].lon;

point.latitude = this.rvRec.linePList[i].lat;

guiJipoints.push(point);

}

}

//中心点设置

let centerP = this.rvLine == null || this.rvLine.staTra==null ? {} : JSON.parse(this.rvLine.staTra.toString());

// points.push(centerP);

// this.mapService.init(lines, points,guiJiLines,guiJipoints, centerP);

// console.log(points);

this.mapService.init(this.rvRec.rvSegId);

if(centerP.longitude && centerP.latitude){

this.mapService.setCenter([centerP.longitude, centerP.latitude]);

} else {

for (let i = 0; i < guiJiLines.length; i++) {

let element = guiJiLines[i];

if(element) {

this.mapService.setCenter([element[0].longitude, element[0].latitude]);

break;

}

}

}

if(lines && lines.length > 0) {

this.mapService.addLine(lines, ‘expect’);

}

if(points && points.length > 0) {

this.mapService.addPoint(points, ‘expect’);

}

if(guiJiLines && guiJiLines.length > 0) {

this.mapService.addLine(guiJiLines, ‘real’);

}

if(guiJipoints && guiJipoints.length > 0) {

this.mapService.addPoint(guiJipoints, ‘real’);

}

});

 

}

 

/**

* 查看问题详情

*/

lookWrRvLog(wrRvLog){

this.$sessionStorage.store(‘wrRvRecLog’,wrRvLog);

// this.router.navigate([‘/’, { outlets: { popup: ‘wrRvRec-RvLog’} }]);

this.wrRvRecModalService.openRvLog(WrRvLogMgmtDialogComponent);

}

 

previousState() {

window.history.go(-1);

}

 

switchMap(type) {

this.mapType = type;

this.mapService.switchMap(type);

}

 

ngOnDestroy() {

this.subscription.unsubscribe();

}

 

}

转载自:https://blog.csdn.net/zhangbo19920918/article/details/81261384

You may also like...