Change Map language dynamically in angular2

Viewed 1344

I am using AgmCoreModule to load google map. Is it possible to change map language dynamically when language is selected?

I am able to set default language on load of map using code below

@NgModule({
  imports: [ 
    AgmCoreModule.forRoot({
      libraries: ["places"],
      language: 'de'
    }),
    ...
    ]
})  

But what I actually needed is to change language of map on language selected from dropdown. OR How do I set language in MapsAPILoader?

this._mapsAPILoader.load().then(() => {
...
});

Thanks.

2 Answers

in order to replace the language you should at first delete the script and google maps, then generate it again and wait a while till it's reloaded you can do it like that:

async loadScript() {
var oldScript = document.getElementById("agmGoogleMapsApiScript");
if (oldScript !== null) {
  oldScript.parentNode.removeChild(oldScript);
  delete google.maps;
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = 'https://maps.googleapis.com/maps/api/js? 
v=3&key={{YourApiKey}}&region=israel&language= 
{{language}}';
script.id = "agmGoogleMapsApiScript";
document.body.appendChild(script);
await new Promise(resolve => setTimeout(resolve, 1000));
}

then you should reload the agm-core map, you can do it by stepping out of the component.

don't forget to declare google, like that:

declare var google: any;

worked for me, hope it helps :)

Related