OpenLayers 要素标注

205 阅读4分钟

前言

要素标注是一个常用功能,就是将要素信息如名称等显示在地图上,方便查找和使用。在OpenLayers中要素标注很灵活,使用起来也很方便,可以修改标注样式以及标注权限。

1. 创建标注样式

在项目中创建文字标注样式和行政区样式,文字标注通过ol.style.Text类设置,可以设置字体、填充颜色和边线颜色;行政区样式通过填充属性和描边属性进行设置。OpenLayersColor属性可以设置成字符串"#2F4F4F"或者rgba(255, 255, 255, 0.6)或者直接设置成颜色值"red"

// 文字样式
const labelStyle new ol.style.Style({
    textnew ol.style.Text({
        font'12px Calibri,sans-serif',
        overflowtrue,
        // 填充色
        fillnew ol.style.Fill({
            color"#FAFAD2"
        }),
        // 描边色
        strokenew ol.style.Stroke({
            color"#2F4F4F",
            width3,
        }),
    })
})
// 行政区样式
const regionStyle new ol.style.Style({
    fillnew ol.style.Fill({
        // color'rgba(255, 255, 255, 0.6)',
        color: [2302302500.25],
    }),
    strokenew ol.style.Stroke({
        color"#00FFFF",
        width1.25,
    }),
})

2. 设置样式标注

通过fetch函数获取行政区GeoJSON数据,创建行政区矢量数据源和图层,在style函数中设置标注文字并返回样式对象。最后调整视图中心点和缩放级别,使地图居中显示。可以通过两种方式创建矢量数据源

  • 设置format参数和url参数
  • 设置features参数,并通过GeoJSON方法readFeatures 读取数据。
fetch(JSON_URL)
.then(response => response.json())
.then(result => {
    console.log(result)
    const layer = new ol.layer.Vector({
        sourcenew ol.source.Vector({
            // url: JSON_URL,
            // format: new ol.format.GeoJSON(),
            features: (new ol.format.GeoJSON()).readFeatures(result)
        }),
        // 设置图层背景色
        // background: "white",
        stylefunction (feature) {
            const label = feature.get("name").split(" ").join("n")
            labelStyle.getText().setText(label)
            return style
        },
        // 开启标注优先级
        decluttertrue
    })
    map.addLayer(layer)
    map.getView().setCenter([101.48510625.008643])
    map.getView().setZoom(6.5)
})

3. 完整代码

其中libs文件夹下的包需要更换为自己下载的本地包或者引用在线资源。本示例引用了layui组件,请自行替换。

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>OpenLayers 要素标注</title>
    <meta charset="utf-8" />

    <script src="../../../libs/proj4.js"></script>
    <script src="../../../js/ol9.2.4.js"></script>
    <script src="../../../libs/layui/layui.js"></script>

    <link rel="stylesheet" href="../../../css/ol9.2.4.css">
    <link rel="stylesheet" href="../../../libs/layui/css/layui.css">

    <script src="../../../libs/js/geotiff.min.js"></script>
    <style>
        * {
            padding0;
            margin0;
            font-size14px;
            font-family'微软雅黑';
        }
        .clearfix::after {
            display: block;
            content"";
            clear: both;
        }
        html,
        body {
            width100%;
            height100%;
        }

        #map {
            position: absolute;
            top50px;
            bottom0;
            width100%;
        }

        #top-content {
            position: absolute;
            width100%;
            height50px;
            line-height50px;
            backgroundlinear-gradient(135deg#ff00cc#ffcc00#00ffcc#ff0066);
            color#fff;
            text-align: center;
            font-size32px;
        }

        #top-content span {
            font-size32px;
        }

        #layer-container {
            position: absolute;
            top15%;
            left20px;
            width30%;
            bottom5%;
            background#fff;
            color#fff;
            border1px solid #ddd;
            border-radius2.5px;
        }

    </style>
</head>

<body>
    <div id="top-content">
        <span>OpenLayers 要素标注</span>
    </div>
    <div id="map" title="地图显示"></div>
</body>

</html>

<script>
    //地图投影坐标系
    const projection = ol.proj.get('EPSG:3857');
    //==============================================================================//
    //============================天地图服务参数简单介绍==============================//
    //================================vec:矢量图层==================================//
    //================================img:影像图层==================================//
    //================================cva:注记图层==================================//
    //======================其中:_c表示经纬度投影,_w表示球面墨卡托投影================//
    //==============================================================================//
    const TDTImgLayer = new ol.layer.Tile({
        title"天地图影像图层",
        sourcenew ol.source.XYZ({
            url"http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=",
            attibutions"天地图影像描述",
            crossOrigin"anoymous",
            wrapXfalse
        })
    })
    const TDTImgCvaLayer = new ol.layer.Tile({
        title"天地图影像注记图层",
        sourcenew ol.source.XYZ({
            url"http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=",
            attibutions"天地图注记描述",
            crossOrigin"anoymous",
            wrapXfalse
        })
    })
    const map = new ol.Map({
        target"map",
        loadTilesWhileInteractingtrue,
        viewnew ol.View({
            center: ol.proj.fromLonLat([102.84586425.421639]),
            zoom8,
            worldsWrapfalse,
            minZoom1,
            maxZoom20,
            projection'EPSG:4326',
        }),
        layers: [TDTImgLayer],
        // 地图默认控件
        controls: ol.control.defaults.defaults({
            zoomfalse,
            attributiontrue,
            rotatetrue
        })
    })

    // 文字样式
    const labelStyle = new ol.style.Style({
        textnew ol.style.Text({
            font'12px Calibri,sans-serif',
            overflowtrue,
            // 填充色
            fillnew ol.style.Fill({
                color"#FAFAD2"
            }),
            // 描边色
            strokenew ol.style.Stroke({
                color"#2F4F4F",
                width3,
            }),
        })
    })
    // 行政区样式
    const regionStyle = new ol.style.Style({
        fillnew ol.style.Fill({
            // color: 'rgba(255, 255, 255, 0.6)',
            color: [2302302500.25],
        }),
        strokenew ol.style.Stroke({
            color"#00FFFF",
            width1.25,
        }),
    })

    const style = [labelStyle, regionStyle]

    const JSON_URL = "https://geo.datav.aliyun.com/areas_v3/bound/530000_full.json"

    fetch(JSON_URL)
        .then(response => response.json())
        .then(result => {
            console.log(result)
            const layer = new ol.layer.Vector({
                sourcenew ol.source.Vector({
                    // url: JSON_URL,
                    // format: new ol.format.GeoJSON(),
                    features: (new ol.format.GeoJSON()).readFeatures(result)
                }),
                // 设置图层背景色
                // background: "white",
                stylefunction (feature) {
                    // 标注name字段
                    const label = feature.get("name").split(" ").join("n")
                    labelStyle.getText().setText(label)
                    return style
                },
                decluttertrue
            })
            map.addLayer(layer)
            // 设置视图中心点和缩放级别
            map.getView().setCenter([101.48510625.008643])
            map.getView().setZoom(6.5)
        })
</script>

OpenLayers示例数据下载,请回复关键字:ol数据

全国信息化工程师-GIS 应用水平考试资料,请回复关键字:GIS考试

【GIS之路】 已经接入了智能助手,欢迎关注,欢迎提问。

欢迎访问我的博客网站-长谈GIShttp://shanhaitalk.com

都看到这了,不要忘记点赞、收藏 + 关注

本号不定时更新有关 GIS开发 相关内容,欢迎关注 !