The Google Maps feature encountered an error (ReferenceError: google is not defined)

Utilizing the Google Maps API on my website to display multiple locations has been successful so far. However, an issue arises when attempting to determine the distance between two sets of latitude and longitude coordinates - resulting in an error message stating: "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>
 <!-- ... -->

The primary error encountered states: ReferenceError: google is not defined

Seeking guidance from those who have experience with a similar issue.

Answer №1

Give it a shot!

  1. Open the index.html file and add the following code:

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

  2. Make sure to include googlemaps in the types section of your tsconfig.app.json file

Here's an example for your tsconfig.app.json:

 {
  "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"
  ]
}

Answer №2

the solution provided here was effective for my project

content.component.ts

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

@Component({

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

})
export class ContentComponent 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>;
}

Answer №3

Decorator type above component

var google: any;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to successfully send data props from child components to parent in Vue3

I am currently working on a personal project to add to my portfolio. The project involves creating a registration site where users can input their personal data, shipping information, and then review everything before submission. To streamline the process ...

Creating recursive functions to produce a unique variable without any repetitions

Currently utilizing MongoDB and Express in my project. I have a post endpoint that generates a random name for the name field. Everything is working as expected except when I encounter a duplicate name. I need to check if the name already exists in the d ...

Using three.js to set the HTML background color as clearColor

How can I set the HTML background as clearColor using three.js? Here is the code snippet for three.js: // Setting up the environment var vWebGL = new WEBGL(); var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(75, window.innerWidth / ...

Make sure to update the value of a Mongoose document only if it has been

I am looking to update a specific value in the document only if it is newly defined. If the value is not defined, I want to leave it as it is in the document. For example: If this particular document exists in the database: { "_id": "592c53b3bdf350ce00 ...

The functionality to verify the presence of a child element is not functioning correctly when using

Trying to determine the existence of a child, I have created a new Firebase list observable and also attempted with an object observable. Upon creating the observable, I verify if it exists or not; however, it always returns false. Database Structure: {R ...

Utilizing a plugin to execute a function in Wordpress

I'm currently facing the challenge of combining two WordPress plugins without the need to modify one to fit into the other seamlessly. My main question is: How can I call a function from one plugin that exists outside of another plugin? For example, ...

ajax: ensure utf-8 encoding is applied

I am facing an issue with my webpage that is saved in UTF-8 encoding. In the head section of the HTML document, I have defined it as follows: <meta charset="utf-8" /> Within an external JavaScript file, there is a function called ajax_db() which ma ...

javascript - convert a JSON string into an object without using quotation marks

Consider the following example: var mystring = `{ name: "hello", value: 1234 }` var jsonobj = JSON.parse(mystring) The code above will not output anything because the "name" and "value" keys are missing quotes. How can I parse this strin ...

Is it possible to manually disrupt the predetermined prototype chain of Numbers, Strings, Booleans, and Arrays in JavaScript, or reassign values to do so?

Whenever we create a new variable of the number type (let's say num1), its __proto__ is set to point to the Number Object. The __proto__ of this points to Object Core, and its __proto__ ultimately ends with null, completing the Prototype chain. My go ...

Routing in Next.js to create custom URL slugs for usernames, like (site.com/username), is a

I have a requirement to create username pages on my website, where each username will have its own page like site.com/jack The current folder structure I am using is pages > [user] > index.js, but this setup causes issues when someone tries to acces ...

Navigating the intricacies of sub-State mapping in Nuxtjs

I have set up a state called ~/store/modules/general/index.js Within this state, there are Actions named get_info and get_pages, as well as states named info and pages. When I use ...mapActions({ getInfo: 'modules/general/get_info' getPages: ...

Can Ajax be utilized to call a PHP script that contains another Ajax function?

I have set up a checkbox that triggers an Ajax call to another PHP script once checked. In this PHP script, there are three text boxes and a button. When the button is pressed, another Ajax call is made to execute yet another PHP script, all within the sam ...

Is AJAX causing issues with my media uploader and color picker?

Currently, I have incorporated tabbed navigation within a WordPress admin page and it is functioning properly on its own (data can be saved). However, I am now looking to implement some AJAX functionality for toggling between pages. The issue arises when t ...

Issue encountered with PNR generation while utilizing the Amadeus flight create orders API

My goal is to utilize the Amadeus flight booking API to create bookings and generate PNRs. I have outlined the 3 steps involved in this process: Utilize the Flight Offers Search API available at the following link: Flight Offers Search API - Documentation ...

Execute a function upon pressing the enter key

Currently, I am working on coding a webpage with a form that includes one field where users input a set of numbers. After typing in the numbers, they should then press a button labeled 'Run' to execute the code. However, the issue arises when use ...

Breaking on newline, excluding newline-space in JavaScript

I want to divide my string into an array based on new lines, excluding those that start with a space. ORGANIZER;<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3758455056595e4d524577524f565a475b521954585a">[email prot ...

What is the process for logging out when a different user signs in using Firebase authentication in a React Native application?

I am new to React Native and facing challenges with managing authentication state in my application. Currently, I am using Redux but have not yet implemented persistence for user login. I have incorporated Firebase authentication. Essentially, I would li ...

Leveraging local resources to create images with the help of @vercel/og and Next.js

Utilizing the latest @vercel/og library for generating meta-tag images has been quite intriguing. The official example showcases how to leverage images from an external source. The Quandary at Hand <img src={"https://res.cloudinary.com/iqfareez ...

React Hook is failing to trigger an update

Learning React and JavaScript has been quite a challenge for me, especially when it comes to understanding React Hooks and the issue of them not updating sometimes. I have tried searching online but either end up with solutions for class-based components o ...

Typescript challenge: Implementing a route render attribute in React with TypeScript

My component has props named project which are passed through a Link to a Route. Here's how it looks (the project object goes in the state extended property): <Link to={{ pathname: path, state: { project, }, }} key={project. ...