

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 맵에 대한 기본 언어를 설정하는 방법
<a name="how-to-set-preferred-language-map"></a>

Amazon Location Service를 사용하면 특정 언어에 대한 스타일 설명자를 업데이트하여 클라이언트 측에서 기본 언어를 설정할 수 있습니다. 기본 언어를 설정하고 포함된 콘텐츠를 해당 언어로 표시할 수 있습니다. 그렇지 않으면 다른 언어로 대체됩니다.

**참고**  
자세한 내용은 [현지화 및 국제화](maps-localization-internationalization.md) 단원을 참조하십시오.

## 기본 언어를 일본어로 설정하고 일본 맵 표시
<a name="set-preferred-language-japanese"></a>

이 예제에서는 일본어(ja)로 맵 레이블을 표시하도록 업데이트 스타일을 설정합니다.

### 기본 언어를 일본어로 설정 예제
<a name="set-preferred-language-japanese-example"></a>

------
#### [ index.html ]

```
<html>
<head>
    <link href="https://unpkg.com/maplibre-gl@5.x/dist/maplibre-gl.css" rel="stylesheet" />
    <script src="https://unpkg.com/maplibre-gl@5.x/dist/maplibre-gl.js"></script>
    <link href="style.css" rel="stylesheet" />
    <script src="main.js"></script>
</head>
<body>
    <div id="map" />
    <script>
        const apiKey = "Add Your Api Key";
        const mapStyle = "Standard";
        const awsRegion = "eu-central-1";
        const initialLocation = [139.76694, 35.68085]; //Japan   
        
        async function initializeMap() {
            // get updated style object for preferred language. 
            const styleObject = await getStyleWithPreferredLanguage("ja");
            // Initialize the MapLibre map with the fetched style object
            const map = new maplibregl.Map({
                container: 'map',
                style: styleObject,
                center: initialLocation,
                zoom: 15,
                hash:true,
            });
            map.addControl(new maplibregl.NavigationControl(), "top-left");
        
            return map; 
        }
  
        initializeMap();
    </script>
</body>
</html>
```

------
#### [ style.css ]

```
body { margin: 0; }
#map { height: 100vh; }
```

------
#### [ main.js ]

```
async function getStyleWithPreferredLanguage(preferredLanguage) {
    const styleUrl = `https://maps.geo.${awsRegion}.amazonaws.com/v2/styles/${mapStyle}/descriptor?key=${apiKey}`;

    return fetch(styleUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok ' + response.statusText);
            }
            return response.json();
        })
        .then(styleObject => {
            if (preferredLanguage !== "en") {
                styleObject = setPreferredLanguage(styleObject, preferredLanguage);
            }

            return styleObject;
        })
        .catch(error => {
            console.error('Error fetching style:', error);
        });
}

const setPreferredLanguage = (style, language) => {
    let nextStyle = { ...style };

    nextStyle.layers = nextStyle.layers.map(l => {
        if (l.type !== 'symbol' || !l?.layout?.['text-field']) return l;
        return updateLayer(l, /^name:([A-Za-z\-\_]+)$/g, `name:${language}`);
    });

    return nextStyle;
};

const updateLayer = (layer, prevPropertyRegex, nextProperty) => {
    const nextLayer = {
        ...layer,
        layout: {
            ...layer.layout,
            'text-field': recurseExpression(
                layer.layout['text-field'],
                prevPropertyRegex,
                nextProperty
            )
        }
    };
    return nextLayer;
};

