Unable to update markers on agm-map for dynamic display

In my Angular 5 application, I am utilizing Angular Google Maps (https://angular-maps.com/) along with socket.io for real-time data updates of latitude and longitude from the server. Although I am successfully pushing the updated data to an array in the component, the agm-map on the UI is not reflecting these changes.

Below is the code snippet from my component.ts file:

import { Component, OnInit } from '@angular/core';
import { SocketService } from '../../app/services/socket.service';

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

  public title: string = 'AGM project';
  public lat: number = 12.954517;
  public lng: number = 77.3507335;


  public msg : string;
  public mcar = "https://maps.google.com/mapfiles/kml/shapes/parking_lot_maps.png";
  public agmMarkers: agmmarker[] = [
    {
      lat: 12.954517,
      lng: 77.3507335,
      icn: this.mcar
    }
  ];

 constructor(private socketService : SocketService) { }

ngOnInit() {
 this.socketService.getMessage().subscribe((msg: any) => {
      console.log("msg: "+JSON.stringify(msg));
      this.updateMarkers(msg);
    });
}

public updateMarkers(msg){
 this.agmMarkers = [];
  for (let entry of msg.stats) {
    console.log("entry.latlng.lat: "+entry.latlng.lat); 
    console.log("entry.latlng.lng: "+entry.latlng.lng); 
    this.agmMarkers.push({
      lat: entry.latlng.lat,
      lng: entry.latlng.lng,
      icn: this.mcar
    });
  }
 }
}

interface agmmarker {
  lat?: number;
  lng?: number;
  icn?: string;
}

Here is the snippet from my component.html file:

<agm-map [latitude]="lat" [longitude]="lng">
    <agm-marker *ngFor="let i of agmMarkers" 
      [latitude]="i.lat" [longitude]="i.lng" [iconUrl]="i.icn">
    </agm-marker>
</agm-map>

Answer №1

Apologies for the mistake. It turns out that the service's response was in string format.

this.agmMarkers.push({
  lat: +entry.latlng.lat,
  lng: +entry.latlng.lng,
  icn: this.mcar
});

Casting the latitude and longitude as numbers successfully resolved the problem.

Answer №2

I am currently implementing the use of "@agm/core": "^1.0.0-beta.2

   import { MapsAPILoader } from '@agm/core';



    export class JovenComponent implements OnInit
         { 

        constructor(public mapsApiLoader: MapsAPILoader) {}
        ngOnInit() {
                     //once the data is retrieved from the service, assign it to this.joven
                    //the variable data contains all the required information
                      this.mapsApiLoader.load().then(()=>{
                      this.lat=Number(this.joven.user_residential_address.latitude);
                      this.lng=Number(this.joven.user_residential_address.longitude);
                         })
                   }
          }

Incorporate into HTML

<agm-map [latitude]="lat" [longitude]="lng" [zoom]="zoom" [disableDefaultUI]="true">
                      <agm-marker [latitude]="lat" [longitude]="lng">
                        <agm-info-window>
                          <strong>{{joven.name}}</strong>
                          <br/>
                          <strong>City: {{joven?.user_residential_address?((joven?.user_residential_address?.city!==null)?joven?.user_residential_address?.city:'&mdash;'):'&mdash;'}}
                          </strong>
                          <br/>
                          <strong>State Code: {{joven?.user_residential_address?((joven?.user_residential_address?.stateCode!==null)?joven?.user_residential_address?.stateCode:'&mdash;'):'&mdash;'}}
                          </strong>
                          <br/>
                          <strong>ZIP Code: {{joven?.user_residential_address?((joven?.user_residential_address?.zipcode!==null)?joven?.user_residential_address?.zipcode:'&mdash;'):'&mdash;'}}
                          </strong>
                        </agm-info-window>
                      </agm-marker>
                    </agm-map>

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

Testing React Hook Form always returns false for the "isValid" property

When creating a registration modal screen, I encountered an issue with the isValid value when submitting the form. In my local environment (launched by npm start), the isValid value functions correctly without any issues. However, during unit testing us ...

Successfully upgraded Angular 7 to 8, however, encountering an issue with the core not being able to locate the rxjs module

After updating my Angular version from 7.X to 8.2.5, everything seemed fine until I started getting errors related to the rxjs module within the angular/core package. Despite having the latest version of rxjs (6.5.3), the errors persisted even after removi ...

The information is failing to display properly within the mat-menu

Recently, I've been working on creating a navbar that includes a submenu. Even though the navigation bar data is loading properly, I am facing some issues with the submenu functionality. As a beginner in this area, I would appreciate any help or guida ...

