Last active
December 9, 2023 01:25
-
-
Save elygeo/7e36a29935042679dfa3bd4f1982ecad to your computer and use it in GitHub Desktop.
Add language config to Mapbox Standard style
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>Configure style language</title> | |
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no"> | |
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/v3.0.1/mapbox-gl.css"> | |
<script src="https://api.mapbox.com/mapbox-gl-js/v3.0.1/mapbox-gl.js"></script> | |
<style> | |
body { margin: 0; padding: 0; } | |
#map { position: absolute; top: 0; bottom: 0; width: 100%; } | |
</style> | |
</head> | |
<body> | |
<div id="map"></div> | |
<script> | |
mapboxgl.accessToken = 'YOUR_MAPBOX_ACCESS_TOKEN'; | |
const url = `https://api.mapbox.com/styles/v1/mapbox/standard?access_token=${mapboxgl.accessToken}`; | |
const schema = { | |
type: "string", | |
default: "name_ar", | |
values: [ | |
"name_en", | |
"name_de", | |
"name_fr", | |
"name_es", | |
"name_pt", | |
"name_it", | |
"name_ru", | |
"name_vi", | |
"name_ja", | |
"name_ko", | |
"name_zh-Hans", | |
"name_zh-Hant", | |
"name_ar", | |
], | |
}; | |
function replace(pattern, replacement, elem) { | |
if (Array.isArray(elem)) { | |
return elem.map(replace.bind(null, pattern, replacement)); | |
} | |
return pattern.test(elem) ? replacement : elem; | |
} | |
function configLanguage(layers, replacement) { | |
return layers.map((layer) => { | |
const original = layer.layout && layer.layout["text-field"]; | |
if (original) { | |
const updated = replace(/name_\S+/, replacement, original); | |
return { ...layer, layout: { ...layer.layout, "text-field": updated } }; | |
} | |
return layer; | |
}); | |
} | |
fetch(url) | |
.then((resp) => resp.json()) | |
.then((style) => { | |
style.schema.lang = schema; | |
style.layers = configLanguage(style.layers, ["config", "lang"]); | |
new mapboxgl.Map({ style, container: "map" }); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment