Utilizing Angular 2 for a dynamic Google Map experience with numerous markers

I am currently working on an Angular2 project that involves integrating Google Maps.

My goal is to display multiple markers around a specific area on the map. Although I have been able to get the map running, I am facing issues with displaying the markers.

<div class="google-maps"></div>

constructor(private _elementRef:ElementRef) {
  }
  
ngAfterViewInit() {
    let el = this._elementRef.nativeElement.querySelector('.google-maps');
    
    GoogleMapsLoader.load((google) => {
      let myLatlng = new google.maps.LatLng(44.5403,-78.5463);
      
      new google.maps.Map(el, {
        center: new google.maps.LatLng(44.5403, -78.5463),
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });

      new google.maps.Marker(el,{ 
        draggable: true,
        animation: google.maps.Animation.DROP,
        position: myLatlng,
        title:"Hello World!"
      });
  
    }); 
}

Answer №1

Give this code a try in your project

For more information, check out the Google Official Documentation here

import GoogleMapsLoader from 'google-maps';
import { google } from 'google-maps';

ngAfterViewInit() {

let el = this._elementRef.nativeElement.querySelector('.contact-us');

GoogleMapsLoader.KEY = 'g4554645645645645645646';

GoogleMapsLoader.load((google) => {

let myLatlng = new google.maps.LatLng(23.5454, 90.8785);

let map = new google.maps.Map(el, {
    center: new google.maps.LatLng(23.8787878, 90.87878),
    zoom: 18,
    mapTypeId: google.maps.MapTypeId.ROADMAP
});

let marker = new google.maps.Marker({ 
      draggable: true,
      animation: google.maps.Animation.DROP,
      position: myLatlng,
      map: map,
      title:"Hello World!"
    });

});

Include the following code snippet in your Template.html file:

<div class="contact-us" style="position: relative; height: 470px;"></div>

Answer №2

The marker function in the code snippet above appears to differ from what is outlined in the official documentation available here.

 const map = new google.maps.Map(el, {
        center: new google.maps.LatLng(44.5403, -78.5463),
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP

      });
 
 const marker = new google.maps.Marker({ 
        draggable: true,
        animation: google.maps.Animation.DROP,
        position: myLatlng,
        map: map,
        title: "Hello World!"
      });

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

Is there a way to set the default timezone for the entire application to something like 'UTC' using JavaScript and Angular?

I'm currently developing a Hotel application where customers communicate using UTC. I have completed most of the work but everywhere I used the date object like so => new Date(). Before running the application, I need to change my local timezone to ...

Set up linter rules that utilize `useEffect` in place of `React.useEffect` (utilizing named export rather than full export)

It's important in our codebase to always use: import { useEffect } from 'react'; instead of: import React from 'react'; // use in code as `React.useEffect` Can we enforce this rule with longer eslint rules? If so, how can we impl ...

Is it still relevant to use the href attribute in Angular development?

Is there any specific benefit to either including or excluding the href attribute on internal links within an Angular 7 single-page application? Regardless, the functionality remains intact as Angular primarily relies on the routerLink attribute. ...

What is the reason behind the never return value in this typescript template?

As demonstrated in this example using TypeScript: Access TypeScript Playground type FirstOrSecond<condition, T1, T2> = condition extends never ? T1 : T2 type foo = never extends never ? () => 'hi' : (arg1: never) => 'hi' ...

Discovering the interface type of class properties in order to implement a factory method

I am struggling with implementing a factory method in my code. I want to be able to pass not only a Class type to instantiate but also a set of default values for the properties within the class. My goal is to have the compiler notify me if I try to pass i ...

Assign the primeng dropdown's value to the model in a reactive form

I am currently encountering an issue while populating a form that contains several PrimeNg dropdowns. To simplify, let's consider an example similar to the ones provided on their website. <form [formGroup]="myFormGroup"> <p-dropdown [optio ...

An error in Typescript is indicating that a semicolon is expected. The identifier 'EventNameString' is currently being used as a value, even though it only refers to a type

I've been working on integrating Firebase phone authentication into an older Ionic project and have followed several tutorials. I was able to successfully implement it, but whenever I run ionic serve -l, I encounter the following error: Interestingly ...

Is a special *ngFor required when implementing Angular2 with Nativescript?

My current project involves creating a mobile app that requires listing a few labels. Here is the code snippet: @Component({ selector: 'code-m', template: ` <StackLayout dock="top" orientation="vertical" style="height: ...

What could be causing my component to not refresh when used as a child?

I have been experimenting with some code to track rerenders. The initial approach failed when passing <MyComponent> as a child component. it("should return the same object after parent component rerenders", async () => { jest.useF ...

Displaying geoJSON data from a variable instead of a file is a feature implemented by

Let's say I have a geoJSON data stored in a variable or parsed as an object: // GeoJSON stored as an object var segment = segment; // GeoJSON saved as a JSON string var json = JSON.stringify(segment); Now, the challenge is to display this geoJSON o ...

When working with Angular, the onSubmit method may sometimes encounter an error stating "get(...).value.split is not a function" specifically when dealing with Form

When the onSubmit method is called in edit, there is an error that says "get(...).value.split is not a function" in Form. // Code for Form's onSubmit() method onSubmitRecipe(f: FormGroup) { // Convert string of ingredients to string[] by ', ...

What is a more organized approach to creating different versions of a data type in Typescript?

In order to have different variations of content types with subtypes (such as text, photo, etc.), all sharing common properties like id, senderId, messageType, and contentData, I am considering the following approach: The messageType will remain fixed f ...

What is the best approach for incorporating a customized set of valid keywords into a text input field in JHipster while maintaining a sophisticated design?

My code snippet is not displaying the input even though all the necessary elements are in place: home.component.ts <p class="lead">Input: </p> <div><jhi-calculator-input></jhi-calculator-input></div> calculator.compon ...

The Ng4LoadingSpinner will automatically stop after 5 seconds

When utilizing Ng4LoadingSpinner, I encountered an issue where it disappears automatically after the default timeout of 5 seconds, even though our request is still processing. Increasing the timeout resolves the problem, but I am seeking an alternative s ...

Extract the Top X elements from a multidimensional array

Consider an Array that consists of nested arrays: [ ["2000-01-01", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a9a8abe091b6bcb0b8bdffb2bebc">[email protected]</a>", 1, 9, 338], ["2000-01-01", "<a href="/ ...

Working with JSON data in AngularJS2's templates

Is there a way for me to process JSON from the template in a manner similar to the second code I provided? First code. This method works well when using .json and .map () @Component({ ..// template: `..// <li *ngFor="#user of users"> ...

Comparing Angular 2 Components and AngularJS Directives: What Sets

Are there any parallels or distinctions between an angular2 component and an AngularJS directive? It seems that these two share similar functionalities in the angular2 component and AngularJS directive. Additionally, angular2 also incorporates a directive ...

Having trouble with react-responsive-carousel in Next.js version 13?

I have been following a tutorial to create an eBay clone. One of the steps involves creating a carousel. However, when I add it, the carousel does not transition to the next page. I have attempted to uninstall and reinstall packages, but the issue persists ...

The function type '() => JSX.Element' cannot be assigned to the type 'ReactNode'

I am encountering an issue while trying to display a component using an object. The code is throwing an error: const Login = () => <>login</> const publicRoutes = [ { path: '/login', component: Login } ] function AppR ...

Populate List Items until Maximum Capacity is Reached and Increase the

Is there a way to make a ListItem fill the list vertically while also being able to overflow it if needed? I'm looking for a solution that would allow me to access the height of the empty space in the list, which I believe would be the minHeight. Som ...