Change angular-google-maps language dynamically
Asked Answered
P

4

7

Is it possible to change map language dynamically when language is changed ? Or at least have the language map changed the next time I access it (after language is changed).

I can set default language on map loading using this code (in mymap.module.ts) :

@NgModule({ imports: [ 
  AgmCoreModule.forRoot({ apiKey: 'MY_KEY',
  language: 'es', }),
  ]
})

And I can get the current language using this.translate.currentLang (in mymap.component.ts).

But I don't know how I can combine both.

Precinct answered 24/3, 2018 at 9:39 Comment(1)
Have you tried to re-initialize the whole map?Andreeandrei
G
4

In order to change map's language, a bunch of localized JS scripts need to be refetched anew. So, you can just try to refresh entire page (JS not Angular) providing wanted language via local storage for example:

@NgModule({ 
  imports: [ 
    AgmCoreModule.forRoot({ 
      apiKey: 'MY_KEY',
      language: localStorage && localStorage.gml || 'en'
    }),
  ]
})

to reload your page, use window.location.reload() method

StackBLITZ: https://stackblitz.com/edit/angular-google-maps-demo-f3xzhn?file=app%2Fapp.module.ts

Garlandgarlanda answered 24/3, 2018 at 14:6 Comment(2)
this solution does not work if I build for production i.e. "ng build --prod" and deploy the dist to any http server. The resulting production build is removing the condition "localStorage && localStorage.gml || ".Contrabassoon
Not working when build production: ng build --prod --build-optimizerKoroseal
Q
2

In app.component add the following make sure upon language change to update "lang" in local storage and reload the page using window.location.reload()

export class AppComponent implements OnInit {
  constructor() { }

  ngOnInit() {

    var script = document.createElement('script');
    script.src = `https://maps.googleapis.com/maps/api/js?v=quarterly&key=${KEY}&libraries=places&language=${localStorage && localStorage.lang || 'en'}`;
    document.head.appendChild(script);
  }
}

In your relevant module add:

@NgModule({ 
  imports: [ 
    AgmCoreModule.forRoot(),
  ]
})
Quirita answered 21/4, 2020 at 23:47 Comment(0)
O
0

I know this issue has been raised a long time ago, but I'll send a link to anyone who is interested in the solution. It's a bit complex but it works fine with AOT AgmCoreModule - Load Google API KEY Dynamically from Angular service

Odetteodeum answered 24/3, 2021 at 1:40 Comment(0)
S
0

I've had a need to do something similar where language and API key are loaded in dynamically.

To do this, I've created a class called AppInitService. Here, I'll initialise various properties in my app on the fly, such as translation language/currency or, in the case of AGM, the API key and language.

In your app.module.ts or whatever you use you would add the following provider:

import { NgModule, APP_INITIALIZER } from '@angular/core';
import { AgmCoreModule, LazyMapsAPILoaderConfigLiteral, LAZY_MAPS_API_CONFIG } from '@agm/core';

@NgModule({
  imports: [
    AgmCoreModule.forRoot({
      // The apiKey must always be set, even if empty.
      apiKey: 'MyApiKey'
    })
  ],
  providers: [
    {
      // APP_INITIALIZER is the Angular dependency injection token.
      provide: APP_INITIALIZER,
      // Pass in the AGM dependency injection token.
      deps: [LAZY_MAPS_API_CONFIG],
      // Allow for multiple startup injectors if needed.
      multi: true,
      // UseFactory provides Angular with the function to invoke.
      useFactory: (googleMapsConfig: LazyMapsAPILoaderConfigLiteral) => () => AppInitService.Init(googleMapsConfig)
    }
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }

Then in AppInitService.ts:

import { Injectable } from '@angular/core';
import { LazyMapsAPILoaderConfigLiteral } from '@agm/core';

@Injectable()
export class AppInitService {
  public static Init(googleMapsConfig: LazyMapsAPILoaderConfigLiteral) : Promise<void> {
    return new Promise<void>((resolve, reject) => {

      // Here you'll put in your call to retrieve your language code.
      const languageCode = GetMyLanguageCode();

      // And now we set it.
      googleMapsConfig.language = languageCode;

      // Resolve the promise as we're done.
      resolve();
    });
  }
}

There's an example of how to use the Angular app initialisation here. I prefer static functions though as you don't have to instantiate the class in order to use them.

Supporter answered 23/4, 2021 at 19:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.