Search code examples
angulargoogle-maps

How can I set my Google maps key in index.html dynamically in angular 2?


I'm trying to set google maps key dynamically in my angular project.

Generally we set that API key in index.html file of angular project. Now I want to change that key dynamically. I'll be fetching that key by some API and the question is that how can I set that in my index.html. any help will be appreciated.

Index.html

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>Angular App</title>

  <script type="text/javascript"
    src="https://maps.googleapis.com/maps/api/js?key=GOOGLE_API_KEY&libraries=places,drawing&callback=initMap"></script>

  <script src="https://apis.google.com/js/platform.js" async defer></script>

  <link rel="icon" type="image/x-icon" href="web_images/title_image.png">
</head>

</html>

Solution

  • Here is Some Solution that worked for me to load JavaScript in Angular. It might help you..

    app.component.ts

    export class AppComponent implements OnInit {
          scripts: any;
    
      ngOnInit() {
        this.loadScript('https://maps.googleapis.com/maps/api/js?key=GOOGLE_API_KEY&libraries=places,drawing&callback=initMap').then(() => {
          console.log('Success')
        })
      }
    
    loadScript(name: string) {
        return new Promise((resolve, reject) => {
          let script = document.createElement('script');
          script.type = 'text/javascript';
          script.src = name;
          document.getElementsByTagName('head')[0].appendChild(script);
          console.log('Script Loaded');
          resolve()
        });
      }
    

    You may call api from backend to get api key in ngOnInit before loading script.