GithubHelp home page GithubHelp logo

mapbox / mapbox-gl-language Goto Github PK

View Code? Open in Web Editor NEW
186.0 186.0 51.0 243 KB

Switch language of your Mapbox GL JS style

Home Page: https://mapbox.github.io/mapbox-gl-language/

License: BSD 3-Clause "New" or "Revised" License

HTML 10.23% JavaScript 89.77%

mapbox-gl-language's Introduction

Mapbox GL Language Build Status npm

Adds support for switching the language of your map style in Mapbox GL JS maps.

Requires mapbox-gl-js. For other platforms, such as Android and iOS, see this help document.

Multiple language supported with style transforms

Automatic style transformations for different languages

Switch language based on user agent

Switch language based on user agent

Usage

mapbox-gl-language is a Mapbox GL JS plugin that you can easily add on top of your map.

When using a CDN

    <script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-language/v1.0.0/mapbox-gl-language.js'></script>

When using modules

Check how to use Mapbox GL JS in a module bundler.

npm install --save mapbox-gl @mapbox/mapbox-gl-language
import mapboxgl from 'mapbox-gl';
import MapboxLanguage from '@mapbox/mapbox-gl-language';

Example

mapboxgl.accessToken = 'YOUR_ACCESS_TOKEN';
const map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v10',
    center: [-77.0259, 38.9010],
    zoom: 9
});

// Add RTL support if you want to support Arabic
// mapboxgl.setRTLTextPlugin('https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.10.1/mapbox-gl-rtl-text.js');

const language = new MapboxLanguage();
map.addControl(language);

Check examples/ for more usage examples.

API

Table of Contents

MapboxLanguage

Create a new Mapbox GL JS plugin that modifies the layers of the map style to use the text-field that matches the browser language. As of Mapbox GL Language v1.0.0, this plugin no longer supports token values (e.g. {name}). v1.0+ expects the text-field property of a style to use an expression of the form ['get', 'name_en'] or ['get', 'name']; these expressions can be nested. Note that get expressions used as inputs to other expressions may not be handled by this plugin. For example:

["match",
  ["get", "name"],
  "California",
  "Golden State",
  ["coalesce",
    ["get", "name_en"],
    ["get", "name"]
  ]
]

Only styles based on Mapbox v8 styles are supported.

Parameters

  • options object Options to configure the plugin.

    • options.supportedLanguages Array<string>? List of supported languages
    • options.languageTransform Function? Custom style transformation to apply
    • options.languageField RegExp RegExp to match if a text-field is a language field (optional, default /^name_/)
    • options.getLanguageField Function? Given a language choose the field in the vector tiles
    • options.languageSource string? Name of the source that contains the different languages.
    • options.defaultLanguage string? Name of the default language to initialize style after loading.
    • options.excludedLayerIds Array<string>? Name of the layers that should be excluded from translation.

setLanguage

Explicitly change the language for a style.

Parameters
  • style object Mapbox GL style to modify
  • language string The language iso code

Returns object the modified style

Develop

Run the linter and watch for changes to rebuild with browserify.

npm install
npm run test

Languages

Showcasing the languages supported by Mapbox Streets.

Supported Styles

You can configure the plugin to support your own custom style using style transforms and custom language fields. By default, this plugin works best with official Mapbox styles or styles derived from official Mapbox styles. The styles must be based on Mapbox v8 styles:

  • mapbox://styles/mapbox/streets-v11
  • mapbox://styles/mapbox/outdoors-v11
  • mapbox://styles/mapbox/dark-v10
  • mapbox://styles/mapbox/light-v10
  • mapbox://styles/mapbox/satellite-streets-v9
  • mapbox://styles/mapbox/traffic-day-v2
  • mapbox://styles/mapbox/traffic-night-v2

mapbox-gl-language's People

Contributors

1ec5 avatar iamgreut avatar lukasmartinelli avatar manoharuss avatar phillip9587 avatar ryanhamley avatar sergei-zelinsky avatar stepankuzmin avatar thibaudlopez avatar wanghongrui avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mapbox-gl-language's Issues

cannot translate the whole map to Chinese

image

version:
"@mapbox/mapbox-gl-language": "^1.0.0",
"mapbox-gl": "^2.4.0"

styles:
'mapbox://styles/mapbox/light-v10'