Placing files in the "Dist" folder is causing an issue by disrupting the functionality of the Angular 2 app

For testing my login component in Angular2, I am using a mockBackend within my app. Initially, the standalone version of the login worked perfectly fine. However, when trying to integrate it into my ongoing development project, I encountered an issue. Duri ...

Using TypeScript with React: Updating input value by accessing event.target.nodeValue

As a newcomer to TypeScript, I am in search of an elegant solution for the following dilemma. I have a state variable named emailAddress, which is assigned a value from an input field. Additionally, I need the input field to display and update its value ba ...

Guide to setting up a trigger/alert to activate every 5 minutes using Angular

limitExceed(params: any) { params.forEach((data: any) => { if (data.humidity === 100) { this.createNotification('warning', data.sensor, false); } else if (data.humidity >= 67 && data.humidity <= 99.99) { ...

The CSS properties intended for ion-button elements are not taking effect

I'm attempting to set a background color when a ion-button is clicked or maintain the ion-ripple effect after it has filled the button in Ionic 4. I experimented with applying custom CSS states in global.scss, but encountered issues where the active ...

How do I implement a click event in an item list using Angular 5?

As a novice student delving into Angular 5, I am faced with an issue that may also arise in Angular 2. Currently, I am working on a project where I need to implement a basic search input feature. The idea is to allow users to type in the name of a city an ...

Encountered an issue: Unable to access the property 'querySelectorAll' of null and Unable to access the property 'getElementsByTagName' of null

*<div class="col-md-12" *ngIf="data_client2.length>0"> <button class="btn print" printSectionId="listVotantesPrint" ngxPrint i18n="@@downloadList"></button> ' <button class=&qu ...

Why is there a discrepancy between the value displayed in a console.log on keydown and the value assigned to an object?

As I type into a text box and log the keydown event in Chrome, I notice that it has various properties (specifically, I'm interested in accessing KeyboardEvent.code). Console Log Output { altKey: false bubbles: true cancelBubble: false cancelable: t ...

Issue with subscribing in a MEAN stack application

Currently, I have completed the backend development of my application and am now working on the frontend. My focus at the moment is on implementing the register component within my application. Below is the code snippet for my Register Component where I a ...

Guide to integrating Mongoose typings with Angular 2 webpack starter

As a newcomer, I'm hoping this issue is straight forward. I am currently utilizing the angular2-webpack-starter found on GitHub. Based on the mongoose documentation, it appears that including their JavaScript file allows for accessing a global varia ...

Form remains unchanged after manipulation in callback

Currently, I have a form with a list of editable objects (constants). Previously, it was possible to delete any object without confirmation. Now, I want to add a ngBootbox confirm step before the deletion process. In my .ts file, the code for deleting an ...

I am experiencing an issue where the mat-header-cell components are not appearing after navigating

After initially loading the page, mat-header-cell displays fine. However, upon navigating to a second page, refreshing it in the browser, and then returning to the original page, the mat-header-cell is no longer visible. It only reappears after manually re ...

Display a loading indicator when loading a lazy loaded module in Angular 2

Here's my situation: I have a menu with various options that should be displayed based on user permissions. The majority of the menu items are contained within modules, and these modules are lazy loaded. This means that when a user clicks on a menu it ...

Develop a versatile factory using Typescript

For my current project, I am developing a small model system. I want to allow users of the library to define their own model for the API. When querying the server, the API should return instances of the user's model. // Library Code interface Instanc ...

What is the most effective method to create a versatile function in Angular that can modify the values of numerous ngModel bindings simultaneously?

After working with Angular for a few weeks, I came across a problem that has me stumped. On a page, I have a list of about 100 button inputs, each representing a different value in my database. I've linked these inputs to models as shown in this snipp ...

Understanding the connection between two unions through TypeScript: expressing function return types

Within my codebase, I have two unions, A and B, each with a shared unique identifier referred to as key. The purpose of Union A is to serve as input for the function called foo, whereas Union B represents the result yielded by executing the function foo. ...

Establishing a standard value for a class that can be injected

Here is my desired approach: @Injectable() export class MyInjectableClass { constructor(timeout: number = 0) { } } The goal is to have the timeout set to 0 when it's injected, but allow the calling code to specify a different value when constr ...

Tips for accurately mapping JSON from an Angular 5 POST request to a Java entity with RestEasy integration

Below is code snippet from an Angular 5 component: export class TripsComponent implements OnInit { ... ... addTrip() { let newTrip = new Trip(this.new_trip_name, this.new_trip_description, this.company); this.tripService.addTrip(newTrip).t ...