Integrating JavaScript mapping features into Angular applications

I am currently working on integrating Javascript Google Maps into my Angular 8 project to enhance the functionality beyond what AGM offers. Despite creating a typings.d.ts file and including my JavaScript in the angular.json, I keep encountering the error: 'map' is declared but its value is never read. Below is an overview of my code...

component.html

  <body>
    <div id="map"></div>
    <script src="https://maps.googleapis.com/maps/api/js?key={{apiKey}}&callback=initMap"
    async defer>
    </script>
    <script >
    </script>
  </body>
</html>

component.ts

import * as map from 'map';
import { Component, OnInit } from '@angular/core';
import { environment } from '../../environments/environment';

@Component({
  selector: 'app-google-maps',
  templateUrl: './google-maps.component.html',
  styleUrls: ['./google-maps.component.css']
})
export class GoogleMapsComponent implements OnInit {

  private apiKey = environment.googleMapsAPIkey;

  constructor() { }

  ngOnInit() {
  }

}

maps.js

var map;
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -34.397, lng: 150.644},
    zoom: 8
  });
}

typings.d.ts

declare module Map {
  export interface Main {
    map;
  }
}
declare var Map:Map.Main;

Answer №1

This code snippet demonstrates how to display Google Maps in developer mode.

HTML

<div style="width: 1000px;height: 300px;" id="map"></div>

Component.ts

constructor() { 

var dynamicScripts = ["https://maps.googleapis.com/maps/api/js?key="apiKey"];

for (var i = 0; i < dynamicScripts.length; i++) {
let node = document.createElement('script');
node.src = dynamicScripts[i];
node.type = 'text/javascript';
node.async = true;
node.charset = 'utf-8';
document.getElementsByTagName('head')[0].appendChild(node);
}
}
initMap() {
var uluru = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});

}
ngOnInit() {
setTimeout(()=>{ // 
this.initMap();
},2000);
}

Note Instead of using setTimeout, consider using promises.then().

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

Encountered an Angular 2 error: Uncaught TypeError - Unable to access property 'isActivated' of undefined

Whenever I try to return to the same routing path, an error pops up showing: "Uncaught (in promise): TypeError: Cannot read property 'isActivated' of undefined". Strangely, this error doesn't occur the first time. Can anyone assist me with ...

Express and Angular 5 service worker facing compatibility issues

For the past couple of days, I've been struggling with my Angular5 service worker. However, after some investigation, I believe the issue lies in the way I am serving the application. If you're interested in the detailed journey leading up to thi ...

Retrieving an Enum member based on its value in TypeScript

I am working with an enum called ABC: enum ABC { A = 'a', B = 'b', C = 'c', } In addition, I have a method named doSomething: doSomething(enum: ABC) { switch(enum) { case A : console.log(A); break; case ...

Utilizing Phantom Js with Apache server

After creating a JavaScript app, I realized the importance of making it SEO friendly. I am curious if anyone has experience setting up a crawlable webpage on Apache using Backbone.js (potentially with assistance from PHP and .htaccess files, or with Phant ...

Validating for the existence of a property in Typescript

My function is able to accept two different types of objects as arguments myFunc(arg: (Obj1 | Obj2)) Within my function, I am trying to achieve the following: let val = ( arg instance of Obj1 ) ? Obj1.propOnlyOnObj1 : Obj2.propOnlyOnObj2; However, Type ...

Default values using Observables in Angular 2 Formbuilder

I am encountering an issue with setting the default value of an Angular 2 Form (formbuilder). In my case, the default values are observables retrieved from a server, so I am unable to implement them in the usual way: export class UserComponent implements ...

Every time I try to request something on my localhost, NextJS console throws a TypeError, saying it cannot read the properties of undefined, specifically '_owner'

Update: I've noticed that these errors only appear in Chrome, while other browsers do not show them. Recently, I created a simple NextJS project by following a couple of tutorials, which also includes TypeScript. However, after running npm run dev, I ...

Utilizing JavaScript along with ASP.NET web user controls

My web user control generates specific HTML code on the client side. I am trying to reference a particular RadioButton control using JavaScript. The issue is that the RadioButton ID is dynamically generated by ASP.NET, for example, I assign the ID as 1_R ...

Troubleshooting problem with Angular4's HTTP requests

While working on my Angular 4 application, I am creating an oath guard service to check the validity of tokens. If the token is not valid, I want the user to log in again. Below are the functions I have implemented for this purpose: isLogedIn(){ ret ...

Vue.js $scopedSlots do not function with Vue object

In the process of developing a Vue component that will be released once completed, I am wrapping Clusterize.js (note that the vue-clusterize component is only compatible with v1.x). The goal is to efficiently render a large list of items using Vue, particu ...

Is there a way to keep a JS script running even after navigating away in the Google Chrome console?

Assume there is a basic script available var x = 0; run(); function run() { console.log(x++); setTimeout(run, 1000); } If I input it into the Google Chrome console. How can I keep it running even after navigating to another page (continuously d ...

Learn how to implement interconnected dropdown menus on an html webpage using a combination of JavaScript, AngularJs, and JSON dataset

Incorrect HTML code example: <div ng-app="myApp" ng=controller="myCtrl"> States : <select id="source" name="source"> <option>{{state.name}}</option> </select> Districts: <select id="status" name="status"> ...

Leveraging Angular 2 directives in TypeScript to bind a value from a custom control to an HTML control

I have created a unique custom directive named "my-text-box", and within this directive, I am utilizing the HTML control <input>. I want to pass values from my custom control to the HTML input control. In Angular 1, I would simply do something like & ...

An error occurred while defining props due to a parsing issue with the prop type. The unexpected token was encountered. Perhaps you meant to use `{`}` or `}`?

const dataProps = defineProps({ selectedData: <Record<string, string>> }); Under the closing bracket, there is a red line indicating: Error: Unexpected token. Consider using {'}'} or &rbrace; instead?eslint Expression expecte ...

What is the process for changing search box suggestions in Google and Wikipedia to radio buttons?

I recently integrated Google and Wikipedia search boxes into a webpage and I'm seeking a method to modify the suggestions based on the selected radio button. Specifically, the suggestion language should adjust according to the checked language option ...

Verifying the existence of a property in JavaScript

Is there a better method to verify if an object property, such as obj.prop.otherprop.another, exists? if(obj && obj.prop && obj.prop.otherprop && obj.prop.otherprop.another) While this solution is effective, it may be considered cumbersome. ...

Looking for the Tree in the backend 3D model of Three.js

Lately, I've been exploring various WebGL showcases and came across three.js, a widely popular framework that even has its own dedicated book by Toni Parsli. Upon examining the source code of three.js, I was surprised not to find any traditional scene ...

Removing a specific object from a MongoDB array by its unique identifier

I'm currently developing an application that focuses on playlists. Utilizing MongoDB with mongoose, I am storing videos within each playlist using an array structure as demonstrated below: { _id: ObjectId("61ca1d0ddb66b3c5ff93df9c"), name: "Playli ...

Encountering an issue when trying to assign a database value to a drop-down list using Angular.js

I encountered an issue while attempting to set the database value using Angular.js. Error: TypeError: index.push is not a function Below, I have provided an explanation of my code. <tr ng-repeat="d in days"> <td>{{d.day}}</td> < ...

What is the syntax for declaring an object within an Angular component?

Hello there, I'm fairly new to Angular and I've been encountering an issue with object declaration in one of my angular components. import { Component } from '@angular/core'; @Component({ selector: 'app-clases', templateU ...