fayez bargout
fayez bargout

Reputation: 21

Google Maps (ReferenceError: google is not defined)

I use google map's API in my website to show couple of locations. Google Maps is working fine . But when I want to calculate the distance between to latitude and longitude I got this error ( ReferenceError: google is not defined)

home.component.ts

import { Component, OnInit } from '@angular/core';
declare var google: any;
@Component({

selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']

})
export class HomeComponent implements OnInit {



location: Location
selectedMarker: Marker
origin: any;
destination: any;
distance: String;



ngOnInit(){


this.distance = this.calculateDistance(this.origin, this.destination);



this.origin = { 
  lat: 32.6950, 
  lng: 35.2820 
};
this.destination = { 
  lat: 32.6050, 
  lng: 35.2020 
};

this.location = {
  latitude: 32.6950,
  longitude: 35.2820,
  zoom: 15,
  markers: [
      {
          lat: 32.6950,
          lng: 35.2820
      }
  ]
  }



 this.loadScript('assets/js/jquery-3.3.1.min.js');
 this.loadScript('assets/vendors/appear/jquery.appear.min.js');
 this.loadScript('assets/vendors/jquery.easing/jquery.easing.min.js');
 this.loadScript('assets/js/popper.min.js');
 this.loadScript('assets/js/bootstrap.min.js');
 this.loadScript('assets/vendors/common/common.min.js');
 this.loadScript('assets/vendors/fancybox/jquery.fancybox.min.js');
 this.loadScript('assets/vendors/menu/src/main.menu.js');
 this.loadScript('assets/vendors/owl.carousel/owl.carousel.min.js');
 this.loadScript('assets/vendors/animated-headline/js/animated-headline.js');
 this.loadScript('assets/js/main.js');
 this.loadScript('assets/js/theme.init.js');
 this.loadScript('assets/js/custom.js');


 }

 public loadScript(url: string) {
 const body = <HTMLDivElement> document.body;
 const script = document.createElement('script');
 script.innerHTML = '';
 script.src = url;
 script.async = false;
 script.defer = true;
 body.appendChild(script);
 }


addMarker(lat: number, lng: number) {
this.location.markers.push({
    lat,
    lng
 })
 }

selectMarker(event) {
this.selectedMarker = {
    lat: event.latitude,
    lng: event.longitude
 }
 } 


calculateDistance(point1, point2) {


const p1 = new google.maps.LatLng(
point1.lat,
point1.lng
);
const p2 = new google.maps.LatLng(
point2.lat,
point2.lng
);

return (
google.maps.geometry.spherical.computeDistanceBetween(p1, p2)/1000
).toFixed(2);
}


}

interface Marker {
lat: number;
lng: number;
}

interface Location {
latitude: number;
longitude: number;
zoom: number;
markers: Array<Marker>;
}     

home.component.html

<agm-map [latitude]="location.latitude" [longitude]="location.longitude" 
[zoom]="location.zoom" (mapClick)="addMarker($event.coords.lat, $event.coords.lng)">
<!-- ... -->
<agm-direction 
    [origin]="origin" 
    [destination]="destination"
></agm-direction>
</agm-map>
<div>
 Distance: {{distance}}
 </div>
 <!-- ... -->

Only thing it says: ReferenceError: google is not defined

Does anyone familiar with such problem?

Upvotes: 1

Views: 3405

Answers (3)

fayez bargout
fayez bargout

Reputation: 21

this code worked for me

home.component.ts

import { Component, OnInit ,ViewChild} from '@angular/core';
import { MapsAPILoader, AgmMap } from '@agm/core';
declare var google: any;



@Component({

  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']

})
export class HomeComponent implements OnInit {



  location: Location
  selectedMarker: Marker
  origin: any;
  destination: any;
  distance: String;
  geocoder: any;


   ngOnInit(){

    this.origin = { 
      lat: 32.6950, 
      lng: 35.2820 
    };
  this.destination = { 
      lat: 32.6050, 
      lng: 35.2020 
   };

    this.location = {
      latitude: 32.6950,
      longitude: 35.2820,
      zoom: 15,
      markers: [
          {
              lat: 32.6950,
              lng: 35.2820
          }
      ]
  }

     this.loadScript('assets/js/jquery-3.3.1.min.js');
     this.loadScript('assets/vendors/appear/jquery.appear.min.js');
     this.loadScript('assets/vendors/jquery.easing/jquery.easing.min.js');
     this.loadScript('assets/js/popper.min.js');
     this.loadScript('assets/js/bootstrap.min.js');
     this.loadScript('assets/vendors/common/common.min.js');
     this.loadScript('assets/vendors/fancybox/jquery.fancybox.min.js');
     this.loadScript('assets/vendors/menu/src/main.menu.js');
     this.loadScript('assets/vendors/owl.carousel/owl.carousel.min.js');
     this.loadScript('assets/vendors/animated-headline/js/animated-headline.js');
     this.loadScript('assets/js/main.js');
     this.loadScript('assets/js/theme.init.js');
     this.loadScript('assets/js/custom.js');
  }

  @ViewChild(AgmMap, { static: true }) map: AgmMap;

  constructor(public mapsApiLoader: MapsAPILoader) {
    this.mapsApiLoader = mapsApiLoader;

    this.mapsApiLoader.load().then(() => {
      this.geocoder = new google.maps.Geocoder();
      this.distance = this.calculateDistance(this.origin, this.destination);
    });
  }

  public loadScript(url: string) {
    const body = <HTMLDivElement> document.body;
    const script = document.createElement('script');
    script.innerHTML = '';
    script.src = url;
    script.async = false;
    script.defer = true;
    body.appendChild(script);
  }


  addMarker(lat: number, lng: number) {
    this.location.markers.push({
        lat,
        lng
    })
  }

  selectMarker(event) {
    this.selectedMarker = {
        lat: event.latitude,
        lng: event.longitude
    }
  } 


  calculateDistance(point1, point2) {


    const p1 = new google.maps.LatLng(
    point1.lat,
    point1.lng
    );
    const p2 = new google.maps.LatLng(
    point2.lat,
    point2.lng
    );

    return (
    google.maps.geometry.spherical.computeDistanceBetween(p1, p2)/1000
    ).toFixed(2);
}


}

interface Marker {
lat: number;
lng: number;
}

interface Location {
latitude: number;
longitude: number;
zoom: number;
markers: Array<Marker>;
}

Upvotes: 1

Aakash Garg
Aakash Garg

Reputation: 10979

Above component decorator type

var google: any;

Upvotes: 0

Manish
Manish

Reputation: 6286

Try

  1. In the index.html,

    < script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&key={your_key_here}" async defer>

  2. Include googlemaps in types of tsconfig.app.json

Example:

 {
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": [
      "googlemaps"
    ]
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "src/test.ts",
    "src/**/*.spec.ts"
  ]
}

Upvotes: 1

Related Questions