Friday, 29 March 2019

load dynamic script in angular 6

import { Component, ViewEncapsulation, OnInit, ElementRef, NgModule, NgZone, ViewChild, AfterViewInit } from '@angular/core';
         
declare var google: any; 

  ngAfterViewInit(): void {
    let googleApiKey = 'AIzaSyB4a';
    let googleMapsUrl = 'https://maps.googleapis.com/maps/api/js?key=' + googleApiKey + '&libraries=places'; // replace by your API key
    this.addMapsScript(googleMapsUrl);
  }


  addMapsScript(googleMapsUrl: string) {
    if (!document.querySelectorAll(`[src="${googleMapsUrl}"]`).length) {
      document.body.appendChild(Object.assign(
        document.createElement('script'), {
          type: 'text/javascript',
          src: googleMapsUrl,
          onload: () => this.createGoogleSearchBox()
        }));
    } else {
      this.createGoogleSearchBox();
    }
  }

createGoogleSearchBox() {
    let updateSitesLocationEl = document.getElementById('txtUpdateSitesLocation');
    let updateSitesLocation = new google.maps.places.SearchBox(updateSitesLocationEl);
    updateSitesLocation.addListener('places_changed', function() {
      let searchBoxValue = self.getValueFromGoogleSearchBox(updateSitesLocation);
      self.updateSitesLocationData['location'] = searchBoxValue.location;
    });
  }

First import AfterViewInit from angular core

create google variable 

in ngAfterViewInit   set google api key and google library url

call a addMapsScript  function in ngAfterViewInit 


After a script onload event call you other google map function s




Load google map script in angular 6

dynamic load google script in angular 6 ,7

No comments:

Post a Comment