[Mapbox]Change your map’s label language

This section describes the procedure for converting Mapbox’s map notation to Japanese with the mapbox-gl-language package, which is officially provided by Mapbox.

Please refer to this article for the map display.

This article assumes that the Nextjs version is “13.5.4” and that react-map-gl has already been installed.

目次

Introduction of packages

install @mapbox/mapbox-gl-language.

$ yarn add @mapbox/mapbox-gl-language

Change your map’s label language in Mapbox

Add MapProvider to layout.tsx.

MapProvider is a context that enables map operations outside the map component.

'use client'

import * as React from 'react'
import Mapbox2 from '@/components/Mapbox/Mapbox2'
import { MapProvider } from 'react-map-gl'

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang='ja'>
      <body>
        <MapProvider>
          <Mapbox2 />
        </MapProvider>
      </body>
    </html>
  )
}

UseMap to get a map instance, and useEffect to set the language when there is a change to the map instance.

Japanese is displayed by passing “ja” to the MapboxLanguage constructor.

import Map, { useMap } from 'react-map-gl'
import 'mapbox-gl/dist/mapbox-gl.css'
import MapboxLanguage from '@mapbox/mapbox-gl-language'
import { useEffect } from 'react'

/**
 * Mapbox 
 */
const Mapbox2 = () => {
  const { map } = useMap()

  useEffect(() => {
    if (map) {
      const language = new MapboxLanguage({
        defaultLanguage: 'ja'
      })
      map.addControl(language)
    }
  }, [map])

  return (
    <Map
      id='map'
      initialViewState={{
        longitude: 139.636814,
        latitude: 35.443098,
        zoom: 15
      }}
      style={{ width: '100%', height: '100vh' }}
      mapStyle={'mapbox://styles/xxx/yyy'}
      mapboxAccessToken={"Mapbox Access Token"}
    />
  )
}

export default Mapbox2

By default, it seems to support Mapbox v8 styles languageisation.

Summary

There were many articles about using Mapbox GL JS when making Japanese, but there was none for react-map-gl, so I looked it up while looking at the documentation.
In order to get a map instance with useMap(), a MapProvider is required in layout.tsx.
This may be a stumbling block for those just starting out with Nextjs.

よかったらシェアしてね!
目次