What are the best ways to work with LatLng objects?

When I run a request to retrieve data from a database, the response displayed in the console using JSON.Stringify() is as follows:

sites : [{"siteName":"Site de Marseille",
"siteAdress1":"rue du string",
"siteAddress2":"string",
"siteCodPost":"13010","siteTown":"Marseille",
"id":"5d0ce7c4a06b07213a87a753",
"companyId":"5cd430745304a21b9464a219",
"customerId":"5cd430c65304a21b9464a21a",
"points":
[
 {"lat":44.841225,"lng":-0.580036},
 {"lat":44.842236,"lng":-0.64696},    
 {"lat":44.805615,"lng":-0.63084}]}
]

This data includes various properties, one of which is an array of latitude and longitude coordinates. To access this data, I am using the following code:

 this.customerApi.getSites(this.currentUser.id)
.subscribe(response => {
  this.sites = response;
  console.log('sites : ' + JSON.stringify(this.sites));
});
  }

The subscription returns an Observable that I can view in the console.

My objective is to extract the "points" property and store it in an array of arrays since multiple records may be returned by the backend system. This nested structure would allow me to plot polygons on Google Maps using the Angular Google Map component.

To achieve this, I have initialized the following:

rectangles: Array<Array<LatLngLiteral>> = [];

And within the subscribe function, I do the following:

