OpenLayers 个性化标注

125 阅读5分钟

前言

GIS开发中,地图标注是一个重要功能,如何实现美观、高效的文本标注是一个值得思考的问题。在进行地图标注时,某些情况下需要标注多个字段信息,可以实现左右分隔标注或者上下标注。而在OpenLayers中已经给我们提供了这种标注的实现方式————富文本标注

1. 数据准备

在进行数据标注前,需要准备相应的地图数据,在本文中以GeoJSON数据为例进行讲解。通过下载云南省行政区范围GeoJSON数据,然后将云南省16个州市的GDP数据写入属性信息中进行展示。数据结构如下。
如果你还不知道怎么下载GeoJSON数据源请参考文章:GeoJSON 数据源站介绍如果你想进一步了解GeoJSON数据请参考文章:GeoJSON 数据简介

2. 创建标注样式

在项目中创建文字标注样式和行政区样式,文字标注通过样式类(Style)属性ol.style.Text类设置,可以设置字体、填充颜色和边线颜色;行政区样式通过样式类(Style)填充属性和描边属性进行设置。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: [2302302500.25],
    }),
    strokenew ol.style.Stroke({
        color"#00FFFF",
        width1.25,
    }),
})

3. 设置文本标注

在矢量图层中创建矢量数据源,将矢量数据源的format属性设置为new ol.format.GeoJSON(),并且设置url属性指向下载的GeoJSON文件存储路径,然后设置图层标注样式。

const JSON_URL = "../../data/geojson/yn_region.json"
const layer = new ol.layer.Vector({
    sourcenew ol.source.Vector({
        urlJSON_URL,
        formatnew ol.format.GeoJSON(),
    }),
    stylefunction (feature) {
        const label = feature.get("name").split(" ").join("n")
        labelStyle.getText().setText([
            label,
            '16px sans-serif',
            'n',
            '',
            '————',
            '',
            'n',
            '',
            `${feature.get("GDP")}`,
            "12px bold italic Calibri",
            `(${feature.get("unit")})`,
            '12px sans-serif',
        ])
        return style
    },
    decluttertrue
})

在如上方设置完成样式标注后,可以看到富文本标注更加丰富、强大的标注能力。在本例中将实现如箭头右图所示上下分隔标注内容。将行政区名称显示在上方,中间用"——"分隔,下方标注内容为GDP数值和单位。
现在讲一下在OpenLayers开发工作中如何设置富文本标注。富文本标注的实现应使用样式函数来完成,该函数具有一个Feature类型的参数为feature,即要标注的要素。在该要素中,可以获取要标注的文本内容,如例子中的行政区名称(name)、GDP、标注单位(unit)。

然后通过setText方法设置标注文本,该方法可以接受字符串、字符串数组类型的文本。要实现富文本标注,需要传入字符串数组。
可以将文本标注内容划分为组,如下图在设置行政区名称和GDP数值标注时将标注内容划分为6组。每一组内容又可以划分为上下两个要素,前一个要素是标注内容,后一个要素是标注样式,该标注样式为字体值,包括字体大小、使用字体、是否加粗、是否倾斜等。如若需要换行,实现文本上下标注,则需要设置如下图2、3组内容。前一个要素标注内容为换行符'n',后一个标注样式置空即可。

stylefunction (feature) {
    const label = feature.get("name").split(" ").join("n")
    labelStyle.getText().setText([
        label,
        '16px sans-serif',
        'n',
        '',
        '————',
        '',
        'n',
        '',
        `${feature.get("GDP")}`,
        "12px bold italic Calibri",
        `(${feature.get("unit")})`,
        '12px sans-serif',
    ])
    return style
},

4. 完整代码

其中libs文件夹下的包需要更换为自己下载的本地包或者引用在线资源。

<!DOCTYPE html>
<html>

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

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

    <script src="../../js/config.js"></script>
    <script src="../../libs/js/ol9.2.4.js"></script>
    <style>
        * {
            padding0;
            margin0;
            font-size14px;
            font-family'微软雅黑';
        }

        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;
        }
    </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=" + TDTTOKEN,
            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=" + TDTTOKEN,
            attibutions"天地图注记描述",
            crossOrigin"anoymous",
            wrapXfalse
        })
    })
    const map = new ol.Map({
        target"map",
        loadTilesWhileInteractingtrue,
        viewnew ol.View({
            center: [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: [2302302500.25],
        }),
        strokenew ol.style.Stroke({
            color"#00FFFF",
            width1.25,
        }),
    })

    // 标注样式数组
    const style = [labelStyle, regionStyle]

    // 行政区数据
    const JSON_URL = "../../data/geojson/yn_region.json"

    const layer = new ol.layer.Vector({
        sourcenew ol.source.Vector({
            urlJSON_URL,
            formatnew ol.format.GeoJSON(),
        }),
        stylefunction (feature) {
            const label = feature.get("name").split(" ").join("n")
            labelStyle.getText().setText([
                label,
                '16px sans-serif',
                'n',
                '',
                '————',
                '',
                'n',
                '',
                `${feature.get("GDP")}`,
                "12px bold italic Calibri",
                `(${feature.get("unit")})`,
                '12px sans-serif',
            ])
            return style
        },
        decluttertrue
    })
    map.addLayer(layer)
    map.getView().setCenter([101.48510625.008643])
    map.getView().setZoom(6.5)

</script>