Search code examples
mapboxmultilingual

How can I default labels to English when not found in other language in MapBox?


I'm attempting to support Spanish users of my map, and have figured out how to set all the label layers to a certain language:

const langCode = Math.random() < 0.5 ? "en" | "es";
const layers = this.mapbox.getStyle().layers.filter((it) => it.id.includes("label"))
layers.forEach((layer) => {
  this.mapbox.setLayoutProperty(layer.id, "text-field", [
    "get",
    `name_${langCode}`
  ])
});

The issue is that half the map ends up empty in Spanish mode. What I would like is for English to be the default back-up if nothing else exists. How can I do this?


Solution

  • You can use coalesce to set up default value to english

    https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/#coalesce https://docs.mapbox.com/mapbox-gl-js/example/fallback-image/

    I guess the code would look like this

    layers.forEach((layer) => {
      this.mapbox.setLayoutProperty(layer.id, "text-field", [
        "coalesce",
        ["get", `name_${langCode}`],
        // default to english if not found
        ["get", `name_en`],
      ])
    })