this.mapInstance = this.swiperIdx.map((idx) => {
       const mapDom = document.querySelector(
              `${BASE_MAP_CLASS}${idx}`
       );

       return new mapboxgl.Map({
               container: mapDom,
               style: MAP_STYLE_LIGHT,
               minZoom: 1,
               zoom: 2,
       });
});

mapboxgl.setRTLTextPlugin(
        'https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.2.3/mapbox-gl-rtl-text.js'
);

this.mapInstance.map((map) => {
        map.addControl(new mapboxgl.NavigationControl(), 'top-right');

        map.addControl(
                new MapboxLanguage({
                       defaultLanguage: 'zh-Hans',
                })
        );
});

When set the language to 'zh-Hans', just translate China & Japan to Chinese, not whole world.

Support multiple languages in browser

Right now we take the first language and if not supported fall back to english.
But let's say in my case i first want something tried in german, then english, then french and then... until the local language.

So we could follow the user agent languages down until the first language our maps support and only then fall back to the default style language.

preferences

README.md Supported Styles

mapbox://mapbox-streets-v10
mapbox://mapbox-outdoors-v10
mapbox://mapbox-dark-v9
mapbox://mapbox-light-v9
mapbox://mapbox-satellite-streets-v9
mapbox://mapbox-traffic-day-v2
mapbox://mapbox-traffic-night-v2

It should be changed to

mapbox://styles/mapbox-streets-v10
mapbox://styles/mapbox-outdoors-v10
mapbox://styles/mapbox-dark-v9
mapbox://styles/mapbox-light-v9
mapbox://styles/mapbox-satellite-streets-v9
mapbox://styles/mapbox-traffic-day-v2
mapbox://styles/mapbox-traffic-night-v2

how to support zh language with new official template style?

this.mapInstance = new mapboxgl.Map({
        container: this.$refs.mapContainer,
        style: 'mapbox://styles/mapbox/streets-v11'
      })
      this.mapInstance.addControl(new MapboxLanguage({
        defaultLanguage: 'zh'
      }))

v10 is work well, but how to support v11?

Cannot set the map language

My website supports two languages: en, de. The currently selected language is set in the <html lang> attribute. The user may choose the language they want out of these two. The map should follow that as well.

Without this plugin, my maps are always in German, no matter what I do.

With this plugin, the map follows the browser's first language (if supported, see #4) but not the page content's language from the above attribute.

I saw that there is a setLanguage method but it requires a parameter style which is not documented. I have no idea what I should pass to it. So I cannot consider that method. And then there's nothing left. The plugin cannot set the map language to the page language.

Add Japanese, Korean to supported languages

The list of supported languages to automatically select from should be updated to include Japanese and Korean, which are now available via the name_ja and name_ko fields in Mapbox Streets v7:

this.supportedLanguages = options.supportedLanguages || ['en', 'es', 'fr', 'de', 'ru', 'zh', 'ar', 'pt'];

/ref mapbox/vector-tiles#54 mapbox/mapbox-gl-native#12283 mapbox/mapbox-plugins-android#566
/cc @lukasmartinelli @eschow

Release an up-to-date version (on NPM)

Hey, we love this package and would like to install it via the NPM registry, but the last release (0.9.2) is 10 months old and lacks features that have been merged into the master branch since.

Are you planning on releasing this some time soon? Is there anything I could help with?

Update peer dependency for new mapbox-gl version

Peer dependencies break npm install when working with the newest verison of mapbox-gl.

"peerDependencies": {
        "mapbox-gl": ">=0.29.0 <2.0.0"
      }

Should be updated to

"peerDependencies": {
        "mapbox-gl": ">=0.29.0 <=2.2.0"
      }

Update Mapbox PeerDependency

Are there any plans on updating the mapbox-gl dependency?
I would like to use this plugin in my application, but mapbox-gl 0.29.0 is too old for my needs.

Error: terrain: terrain is missing required property "source" when use projection: "globe" !

When I use {projection: "globe"} to init map will cause th error .

const map = new mapboxgl.Map({
    container: "map", // container ID
    style: "mapbox://styles/mapbox/dark-v10", // style URL
    center: [106.55, 29.57], // starting position [lng, lat]
    zoom: 2, // starting zoom
    projection: "globe", // display the map as a 3D globe
  });
  map.addControl(
    new MapboxLanguage({
      defaultLanguage: "zh-Hans",
    })
  );

