OpenLayers 创建渐变色地图

146 阅读6分钟

前言

在OpenLayers开发中,对于矢量图层,可以使用渐变色进行渲染,适合主题地图展示。在开发中结合canvas画布上下文,开发者可以通过定义颜色起点和终点,或使用插值算法生成平滑的渐变过渡。设置图层填充样式为渐变色即可实现,从而满足多样化的可视化需求。

1. 创建标注样式

在例子中加载云南省行政区GeoJSON数据,然后对标注文本设置文字样式,对行政区设置透明填充色。defaultFillColor为默认填充色,在恢复填充色时使用。

// 文字样式
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 defaultFillColor = [2302302500.25]
const regionStyle new ol.style.Style({
    fillnew ol.style.Fill({
        color: defaultFillColor,
    }),
    strokenew ol.style.Stroke({
        color"#00FFFF",
        width1.25,
    }),
})

2. 创建画布上下文

在OpenLayers中通过canvas渲染引擎实现渐变色地图,需要创建canvas元素,然后通过getContext方法获取2d上下文。

// 创建canvas元素并获取画布上下文
const canvas = document.createElement("canvas")
const ctx = canvas.getContext("2d")

3. 创建渐变色条带

渐变色条带可以使用ctx.createLinearGradient方法创建,达到线性渐变的效果。在例子中展示彩虹渐变、蓝色渐变、绿色渐变以及多色渐变四种渐变色条带,可以通过点击渐变按钮进行渐变色切换,点击清除按钮恢复地图默认填充色。值得注意的是在改变地图填充渐变色的时候,需要紧接着调用矢量图层changed方法进行渲染,才能立刻看到渐变填充的可视化效果。

const changeColor = function (colorType) {
    switch (colorType) {
        case "rainbow":
            // 彩虹渐变
            ctx.clearRect(001024 * ol.has.DEVICE_PIXEL_RATIO, 0)
            const gradiant = ctx.createLinearGradient(001024 * ol.has.DEVICE_PIXEL_RATIO, 0)
            gradiant.addColorStop(0"red")
            gradiant.addColorStop(1 / 6"orange")
            gradiant.addColorStop(2 / 6"yellow")
            gradiant.addColorStop(3 / 6"green")
            gradiant.addColorStop(4 / 6"aqua")
            gradiant.addColorStop(5 / 6"blue")
            gradiant.addColorStop(1"purple")
            regionStyle.getFill().setColor(gradiant)
            layer.changed()
            break
        case "blue":
            // 蓝色渐变
            ctx.clearRect(001024 * ol.has.DEVICE_PIXEL_RATIO, 0)
            const blueGradiant = ctx.createLinearGradient(001024 * ol.has.DEVICE_PIXEL_RATIO, 0)
            blueGradiant.addColorStop(0"#eff3ff")
            blueGradiant.addColorStop(1 / 6"#c6dbef")
            blueGradiant.addColorStop(2 / 6"#9ecae1")
            blueGradiant.addColorStop(3 / 6"#6baed6")
            blueGradiant.addColorStop(4 / 6"#4292c6")
            blueGradiant.addColorStop(5 / 6"#2171b5")
            blueGradiant.addColorStop(6 / 6"#084594")
            regionStyle.getFill().setColor(blueGradiant)
            layer.changed()
            break
        case "green":
            // 绿色渐变
            ctx.clearRect(001024 * ol.has.DEVICE_PIXEL_RATIO, 0)
            const greenGradiant = ctx.createLinearGradient(001024 * ol.has.DEVICE_PIXEL_RATIO, 0)
            greenGradiant.addColorStop(0"#edf8fb")
            greenGradiant.addColorStop(1 / 6"#ccece6")
            greenGradiant.addColorStop(2 / 6"#99d8c9")
            greenGradiant.addColorStop(3 / 6"#66c2a4")
            greenGradiant.addColorStop(4 / 6"#2ca25f")
            greenGradiant.addColorStop(5 / 6"#006d2c")
            greenGradiant.addColorStop(6 / 6"#005824")
            regionStyle.getFill().setColor(greenGradiant)
            layer.changed()
            break
        case "multiColor":
            // 多色渐变
            ctx.clearRect(001024 * ol.has.DEVICE_PIXEL_RATIO, 0)
            const multiColorGradiant = ctx.createLinearGradient(001024 * ol.has.DEVICE_PIXEL_RATIO, 0)
            multiColorGradiant.addColorStop(0"#edf8fb")
            multiColorGradiant.addColorStop(1 / 6"#bfd3e6")
            multiColorGradiant.addColorStop(2 / 6"#9ebcda")
            multiColorGradiant.addColorStop(3 / 6"#8c96c6")
            multiColorGradiant.addColorStop(4 / 6"#8c6bb1")
            multiColorGradiant.addColorStop(5 / 6"#88419d")
            multiColorGradiant.addColorStop(6 / 6"#6e016b")
            regionStyle.getFill().setColor(multiColorGradiant)
            layer.changed()
            break
        case "none":
            // 清除渐变
            regionStyle.getFill().setColor(defaultFillColor)
            layer.changed()
            removeAllActiveClass(".color-ul""active")
            break
    }
}

