パラメータが見つからないため、ジオコードを逆にして住所をアラビア語と英語の2つの言語で取得したくないので、一方の言語で取得してからAPIの言語を変更し、もう一方の言語で住所を取得したい言語を決定するためにジオコーダーに送信します。助言がありますか?
4 に答える
APIをロードするときに言語を選択するには、API呼び出しのURLに2文字の言語コード(英語、アラビア語など)を追加language=XX
します。ドキュメントについては、 http://code.google.com/apis/maps/documentation/javascript/basics.html#Localizationを参照してください。XX
en
ar
これでは、その場で変更することはできません。また、変更できるとは思いません。1つの言語で必要な初期情報を取得した後、APIをもう一度ロードしてみることができます。しかし、それは問題を引き起こす可能性が高いようです。
それを行うためのよりクリーンな方法は、一種のWebサービスとして機能する別のページを作成することかもしれません。言語コードとアドレスの2つのパラメータを受け入れます。要求された言語コードを使用してAPIをロードし、アドレスを逆に地理コード化して結果を提供します。あなたのページは、このWebサービスのようなものを言語ごとに1回ずつ、2回呼び出し、必要に応じて結果を使用します。
実行時にGoogleマップの言語を変更する関数を作成しました。
を返すのでPromise
、APIがロードされて他のコードを実行するまで簡単に待つことができます。
使用例
setAPILanguage('fr', ['places'], 'xxxxxx').then(() => {
//The API is loaded here
});
ドキュメンテーション
/**
* Changes the language of the Google Maps API
* @param {String} lang - Google Maps new language
* @param {String[]} libraries - The list of libraries needed
* @param {String} key - Your API key
* @returns {Promise} - Resolves when Google Maps API has finished loading
*/
ソース
const setAPILanguage = (lang, libraries, key) => {
//Destroy old API
document.querySelectorAll('script[src^="https://maps.googleapis.com"]').forEach(script => {
script.remove();
});
if(google) delete google.maps;
//Generate new Google Maps API script
let newAPI = document.createElement('script');
newAPI.src = 'https://maps.googleapis.com/maps/api/js?libraries=' + libraries.join(',') + '&key=' + key + '&language=' + lang + '&callback=googleMapsAPILoaded';
//Callback for the Google Maps API src
window.googleMapsAPILoaded = () => {
let event = new CustomEvent('googleMapsAPILoaded');
window.dispatchEvent(event);
}
//Wait for the callback to be executed
let apiLoaded = new Promise(resolve => {
window.addEventListener('googleMapsAPILoaded', () => {
resolve();
});
});
//Start the script
document.querySelector('head').appendChild(newAPI);
return apiLoaded;
}
すでに指摘したように、マップがロードされるとこれを変更することはできませんが、ページを更新する余裕がある人にとっては、これは機能する可能性があります。
HTML
<script type="text/javascript">
//load map based on current lang
var scriptTag = document.createElement('script');
var currentLang = window.localStorage && window.localStorage.getItem('language');
var scriptSrc = '//maps.googleapis.com/maps/api/js?libraries=drawing,places&key=YOUR_KEY_HERE';
if (currentLang)
scriptSrc = '//maps.googleapis.com/maps/api/js?language=' + currentLang + '&libraries=drawing,places&key=YOUR_KEY_HERE';
scriptTag.setAttribute('src', scriptSrc);
scriptTag.setAttribute('async', '');
document.head.appendChild(scriptTag);
</script>
JS
function changeLangAndReload(lang) {
window.localStorage.setItem('language', lang);
window.location.reload();//or use your preferred way to refresh
}
次の例では、日本語の地図を表示し、地域を日本に設定します。
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&language=ja®ion=JP">
</script>