如何在运行中更改Google地图的语言?

Ahm*_*rsy 10 google-maps reverse-geocoding google-maps-api-3 geocode

我不想反转地理编码并用阿拉伯语和英语两种语言获取地址所以我想用一种语言来获取它然后改变API的语言并用另一种语言获取地址,因为我找不到参数发送到地理编码器以确定语言.有什么建议?

Tro*_*ott 19

通过附加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服务两次,每种语言一次,然后根据需要使用结果.

  • 哦'Googloids',不能相信这仍然是真的,他们可以解决任何数学问题并做到这一点.2017年找不到任何更新(此答案已过去6年).无法动态更改语言,无法动态设置API密钥等.@trott你知道今天怎么做得更好吗? (7认同)

Zen*_*noo 8

我创建了一个函数来在运行时更改谷歌地图的语言。
由于它返回一个Promise,您可以轻松地等待 API 已加载以执行其他一些代码。

演示


使用示例

setAPILanguage('fr', ['places'], 'xxxxxx').then(() => {
    //The API is loaded here
});
Run Code Online (Sandbox Code Playgroud)

文档

/**
 * 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
 */
Run Code Online (Sandbox Code Playgroud)

来源

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;
}
Run Code Online (Sandbox Code Playgroud)

演示