angular中使用openlayers开发地图

一、框架版本

angular:6.1.10
openlayers:4.6.5

二、添加相应的包

在package.json文件中添加以下内容

{
    "dependencies": {
        "openlayers": "^4.6.5"
    },
    "devDependencies": {
        "@types/openlayers": "^4.6.12"
    }
}

三、新建地图组件

新建地图组件map-ol,包括以下内容:

hy-map-ol.component.html



hy-map-ol.component.less

/* 缩放 */
.map-controll {
    position: absolute;
    width: 54px;
    height: 120px;
    right: 5px;
    bottom: 75px;
    z-index: 998;
    overflow: hidden;
}

.zoom-in, .zoom-out {
    box-shadow: 1px 2px 1px rgba(0, 0, 0, .15);
    width: 26px;
    height: 26px;
    margin-left: 13px;
    margin-top: 5px;
    background-color: #FFF;
    cursor: pointer;
}

.zoom-in .zoom-btn, .zoom-out .zoom-btn {
    cursor: pointer;
}

/* 渲染 */
.map-type {
    position: absolute;
    width: 100px;
    height: 65px;
    right: 5px;
    bottom: 5px;
    z-index: 5;
    overflow: hidden;
    cursor: pointer;
}

.map-type:hover {
    width: auto;
}

.map-type .item img {
    width: 80px;
    height: 60px;
}

.map-type .item {
    margin: 2px 1px 1px 10px;
    width: 80px;
    height: 60px;
    float: left;
    display: none;
}

.map-type:hover .item, .map-type .item.active {
    display: block;
}

.map-type .item .type-name {
    position: absolute;
    margin-top: 40px;
    text-align: center;
    height: 20px;
    line-height: 20px;
    width: 80px;
    color: white;
    font-size: 12px;
    background: rgba(0, 0, 0, 0.5);
}

/* 经纬度显示 */
.mouse-position-wrapper {
    width: 245px;
    height: 30px;
    color: #000000;
    position: absolute;
    right: 0;
    bottom: 6px;
    z-index: 15;
}

/* 点筛选框 */
.map-tool {
    position: absolute;
    top: 20px;
    left: 51px;
    z-index: 15;
}

hy-map-ol.component.ts

import {AfterViewInit, Component, ElementRef, ViewChild} from "@angular/core";
import * as ol from "openlayers";
import {olx} from "openlayers";
import WMTSOptions = olx.source.WMTSOptions;
import ImageArcGISRestOptions = olx.source.ImageArcGISRestOptions;
import {ZapiService} from "@core/common/zapi/zapi.service";


@Component({
    selector: 'hy-map-ol',
    templateUrl: './hy-map-ol.component.html',
    styleUrls: ['./hy-map-ol.component.less'],
})

export class HyMapOlComponent implements AfterViewInit {
    @ViewChild('mapol') mapol;

    constructor(public zapi: ZapiService) {
    }

    ngAfterViewInit(): void {
        this.init();
        this.addPoints(this.dList);
    }

    cProjection = 'EPSG:4326';

    asmt = 5;
    selectedMapType = 0;

    cvaW = false;

    cond = {dType: ''};

    dList: any;

    map: any;

    // methods
    init() {
        let centerP = {longitude: 105.8, latitude: 30.578};

        let imageArcGisOpt: ImageArcGISRestOptions = {
            hidpi: false,
            ratio: 1,
            url: url
        } as ImageArcGISRestOptions;
        this.map = new ol.Map({
            target: "mapol",
            layers: [
                this.wmts("http://t0.tianditu.com/ter_c/wmts", "ter_c", true),//晕渲图
                this.wmts("http://t0.tianditu.com/img_c/wmts", "img_c", false),//卫星图
                this.wmts("http://t0.tianditu.com/vec_c/wmts", "vec_c", false),//区划图
                this.xyz("http://mt3.google.cn/vt/lyrs=t@131,r@216000000&hl=zh-CN&gl=CN&src=app&x={x}&y={y}&z={z}&s=Gal", "google_a", false),
                this.xyz("http://mt2.google.cn/vt/lyrs=y&hl=zh-CN&gl=CN&src=app&x={x}&y={y}&z={z}&s=G", "google_b", false),
                this.xyz("http://t3.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}", "cva_w", false),
                new ol.layer.Vector({
                    source: new ol.source.Vector()
                })
            ],
            controls: ol.control.defaults({
                zoom: false
            }).extend([
                new ol.control.MousePosition({
                    coordinateFormat: ol.coordinate.createStringXY(4),
                    projection: this.cProjection,
                    className: 'custom-mouse-position',
                    target: document.getElementById('mouse-position')
                }),
                new ol.control.ScaleLine({}),
            ]),
            view: new ol.View({
                center: [centerP.longitude, centerP.latitude],
                projection: ol.proj.get(this.cProjection),
                zoom: 6,
                minZoom: 4,
                maxZoom: 20
            })
        });
    }