const recurseExpression = (exp, prevPropertyRegex, nextProperty) => {
    if (!Array.isArray(exp)) return exp;
    if (exp[0] !== 'coalesce') return exp.map(v =>
        recurseExpression(v, prevPropertyRegex, nextProperty)
    );

    const first = exp[1];
    const second = exp[2];

    let isMatch =
    Array.isArray(first) &&
    first[0] === 'get' &&
    !!first[1].match(prevPropertyRegex)?.[0];

    isMatch = isMatch && Array.isArray(second) && second[0] === 'get';
    isMatch = isMatch && !exp?.[4];

    if (!isMatch) return exp.map(v =>
        recurseExpression(v, prevPropertyRegex, nextProperty)
    );

    return [
        'coalesce',
        ['get', nextProperty],
        ['get', 'name:en'],
        ['get', 'name']
    ];
};
```

------

## 최종 사용자의 브라우저 언어를 기반으로 기본 언어 설정
<a name="set-preferred-language-browser"></a>

이 예제에서는 사용자의 디바이스 언어로 맵 레이블을 표시하도록 업데이트 스타일을 설정합니다.

### 브라우저 언어를 기반으로 기본 언어 설정 예제
<a name="set-preferred-language-browser-code"></a>

------
#### [ index.html ]

```
<html>
<head>
    <link href="https://unpkg.com/maplibre-gl@5.x/dist/maplibre-gl.css" rel="stylesheet" />
    <script src="https://unpkg.com/maplibre-gl@5.x/dist/maplibre-gl.js"></script>
    <link href="style.css" rel="stylesheet" />
    <script src="main.js"></script>
</head>
<body>
    <div id="map" />
    <script>
        const apiKey = "Add Your Api Key";
        const mapStyle = "Standard";
        const awsRegion = "eu-central-1";
        const initialLocation = [139.76694, 35.68085]; //Japan     
        const userLanguage = navigator.language || navigator.userLanguage;
        const languageCode = userLanguage.split('-')[0];

        async function initializeMap() {
             const styleObject = await getStyleWithPreferredLanguage(languageCode);
             const map = new maplibregl.Map({
                 container: 'map',
                 style: styleObject,
                 center: initialLocation,
                 zoom: 15,
                 hash:true,
             });
             map.addControl(new maplibregl.NavigationControl(), "top-left");
             return map; 
        }

        initializeMap();
    </script>
</body>
</html>
```

------
#### [ style.css ]

```
body { margin: 0; }
#map { height: 100vh; }
```

------
#### [ main.js ]

```
async function getStyleWithPreferredLanguage(preferredLanguage) {
    const styleUrl = `https://maps.geo.${awsRegion}.amazonaws.com/v2/styles/${mapStyle}/descriptor?key=${apiKey}`;

    return fetch(styleUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok ' + response.statusText);
            }
            return response.json();
        })
        .then(styleObject => {
            if (preferredLanguage !== "en") {
                styleObject = setPreferredLanguage(styleObject, preferredLanguage);
            }

            return styleObject;
        })
        .catch(error => {
            console.error('Error fetching style:', error);
        });
}

const setPreferredLanguage = (style, language) => {
    let nextStyle = { ...style };

    nextStyle.layers = nextStyle.layers.map(l => {
        if (l.type !== 'symbol' || !l?.layout?.['text-field']) return l;
        return updateLayer(l, /^name:([A-Za-z\-\_]+)$/g, `name:${language}`);
    });

    return nextStyle;
};

const updateLayer = (layer, prevPropertyRegex, nextProperty) => {
    const nextLayer = {
        ...layer,
        layout: {
            ...layer.layout,
            'text-field': recurseExpression(
                layer.layout['text-field'],
                prevPropertyRegex,
                nextProperty
            )
        }
    };
    return nextLayer;
};

const recurseExpression = (exp, prevPropertyRegex, nextProperty) => {
    if (!Array.isArray(exp)) return exp;
    if (exp[0] !== 'coalesce') return exp.map(v =>
        recurseExpression(v, prevPropertyRegex, nextProperty)
    );

    const first = exp[1];
    const second = exp[2];

    let isMatch =
    Array.isArray(first) &&
    first[0] === 'get' &&
    !!first[1].match(prevPropertyRegex)?.[0];

    isMatch = isMatch && Array.isArray(second) && second[0] === 'get';
    isMatch = isMatch && !exp?.[4];

    if (!isMatch) return exp.map(v =>
        recurseExpression(v, prevPropertyRegex, nextProperty)
    );

    return [
        'coalesce',
        ['get', nextProperty],
        ['get', 'name:en'],
        ['get', 'name']
    ];
};
```

------