.subscribe(response => {
  this.sites = response;
  this.rectangles.push(this.sites.points); 

However, the rectangles array remains empty.

If you have any suggestions or ideas that could assist me, please share them with me.

Thank you for your assistance.

Answer №1

After reviewing your data structure, it appears that 'sites' is an array. Therefore, attempting to access this.sites.points will result in it being undefined.

To achieve what you want, use:

this.rectangles.push(this.sites.map(s => s.points))

The issue lies in trying to access the property sites on an array. Arrays do not possess such a property, hence resulting in it being undefined. Arrays are structured with predefined functions and properties like length or map

For illustration purposes:

const exampleObject = {propertyA: "value", propertyB: "another value" }

//accessing properties on object

//"value"
exampleObject.propertyA

//"another value"
exampleObject.propertyB

const exampleArray = ["one", "two", "three"]

//propertyA does not exist = undefined
exampleArray.propertyA

//length property exists for all arrays = 3
exampleArray.length

Arrays do have a function called map, which executes a function on each element and returns a new array. It's typically used for transforming data structures or accessing deeply nested elements.

This shorthand version simplifies it:

this.sites.map(s => s.points)

In actuality, it translates to this:

const pointsArray = this.sites.map(s => {
       //s represents a single element in the sites array
       // s has a 'points' property, which is an array
       return s.points
    })

// now that we have an array of points, we can add it to rectangles

this.reactangles.push(pointsArray)

I hope this explanation provides clarity.

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

Typescript's definition file includes imports that can result in errors

Occasionally, typescript may generate a definition file with code like the following, leading to compile errors: // issue.ts import { Observable } from 'rxjs'; class Issue { get data() { return new Observable(); } } // issue.d.ts class ...

Tips on ensuring JSON object structure with type and interface in an Angular application

In my angular project, I have created a router config file to handle routing efficiently. This config file contains JSON data like this: router.config.ts { branch:{ list:'/app/branch/list', add:'/app/branch/add' }, ...

Encountering a Typescript issue with mongoose

Working with node.js and various email addresses, I encountered a compile error: TS2345: Argument of type '(error: any, document: any) => void' is not assignable to parameter of type '(err: any) => void'. This error occurs at ...

What is the approach to constructing an observable that triggers numerous observables depending on the preceding outcome?

One of my endpoints returns { ids: [1, 2, 3, 45] }, while the other endpoint provides values for a given id like { id: 3, value: 30, active: true }. I am currently attempting to create an observable that will call the first endpoint and then, for each id r ...

Connecting Angularfire2 with Firestore for advanced querying

Glad you stopped by! Currently, I have two Firestore Collections set up in my Angularfire2 application. One consists of "Clients", while the other contains "Jobs". Each client can have multiple jobs assigned to them, and vice versa. I've been workin ...

Angular 9: The instantiation of cyclic dependencies is not allowed

After transitioning from Angular 8 to Angular 9, I encountered an issue with a previously functioning HTTP communication service. The error message now reads: Error: Cannot instantiate cyclic dependency! HttpService at throwCyclicDependencyError (core ...

Challenge with sharing an array from a different component in Angular using @Input()

Recently, I started learning Angular and decided to create a basic blog application. While trying to retrieve a property from another component using the @Input() decorator, I encountered an issue specifically related to arrays. In a post-list-item compone ...

Implementing debounceTime in Angular can be done by using the debounceTime operator

I am currently working on implementing the debounceTime functionality in an autocomplete feature. My goal is to use debounceTime to minimize the number of server calls. After researching, I found 3 possible solutions which I have included snippets of belo ...

Developing interconnected dynamic components in Angular

Can you help me figure out how to create nested dynamic components while maintaining the parent-child relationship? For instance, if I have data structured like this: - A --A.1 --A.2 -B --B.1 -C I want to build components that reflect this structure, su ...

Break apart the string and transform each element in the array into a number or string using a more specific type inference

I am currently working on a function that has the ability to split a string using a specified separator and then convert the values in the resulting array to either strings or numbers based on the value of the convertTo property. Even when I call this fun ...

Access Select without needing to click on the child component

I am curious to learn how to open a Select from blueprint without relying on the click method of the child component used for rendering the select. <UserSelect items={allUsers} popoverProps={{ minimal: false }} noResults={<MenuItem disabled={ ...

What is the best way to outline the specifications for a component?

I am currently working on a TypeScript component. component @customElement("my-component") export class MyComponent extends LitElement { @property({type: String}) myProperty = "" render() { return html`<p>my-component& ...

Unable to find any routes that match child routes using the new Angular 2 RC1 router

ApplicationComponent import { Component } from '@angular/core'; import {Router, ROUTER_DIRECTIVES, Routes, ROUTER_PROVIDERS} from '@angular/router'; import {SchoolyearsComponent} from "./schoolyear/schoolyears.component"; @Component({ ...

Unexpected behavior of TypeScript optional object key functionality

I am facing an issue with an object that has conditional keys. For example: const headers: RequestHeaders = {}; if (...) { headers.foo = 'foo'; } if (...) { headers.bar = 'bar'; } As a newcomer to TS, I initially thought this wo ...

Angular has the feature of a right float button with *ngfor

I've successfully implemented a form using Reactive Forms in Angular. Currently, my form is displayed as follows: <div class="center" appMcard> <form [formGroup]="GroupRMPM_FG"> <div formArrayName="GroupId_Name" *ngFor="let ...

Create an instance of a class from a group of subclasses, all the while retaining the ability to access static members in Types

I seem to have encountered a dilemma where I am looking to have both the static and abstract keywords used for a member of an abstract class in TypeScript, but it appears that this combination is not supported. The nearest workaround I could come up with ...

The link button appears unselected without a border displayed

I am facing an issue with a link button in my code. Here is the snippet: <div class="col-2"> <a type="button" routerLink="auto-generate-schedules/generate" class="btn btn-primary mb-2">Generate Sche ...

Issues with type errors in authentication wrapper for getServerSideProps

While working on implementing an auth wrapper for getServerSideProps in Next.js, I encountered some type errors within the hook and on the pages that require it. Below is the code for the wrapper along with the TypeScript error messages. It's importan ...

The issue arises when TypeScript declarations contain conflicting variables across multiple dependencies

My current project uses .NET Core and ReactJS. Recently, I updated some packages to incorporate a new component in a .tsx file. Specifically, the version of @material-ui/core was updated from "@material-ui/core": "^3.0.3" to "@material-ui/core": "^4.1.3" i ...

Retrieve: Type 'string | undefined' does not match the parameter type 'RequestInfo'

When using the fetch function, I encountered an error with the "fetchUrl" argument: Error: Argument of type 'string | undefined' is not assignable to parameter of type 'RequestInfo'. This is the code snippet where the error occurred: ...