[Mapbox GL]改变地图语言

本文介绍了一种使用Mapbox GL JS库实现的地图上国家标签动态语言切换的方法。通过监听按钮点击事件并调用map.setLayoutProperty方法,可以轻松地在多种语言间切换地图上的文字显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        使用.setLayoutProperty来动态转化语言


<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <title></title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.29.0/mapbox-gl.js'></script>
    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.29.0/mapbox-gl.css' rel='stylesheet' />
    <style>
        body { margin:0; padding:0; }
        #map { position:absolute; top:0; bottom:0; width:100%; }
    </style>
</head>
<body>

<style>
    #buttons {
        width: 90%;
        margin: 0 auto;
    }
    .button {
        display: inline-block;
        position: relative;
        cursor: pointer;
        width: 20%;
        padding: 8px;
        border-radius: 3px;
        margin-top: 10px;
        font-size: 12px;
        text-align: center;
        color: #fff;
        background: #ee8a65;
        font-family: sans-serif;
        font-weight: bold;
    }
</style>
<div id='map'></div>
<ul id="buttons">
    <li id='button-fr' class='button'>French</li>
    <li id='button-ru' class='button'>Russian</li>
    <li id='button-de' class='button'>German</li>
    <li id='button-es' class='button'>Spanish</li>
</ul>
<script>
mapboxgl.accessToken = '<your access token here>';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/light-v9',
    center: [16.05, 48],
    zoom: 2.9
});

document.getElementById('buttons').addEventListener('click', function(event) { /* DOM.addEventListener(type,callback(e)):为type事件添加监听器,此处是click事件 */
    var language = event.target.id.substr('button-'.length);/* event.target.id获取DOM的id,substr(start,length) 方法可在字符串中抽取从 start 下标开始的指定数目的字符 */
    // Use setLayoutProperty to set the value of a layout property in a style layer.
    // The three arguments are the id of the layer, the name of the layout property,
    // and the new property value.
    map.setLayoutProperty('country-label-lg', 'text-field', '{name_' + language + '}');
});

</script>

</body>
</html>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值