    /**
     * 放大,缩小
     * @param zoomNo 变化等级,正数放大,负数缩小
     */
    zoomInOut(zoomNo: number) {
        let view = this.map.getView();
        let zoom = view.getZoom();
        view.setZoom(zoom + zoomNo);
    }

    /**
     * 切换图层
     * @param no 序号
     */
    changeMapType(no: number) {
        this.selectedMapType = no;
        let layers = this.map.getLayers().getArray();
        for (let i = 0; i < this.asmt; i++) {
            let layer = layers[i];
            let s = layer.getProperties();
            if (i == no) {
                layer.setVisible(true);
            } else {
                layer.setVisible(false);
            }

        }
    }

    /**
     * 显示/地名标注
     * @param no 序号
     */
    showCvaW(no: number) {
        this.cvaW = !this.cvaW;
        this.getLayerByIndex(no).setVisible(this.cvaW);
    }


    wmts(url, layerName, visible) {
        let projection = ol.proj.get(this.cProjection);
        let projectionExtent = projection.getExtent();
        let size = ol.extent.getWidth(projectionExtent) / 256;
        let resolutions = new Array(14);
        let matrixIds = new Array(14);
        for (let z = 0; z <= 14; ++z) {
            resolutions[z] = size / Math.pow(2, z);
            matrixIds[z] = z;
        }

        let wmtsOpt: WMTSOptions = {
            url: url,
            layer: layerName.split("_")[0],
            format: 'tiles',
            tileGrid: new ol.tilegrid.WMTS({
                origin: ol.extent.getTopLeft(projectionExtent),
                resolutions: resolutions,
                matrixIds: matrixIds,
            }),
            matrixSet: layerName.split("_")[1],
            style: 'default'
        } as WMTSOptions;
        return new ol.layer.Tile({
            visible: visible,
            source: new ol.source.WMTS(wmtsOpt)
        });
    }

    xyz(url, layerName, visible) {
        return new ol.layer.Tile({
            visible: visible,
            source: new ol.source.XYZ({
                url: url
            })
        });
    }

    getLayerByIndex(index: number) {
        let layers = this.map.getLayers().getArray();
        for (let i = 0; i < layers.length; i++) {
            if (i == index) {
                return layers[i];
            }
        }
    }

    /**
     * 点类型切换
     */
    changeDType() {
        this.addPoints(this.sList);
    }

    /**
     * 添加点
     */
    addPoints(dList) {
        let layers = this.map.getLayers().getArray();
        let layer = layers[layers.length - 1];
        let vector;
        if (layer.getSource() == null) {
            vector = new ol.source.Vector({});
        } else {
            vector = layer.getSource();
        }
        // 清理原点图层数据
        vector.clear();
        for (let i = 0; i < dList.length; i++) {
            let dData = dList[i];
            if (this.cond.dList != '' && this.cond.dList != dData.type) {
                continue;
            }

            let longitude = dData.longitude;
            let latitude = dData.latitude;
            if (!longitude || !latitude) {
                continue;
            }
            // 初始化一个新的点要素
            let point = new ol.Feature({
                geometry: new ol.geom.Point([longitude, latitude]),
            });
            point.setId(st.iid);

            //设置点的样式
            let style = new ol.style.Style({
                image: new ol.style.Icon({
                    src: "assets/image/map/" + dData.type + ".png"
                }),
                text: new ol.style.Text({
                    text: dData.name,
                    offsetY: 12,
                    font: "500 14px Microsoft YaHei",    //字体与大小
                    fill: new ol.style.Fill({    //文字填充色
                        color: '#333'
                    }),
                    stroke: new ol.style.Stroke({    //文字边界宽度与颜色
                        color: '#fff',
                        width: 3
                    })
                })
            });
            point.setStyle(style);
            vector.addFeature(point);
        }
        if (layer.getSource() == null) {
            layer.setSource(vector);
        }
    }
}

你可能感兴趣的:(angular中使用openlayers开发地图)