4. 渐变色切换

通过事件委托机制切换渐填充颜色,并且高亮点击按钮。使用这种方式只需在父元素上绑定点击事件,可以减少事件监听器数量和事件绑定次数,提高性能。

// 事件委托
const targetEle = document.querySelector(".color-ul")
targetEle.addEventListener('click', evt => {
    const targetEle = evt.target
    const colorType = targetEle.dataset.type
    if (colorType !== "none") {
        toogleAciveClass(targetEle, ".color-ul")
    }
    changeColor(colorType)
})

5. 完整代码

其中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="../../js/util.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;
        }

        .color-wrap {
            position: absolute;
            padding5px;
            top60px;
            left100px;
            background-color#ffcc00ad;
            border-radius2.5px;
        }

        .color-ul {
            list-style-type: none;
        }

        .color-ul::after {
            display: block;
            clear: both;
            content"";
        }

        .color-li {
            float: left;
            padding5px;
            margin0 5px;
            min-width50px;
            background-color: azure;
            background#cae4cf82;
            transition: background-color 10s ease-in-out 10s;
            text-align: center;
            border-radius2.5px;
        }

        .color-li:hover {
            cursor: pointer;
            color#fff;
            filterbrightness(120%);
            backgroundlinear-gradient(135deg#c850c0#4158d0);
        }

        .active {
            backgroundlinear-gradient(135deg#c850c0#4158d0);
        }
    </style>
</head>

<body>
    <div id="top-content">
        <span>OpenLayers 创建渐变色地图</span>
    </div>
    <div id="map" title=""></div>
    <div class="color-wrap">
        <ul class="color-ul">
            <li class="color-li" data-type="rainbow">彩虹渐变色</li>
            <li class="color-li" data-type="blue">蓝色渐变</li>
            <li class="color-li" data-type="green">绿色渐变</li>
            <li class="color-li" data-type="multiColor">多色渐变</li>
            <li class="color-li" data-type="none">清除</li>
        </ul>
    </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 defaultFillColor = [2302302500.25]
    const regionStyle = new ol.style.Style({
        fillnew ol.style.Fill({
            color: defaultFillColor,
        }),
        strokenew ol.style.Stroke({
            color"#00FFFF",
            width1.25,
        }),
    })

    // 创建canvas元素并获取画布上下文
    const canvas = document.createElement("canvas")
    const ctx = canvas.getContext("2d")

    const style = [labelStyle, regionStyle]
    const JSON_URL = "../../data/geojson/yn_region.json"

    const source = new ol.source.Vector({
        urlJSON_URL,
        formatnew ol.format.GeoJSON(),
    })
    const layer = new ol.layer.Vector({
        source: source,
        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)

    const changeColor = function (colorType) {
        switch (colorType) {
            case "rainbow":
                // 彩虹渐变
                ctx.clearRect(001024 * ol.has.DEVICE_PIXEL_RATIO0)
                const gradiant = ctx.createLinearGradient(001024 * ol.has.DEVICE_PIXEL_RATIO0)
                gradiant.addColorStop(0"red")
                gradiant.addColorStop(1 / 6"orange")
                gradiant.addColorStop(2 / 6"yellow")
                gradiant.addColorStop(3 / 6"green")
                gradiant.addColorStop(4 / 6"aqua")
                gradiant.addColorStop(5 / 6"blue")
                gradiant.addColorStop(1"purple")
                regionStyle.getFill().setColor(gradiant)
                layer.changed()
                break
            case "blue":
                // 蓝色渐变
                ctx.clearRect(001024 * ol.has.DEVICE_PIXEL_RATIO0)
                const blueGradiant = ctx.createLinearGradient(001024 * ol.has.DEVICE_PIXEL_RATIO0)
                blueGradiant.addColorStop(0"#eff3ff")
                blueGradiant.addColorStop(1 / 6"#c6dbef")
                blueGradiant.addColorStop(2 / 6"#9ecae1")
                blueGradiant.addColorStop(3 / 6"#6baed6")
                blueGradiant.addColorStop(4 / 6"#4292c6")
                blueGradiant.addColorStop(5 / 6"#2171b5")
                blueGradiant.addColorStop(6 / 6"#084594")
                regionStyle.getFill().setColor(blueGradiant)
                layer.changed()
                break
            case "green":
                // 绿色渐变
                ctx.clearRect(001024 * ol.has.DEVICE_PIXEL_RATIO0)
                const greenGradiant = ctx.createLinearGradient(001024 * ol.has.DEVICE_PIXEL_RATIO0)
                greenGradiant.addColorStop(0"#edf8fb")
                greenGradiant.addColorStop(1 / 6"#ccece6")
                greenGradiant.addColorStop(2 / 6"#99d8c9")
                greenGradiant.addColorStop(3 / 6"#66c2a4")
                greenGradiant.addColorStop(4 / 6"#2ca25f")
                greenGradiant.addColorStop(5 / 6"#006d2c")
                greenGradiant.addColorStop(6 / 6"#005824")
                regionStyle.getFill().setColor(greenGradiant)
                layer.changed()
                break
            case "multiColor":
                // 多色渐变
                ctx.clearRect(001024 * ol.has.DEVICE_PIXEL_RATIO0)
                const multiColorGradiant = ctx.createLinearGradient(001024 * ol.has.DEVICE_PIXEL_RATIO0)
                multiColorGradiant.addColorStop(0"#edf8fb")
                multiColorGradiant.addColorStop(1 / 6"#bfd3e6")
                multiColorGradiant.addColorStop(2 / 6"#9ebcda")
                multiColorGradiant.addColorStop(3 / 6"#8c96c6")
                multiColorGradiant.addColorStop(4 / 6"#8c6bb1")
                multiColorGradiant.addColorStop(5 / 6"#88419d")
                multiColorGradiant.addColorStop(6 / 6"#6e016b")
                regionStyle.getFill().setColor(multiColorGradiant)
                layer.changed()
                break
            case "none":
                // 清除渐变
                // ctx.clearRect(0, 0, 1024 * ol.has.DEVICE_PIXEL_RATIO, 0)
                regionStyle.getFill().setColor(defaultFillColor)
                layer.changed()
                removeAllActiveClass(".color-ul""active")
                break
        }
    }
    // 事件委托
    const targetEle = document.querySelector(".color-ul")
    targetEle.addEventListener('click'evt => {
        const targetEle = evt.target
        const colorType = targetEle.dataset.type
        if (colorType !== "none") {
            toogleAciveClass(targetEle, ".color-ul")
        }
        changeColor(colorType)
    })

</script>

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

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

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

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

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

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