The error info

Error: terrain: terrain is missing required property "source"
    at Object.Mi [as emitValidationErrors] (validate_style.js:13:41)
    at Ht (style.js:57:5)
    at ei.setState (style.js:647:13)
    at Map._updateDiff (map.js:1887:28)
    at Map._diffStyle (map.js:1881:18)
    at Map.setStyle (map.js:1822:18)
    at MapboxLanguage._initialStyleUpdate (index.js:141:13)
    at Map.fire (evented.js:129:26)
    at ei.fire (evented.js:144:24)
    at ei._load (style.js:355:14)

if i do not use {projection: "globe"} , it work find !

Only localize layers based on Mapbox Streets source

If the developer has brought in another source for data visualization purposes, it may well have a name property that’s unrelated to the one in the Mapbox Streets source. This plugin should only touch layers using the Mapbox Streets source. Alternatively, it should offer a way for the developer to map languages to name properties in their non-Streets sources.

This Objective-C code targeting the macOS SDK returns true if a vector source’s URL is a mapbox: URL containing mapbox.mapbox-streets-v7. (A straight-up string comparison won’t work due to compositing.)

/ref mapbox/mapbox-gl-native#7031
/cc @lukasmartinelli

Localization support for street & city names

Hello
If I change the language, I change the name of the country and some points, but this doesn't work for streets and cities
I used the instructions from this library, but I haven't seen any examples with change the language for streets and cities

Thanks for any help

Vietnamese

According to this documentation, Mapbox Streets source now (or will soon) support Vietnamese, so it should be added to the supportedLanguages array:

this.supportedLanguages = options.supportedLanguages || ['ar', 'en', 'es', 'fr', 'de', 'ja', 'ko', 'mul', 'pt', 'ru', 'zh'];

/cc @mapbox/gl-js

Demetricate elevations

Now that expression support has landed in GL JS master, this plugin can demetricate any length measurements that occur in labels if the user agent specifies a U.S. locale, based on the following properties in the Mapbox Streets source:

  • building layer: height and min_height
  • state_label and water_label layers: area
  • road_label layer: len
  • mountain_peak_label layer: elevation_m (use elevation_ft)

Of these properties, height, min_height, and elevation_m/elevation_ft are the most likely to appear in labels. area and len are projected areas and lengths, respectively, which aren’t particularly practical for labeling.

For most of these properties, we’ll need to introduce expressions that convert between meters and feet or between square kilometers and square miles or acres. This will require the library to use the new expression syntax instead of the legacy property function syntax, although perhaps we could detect the absence of expression support and still adjust property functions if needed.

For elevation_m, we’ll simply switch to elevation_ft. One challenge will be localizing units that are written out alongside the property: for example, the mountain_peak_label documentation recommends specifying a text field of {elevation_m}m, but {elevation_m} meters could occur instead.

Demetrication should be an option, not mandatory, since meters are used in technical contexts in the U.S.

/cc @lukasmartinelli @anandthakker

Localize expressions

adaptPropertyLanguage() should attempt to localize expressions used as text-fields. Currently, it only works for constant strings and style functions.

mapbox/mapbox-gl-js#6197 is a proposal to make label localization a built-in feature of the style specification. In the meantime, mapbox/mapbox-gl-native#11651 has a comprehensive implementation of label localization in Objective-C. While that implementation targets NSExpression’s syntax, the same logic should more or less apply when working with style JSON objects.

/cc @lukasmartinelli @tristen @anandthakker

`findStreetsSource` causes `setLanguage` to fail

findStreetsSource should check the actual version instead of the URL.

