Steps to dynamically include a marker on a Google Maps component using HTTPGET in Angular 6

I am currently working on an Angular 6 application that involves integrating the Google Javascript API with AGM. So far, the map functions well except for dynamically adding markers using an http get request.

Here is a snippet of the component.html:

<agm-map [latitude]="51.017467" [longitude]="10.233982">
    <agm-marker *ngFor="let position of positions" [latitude]="position.latitude"
                [longitude]="position.longitude"></agm-marker>
</agm-map>

And in the component.ts:

export class EventsListComponent {
 public positions = [new Position(51.017467, 10.233982)]; // static point for debug

 constructor(public http: HttpClient) {
  let eventIds: string[] = ['5bffbac5596a7de59190dfbb']; // also for debug
  for (let eventId of eventIds) {
    this.http.get<Address>("api/v1/Events/Get/" + eventId +"/GetVenue/GetAddress").subscribe(result => {
      console.log(result);
      this.addresses.push(result);
    });
  }
}

export class Address {

  constructor(
    public latitude: number,
    public longitude: number,
    public addressLine: string,
    public city: string,
    public state: string,
    public country: string,
    public zip) {
  }
}

The following data is displayed in the console:

{
"addressLine":"Gartenstraße 7",
"city":"Eschwege",
"country":"Germany",
"zip":"37269",
"state":"Hessen",
"latitude":"51.1821073",
"longitude":"10.0572713"
}

This results in:

https://i.sstatic.net/cbKgs.png

Although the marker appears in the DOM, it does not show up on the map (the visible marker is the static one).

Alternative Approach Attempted:

I have successfully added markers dynamically by using button presses as follows:

<button (click)="btnClick()" class="btn btn-primary"></button>

Then, in the component.ts:

btnClick() {
    this.addresses.push(new Address(51.1821073, 10.0572713,"","","","",""));
}

This results in:

https://i.sstatic.net/Hmj09.png

The marker now appears both in the DOM and on the map.

Another Alternative Attempt:

I tried placing the http get request inside the method triggered by the button press like this:

btnClick() {
    this.http.get<Address>("api/v1/Events/Get/" + eventId +"/GetVenue/GetAddress").subscribe(result => {
    console.log(result);
    this.addresses.push(result);
  });
}

However, it only adds the marker to the DOM but not the map.

Any suggestions or ideas?

Answer №1

It appears that the issue may lie in how the lat/lng values are being passed - as a string or a number depending on the context. In your console log, they are surrounded by double quotes, indicating they are strings, while manually adding them treats them as numbers. You can resolve this discrepancy by converting the values to numbers before pushing them into the addresses array:

this.addresses.push({
  addressLine: result.addressLine,
  city: result.city,
  country: result.country,
  zip: result.zip,
  state: result.state,
  latitude: +result.latitude,
  longitude: +result.longitude
});

If you prefer a more concise solution, consider the following approach:

result.latitude = +result.latitude;
result.longitude = +result.longitude;
this.addresses.push(result);

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

Incorporate the Angular async pipe along with BehaviourSubject/ReplaySubject to enhance performance with auditTime/debounceTime

Trying to subscribe to a BehaviorSubject/ReplaySubject using the Angular async pipe has been challenging for me. In addition, I need to incorporate either the auditTime or debounceTime operator to filter out certain values. Below is an example (I utilized ...

Angular's ng toolkit universal experiencing loading issues and tools are malfunctioning

I encountered the following issue npm run build: prod commands are not functioning correctly ERROR: Cannot read property 'length' of undefined ERROR: If you think that this error shouldn't occur, please report it here: https://githu ...

update component following an ajax request

I attempted the suggested solutions for similar questions, however, they proved ineffective. Upon inserting data into my database, I am looking to update my component (with the user remaining on the same component). I tried navigating directly to the com ...

When working with Angular/Typescript, the error message "compilation of 'export const' is not possible

Embarking on creating my very own Angular library, I took the first step by adding a service without any issues. The challenge arose when I decided to move a constant to a file named tokens.ts for the service to reference. Following this change, the build ...

Troubleshooting: Icon missing from React vscode-webview-ui-toolkit button

In the process of developing a VSCode extension using React and the WebUi Toolkit library for components, I encountered an issue with adding a "save" icon to my button. I diligently followed the documentation provided by Microsoft for integrating buttons i ...

Learn the process of inserting a table in ExcelJS specifically for Angular applications

I encountered an issue when attempting to add a table with data. An error message stating "AddTable is not function" appeared. let workbook = new ExcelJS.Workbook(); let worksheet = workbook.addWorksheet("Data"); worksheet.addTable({ name: 'My ...

What are the steps for changing this JavaScript file into TypeScript?

I'm currently in the process of converting this JavaScript file to TypeScript. However, I've encountered an error with the onClick function as shown below: import React from 'react'; import { Popover } from 'antd'; import A fr ...

ts:Accessing the state within a Redux store

In my rootReducer, I have a collection of normal reducers and slice reducers. To access the state inside these reducers, I am using the useSelector hook. Here is my store setup : const store = configureStore({reducer : rootReducer}); Main Reducer: const ...

Utilizing Dynamic Class Names in Angular 7 with Typescript

In the process of developing an Angular 7 application, I have created a form component that is intended to be used for various entities. As part of this, I defined a variable route: {path: ':entity/create', component: FormComponent} While this ...

Implementing JWT authentication with express-restify-mongoose in MEAN Stack for selected REST methods

As a newcomer to this world, I appreciate your patience with me. I am attempting to create a REST API using the MEAN stack, and in an effort to simplify things, I have been utilizing the following resource: https://github.com/florianholzapfel/express-res ...

Tips for exporting/importing only a type definition in TypeScript:

Is it possible to export and import a type definition separately from the module in question? In Flowtype, achieving this can be done by having the file sub.js export the type myType with export type myType = {id: number};, and then in the file main.js, i ...

Is it possible for Angular's ngStyle to accept multiple functions? If not, what is the alternative solution?

Can multiple conditions be added to different attributes with ngStyle? Is it possible to change text color and background color based on specific JSON values using ngStyle? About the Project: I am currently working on creating a tab bar that resembles a ...

Include a new module in the declarations NgModule utilizing ts-morph

Currently, I am utilizing the ts-morph library and my objective is to add a new component to the declarations: This is my initial setup: @NgModule({ declarations: [], imports: [], providers: [], }) Here is what I am aiming for: @NgModule({ declarations: [ ...

What are the steps to convert this code into Angular syntax?

After realizing that using jQuery alongside Angular is not a good practice, I am determined to modify my code in this Angular App to eliminate the need for jQuery. Currently, I have a page that displays menu items fetched from the server and I loop throug ...

Animation of lava effect in Angular 7

I have a unique Angular 7 application featuring a homepage with a prominent colored block at the top, along with a header and various images. My goal is to incorporate lava effect animations into the background similar to this CodePen example. If the link ...

What is the best method for exporting and importing types in React and Next.js apps?

Is there a way to export and import types from API responses in TypeScript? I have a type called Post that I want to re-use in my project. // pages/users.tsx type Post = { id: number; name: string; username: string; email: string; address: { ...

Bring in a collection of classes of various types from one TypeScript file to another

In my code file exampleA.ts, I define an object as follows: import { ExampleClass } from 'example.ts'; export const dynamicImportations = { ExampleClass }; Later, in another file named exampleB.ts, I import an array that includes class types and ...

Is there a way to specifically target the MUI paper component within the select style without relying on the SX props?

I have been experimenting with styling the Select MUI component using the styled function. I am looking to create a reusable style and move away from using sx. Despite trying various methods, I am struggling to identify the correct class in order to direct ...

Having trouble injecting HttpClient in a hybrid AngularJS/Angular app that has been upgraded with ngUpgrade? You may come across the error message "NullInjectorError: No provider for http_HttpClient!"

My AngularJS/Angular hybrid app, upgraded with ngUpgrade, has been functioning well. The new Angular components (downgraded) work seamlessly in the AngularJS app. However, I'm encountering an issue where the HttpClient module fails to instantiate. I ...

Puzzled by the specialized link feature

As I delve into the world of React and Next.js, I find myself working on the link component. Initially, I had a grasp on basic routing in next.js which seemed pretty straightforward. However, things took a confusing turn when I stumbled upon this code: imp ...