我不想反转地理编码并用阿拉伯语和英语两种语言获取地址所以我想用一种语言来获取它然后改变API的语言并用另一种语言获取地址,因为我找不到参数发送到地理编码器以确定语言。有什么建议?
通过将language=XX
附加到API URL来加载API时可以选择一种语言,其中XX
是API调用中的URL的双字符语言代码(英语为en
,阿拉伯语为ar
等)。有关文档,请参阅http://code.google.com/apis/maps/documentation/javascript/basics.html#Localization。
这不会让你动态改变它,我认为你不能这样做。在以一种语言获取所需的初始信息后,您可以尝试第二次加载API。但这似乎可能会导致问题。
更简洁的方法可能是创建一个单独的页面,作为一种Web服务。它接受两个参数:语言代码和地址。它使用所请求的语言代码加载API,并反向对地址进行地理编码,从而提供结果。您的页面会调用此类Web服务两次,每种语言一次,然后根据需要使用结果。
我创建了一个在运行时更改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>