It fails with bright-v9 (https://api.mapbox.com/styles/v1/mapbox/bright-v9) and satellite-v9 (https://api.mapbox.com/styles/v1/mapbox/satellite-v9). Both styles are version: 8, but neither match the check (return url && url.indexOf('mapbox.mapbox-streets-v8') > -1 || /mapbox-streets-v[1-9][1-9]/.test(url);).

This check should probably be as follows:

return (style.version && style.version == 8) ||  (url && url.indexOf('mapbox.mapbox-streets-v8') > -1 || /mapbox-streets-v[1-9][1-9]/.test(url));

When the style of the map changes, the map is always translated in "English".

Trying to change the map style from "mapbox://mapbox-streets-v10" to "mapbox://mapbox-satellite-streets-v9", but when map.setStyle is called, the map is translated to "English" .

I suppose that the library needs to update the style with the true language, because if I remove this line of code "this._map.off ('styledata', this._initialStyleUpdate);" the _initialStyleUpdate method is called from the library and the map is translated correctly.

Thanks

Support of streets-v11 (and other styles based on Streets v8 vector tile source)

The plugin does not seem to work with the latest mapbox styles (streets-v11, dark-v10 and bright-v10 for instance), derived from the Streets v8 vector tile source.

Here is a fiddle with the example from the mapbox blog article introducing the plugin, adapted so it uses the latest versions of the plugin, mapbox GL JS and the streets-v11 style:
https://jsfiddle.net/yo1grbdx/3/
The automatic switch of the map language does not work, but it works if we use the streets-v10 style. We can also still change the language of a layer directly if we use setLayoutProperty.

I have looked a bit into the code of the plugin, and the main problem seems to be that the "languageFieldName" is no longer expected to be a string (like "{name_fr}"), but rather an array (i.e. an expression, like ["get", "name_fr"], cf. #20). There are also changes in the source layer names and layer ids.

Is the support of the new styles planned in the near future?
Thank you.

Exclude certain layers from style transforms

Just tested the plugin with North Star which uses mapbox as source but has no translations for name.
Would be good to provide list of layers to the plugin where language style transform should not be applied to.

Not working with Mapbox v8 styles

My code MapTest.vue

<template>
  <div id="map" style="height: 100%; height: 500px" class="mw-75 mh-75"></div>
</template>

<script>
import "mapbox-gl/dist/mapbox-gl.css";
import MapboxLanguage from '@mapbox/mapbox-gl-language'
import mapboxgl from 'mapbox-gl'

export default {
    mounted() {
        mapboxgl.accessToken = "super_secrect_token";

        var map = new mapboxgl.Map({
            container: 'map',
            style: 'mapbox://styles/mapbox/streets-v11',
            center: [-98, 38.88],
            minZoom: 2,
            zoom: 3
        });
        mapboxgl.setRTLTextPlugin('https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.1.0/mapbox-gl-rtl-text.js');
        var language = new MapboxLanguage({ defaultLanguage: "ja" });
        map.addControl(language);
    }
}
</script>

<style>

</style>

If I change to v7 styles (mapbox://styles/mapbox/streets-v10), it's working

map.addControl is not a function

showModal() {
// 英文标注转换为中文
this.mapVisible = true;
// 在v-if下获取的this.$refs是空的
this.$nextTick(() => {
// console.log("--------", this.$refs);
// console.log("--------", this.$refs.id);
// let mymap = this.$refs.id;
let mymap = this.elements.t1.id;
mapboxgl.accessToken =
'pk.eyJ1Ijoicm94YW5uZWYyIiwiYSI6ImNrZW1qcXU1MjIyaDUycm83enQ3aTl5YWwifQ.RVn2aTnGRCk3xtOozCtyaA';
// mapboxgl.setRTLTextPlugin(
// 'https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.1.0/mapbox-gl-rtl-text.js',
// null,
// true // Lazy load the plugin
// );
this.map = new mapboxgl.Map({
container: mymap, // container id
style: 'mapbox://styles/mapbox/streets-v11', // style URL
center: [121.50109, 31.23691], // starting position [lng, lat]
zoom: 9, // starting zoom
});
// 设置语言
var language = new MapboxLanguage();
map.addControl(language);
// const language = new MapboxLanguage({ defaultLanguage: 'zh' });
// map.addControl(language);
// // 全图
// map.addControl(new mapboxgl.FullscreenControl());
// // 定位
// new mapboxgl.GeolocateControl({
// positionOptions: {
// enableHighAccuracy: true,
// },
// trackUserLocation: true,
// });
});
},

Language cannot be set, if zoom is smaller than 6 when creating the map

I found an interesting issue.

  • If I create a map with zoom isn't set (that is, zoom is default), or is set to a value smaller than 6, and then set the language to Chinese,
    map.current = new mapboxLibrary.Map({
      zoom: 5,
      container: mapContainer.current,
      style: isDarkMode()
        ? 'mapbox://styles/mapbox/dark-v10'
        : 'mapbox://styles/mapbox/streets-v11',
      ...mapboxOptions,
    })

    map.current.addControl(new MapboxLanguage({defaultLanguage: 'zh-Hans'}));

then an English map is shown.

  • If I create a map with zoom is set to a value bigger than or equal to 6, and then set the language to Chinese,
    map.current = new mapboxLibrary.Map({
      zoom: 6,
      container: mapContainer.current,
      style: isDarkMode()
        ? 'mapbox://styles/mapbox/dark-v10'
        : 'mapbox://styles/mapbox/streets-v11',
      ...mapboxOptions,
    })

    map.current.addControl(new MapboxLanguage({defaultLanguage: 'zh-Hans'}));

then a Chinese map is shown.

The code above is a part of project photoview [https://github.com/photoview/photoview], and in the ui/src/components/mapbox/MapboxMap.tsx. You can find the context there.

Simplified Chinese

This plugin currently omits zh-Hans from the list of supported languages. Judging from the Mapbox Streets v7 documentation, name_zh-Hans would probably be more appropriate than name_zh when the browser’s preferred language is zh-Hans, zh-CN, or zh-Hans-CN.

For mapbox/mapbox-gl-native#9063, I relied on the locale matching functionality built into iOS and macOS, but I don’t think there’s an analogue on the Web, so zh-Hans would need a special case or two.

/cc @lukasmartinelli

map.addControl not work and without errors sometimes

I use this package to change the display language of maps to Chinese, with following codes to control it when map fires onLoad event:

import MapboxLanguage from '@mapbox/mapbox-gl-language';

// the method I called after onLoad event
const addControlHandler = (event) => {
    const map = event && event.target;
    if (map) {
      map.addControl(new MapboxLanguage({
        defaultLanguage: 'zh',
      }));
	  // map.setLayoutProperty('country-label-lg', 'text-field', ['get', 'name_zh']);
    }
};

// The actual code in my map JSX code
// StaticMap is a module of package `react-map-gl`
return (
	<StaticMap 
		onLoad={addControlHandler}
	>
);

But it seems the Map Control will not work SOMETIMES, and without any errors in console, just keep silence and nothing happened. I thought it could be an internal problem of this package.

Once, I add another line to operate map instance, the Control will work well again. I don't know what's the problem?

// after `map.addControl` line
map.setLayoutProperty('country-label-lg', 'text-field', ['get', 'name_zh']);

...
  1. GRAMMAR: The grammar I wrote is the same as https://github.com/mapbox/mapbox-gl-language/blob/master/examples/zh.html , however I wrote in react, rather than plain JavaScript.
  2. THIRD-PARTY PACKAGE:: I don't think it could be a third-party package's problem, though I use react-map-gl to provide a JSX style in creating map with mapbox, as I discussed in their issue visgl/react-map-gl#683 (comment) I could access the map variable and map.addControl is also not NULL when the onLoad event is fired.
  3. WHY: I got right result sometimes, just the same as I got wrong result, why could that be an occasional event, rather than a definite one?
  4. WHY2: Why would all the things get back to normal after I add one line code called map.setLayoutProperty?

Any ideas about it, thanks very much.

How to use this with mapbox-leaflet-gl-js?

I use Leaflet to control the map while using mapbox-leaflet-gl-js to render the vector tiles to leaflet.

How do I enable this plugin? My code so far is:

"use strict";

var map = L.map('mapid', {
    center: [DEFAULT_LAT, DEFAULT_LNG],
    format: 'jpg80',
    zoom: DEFAULT_ZOOMLEVEL,
    minZoom: 2,
    maxZoom: 14,
    attributionControl: false,
    preferCanvas: true,
    reuseTiles: true,
    unloadInvisibleTiles: false,
    maxBoundsViscosity: 1.0,
    continuousWorld: false,
    worldCopyJump: true,
    noWrap: true,
});

var gl = L.mapboxGL({
    accessToken: L.mapbox.accessToken,
    style: 'mapbox://styles/mapbox/outdoors-v11'
}).addTo(map);

map.zoomControl.setPosition('topright'); 

// ... etc.

But since I am using L.map instead of the raw mapboxgl.map - how do I enable this plugin? Thanks.

How to translate map to Portuguese of Brazil?

Hi, I have an issue about the translation of the map. I want to translate to PT-BR language, but the options only gives the Portuguese of Portugal. How could I resolve this? There is some other information that I have missed?

Thank you, by the way!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.