Localizing MapLibre GL map

MapLibre example, that shows how to change map language dynamically

by Geoapify

HTML

<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/maplibre-gl.css">
<script src="https://unpkg.com/[email protected]/dist/maplibre-gl.js"></script>
<div class="language-selector">
  <select onchange="localizeMap(this.value)">
    <option value="en">English</option>
    <option value="es">Spanish</option>
    <option value="fr">French</option>
    <option value="pt">Portuguese</option>
    <option value="de">German</option>
    <option value="ru">Russian</option>
    <option value="ja">Japanese</option>
    <option value="tr">Turkish</option>
    <option value="ar">Arabic</option>
    <option value="zh">Chinese</option>
    <option value="hi">Hindi</option>
    <option value="el">Greek</option>
  </select>
</div>
<div id="my-map"></div>

CSS

body {
      margin: 0;
      padding: 0;
    }

    #my-map {
      position: absolute;
      top: 0;
      bottom: 0;
      width: 100%;
    }
    
    .language-selector {
      position: absolute;
      top: 10px;
      left: 10px;
      z-index: 100;
    }

JavaScript

// The API Key provided is restricted to JSFiddle website
// Get your own API Key on https://myprojects.geoapify.com
var myAPIKey = "6dc7fb95a3b246cfa0f3bcef5ce9ed9a";

var map = new maplibregl.Map({
  container: 'my-map',
  style: `https://maps.geoapify.com/v1/styles/osm-bright/style.json?apiKey=${myAPIKey}`,
});
map.addControl(new maplibregl.NavigationControl());

let mapTextLayers = [];

map.on('load', function() {
  mapTextLayers = map.getStyle().layers.filter(layer => layer.type === 'symbol' && map.getLayoutProperty(layer.id, 'text-field') && map.getLayoutProperty(layer.id, 'text-field').includes('name')).map(layer => layer.id);

  localizeMap("en");
});

function localizeMap(lang) {

  if (!mapTextLayers.length) {
    // map is not loaded yet, do nothing
    return;
  }

  mapTextLayers.forEach(layerId => {
    map.setLayoutProperty(layerId, 'text-field', ['coalesce', ['get', `name:${lang}`],
      ['concat', ['get', `name:latin`], '\n', ['get', `name:nonlatin`]]
    ])
  })

}