Tips for converting string values from an Observable to numbers using the parseFloat() method

Having trouble converting text to numbers for geolocation coordinates. My model consists of a site with an ID and an array of points as a property. Rather than creating a relationship between site and points, I've structured it differently.

In my code:

points: Array<any> = [];

Rectangles is defined as an array of arrays:

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

I am looping through sites for a specific customer, constructing the rectangles array to display on Google Maps. Each rectangle contains arrays representing the sites from the database. For example, if there are two sites, the rectangle array would look like this:

rectangles : [[
[
   {"lat":44.841225,"lng":-0.580036},
   {"lat":44.842236,"lng":-0.64696},
   {"lat":44.805615,"lng":-0.63084}
],
[
   {"lat":44.819868,"lng":-0.582811},
   {"lat":44.853709,"lng":-0.483573},
   {"lat":44.80696,"lng":-0.53299},
   {"lat":44.80696,"lng":-0.629078}
]]] 

The code snippet to retrieve this data is:

this.customerApi.getSites(this.currentUser.id)
  .subscribe(response => {
    this.sites = response;
    this.rectangles.push(this.sites.map(s => s.points));
  });
}

An example of the structure of a site object:

sites : 
[
    {
    "siteName":"Site de Marseille",
    "siteAdress1":"rue de blabla",
    "siteAddress2":"string",
    "siteCodPost":"13010",
    "siteTown":"Marseille",
    "points":
       [
         {"lat":44.841225,"lng":-0.580036},
         {"lat":44.842236,"lng":-0.64696},
         {"lat":44.805615,"lng":-0.63084}
        ],
    "id":"5d0ce7c4a06b07213a87a753", 
    "companyId":"5cd430745304a21b9464a219",
    "customerId":"5cd430c65304a21b9464a21a"
    }
    ,
    {
"siteName":"Site de Bordeaux",
"siteAdress1":"rue de la  Garonne",
"siteAddress2":"string",
"siteCodPost":"31000",
"siteTown":"Bordeaux",
"points":
    [
        {"lat":44.819868,"lng":-0.582811},
        {"lat":44.853709,"lng":-0.483573},
        {"lat":44.80696,"lng":-0.53299},
        {"lat":44.80696,"lng":-0.629078}
    ],
"id":"5d0cf65fa06b07213a87a754",
"companyId":"5cd430745304a21b9464a219",
"customerId":"5cd430c65304a21b9464a21a"}]

Need help figuring out the proper format for the rectangles array to correctly show rectangles on Google Maps. Maybe I need to adjust the number of square brackets due to the data format issue.

Tried using

points: Array<LatLngLiteral> = [];
but it didn't work. Uncertain about where or how to use parseFloat() method, if needed.

If you have any ideas or suggestions, please share!

Answer â„–1

Hello,

In TypeScript, there isn't a specific `float` type available. However, you can create a function to check the content of a string and convert it to a float if necessary. Here's an example function for achieving this:


getFloatValue(val) {
    if (val.indexOf('.') > -1) {
        try {
            eval(val);
            return parseFloat(val);
        }
        catch(error) {
            console.log('error');
        }
    }
    return val;
}

This function can be used to convert any string to a float value as needed. You can apply it to properties of an object like so:


let lat = getFloatValue(rectangle[0].lat);

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

What is the syntax for nesting an array within another array in PHP?

Help needed to create an array inside another array. Two variables are available with arrays: $first = [12, 23, 34]; $second = [32, 21, 43]; The desired format of the combined array is: $combine = {'name'=>'data1', [[12,32], [23,2 ...

Transform an Angular application built using the Meteor framework to an Express JS-Angular application

Is there an automated or minimalist way to transform an application with a meteor backend and angular frontend to use a backend in Express js and keep the frontend using vue js instead? I have not been able to find any resources or documentation that prov ...

The input elements fail to register the passed-in value until they are clicked on

I am experiencing an issue with my form element that contains a few input fields. Two of these inputs are set to readOnly and have values passed in from a calendar element. Even though the input elements contain valid dates, they still display an error mes ...

Comparing values in an array with PHP

Hello everyone, I could really use your assistance. Let's consider a scenario where I have an array. $arr = array( 1 => array( key1 => something, key2 => something, key3 => something, testkey => 3 ...

How to implement a toggle button in an Angular 2 application with TypeScript

Currently, I'm working with angular2 in conjunction with typescript. Does anyone know how to generate a toggle button using on - off?. ...

Tips for customizing md-autocomplete styling in Angular 4 using SCSS

I have developed an application that utilizes md-autocomplete from material.angular.io. The issue arises when I attempt to search for items, as the dropdown suggestions have a narrower width. Therefore, I am looking to expand the width of md-autocomplete. ...

I'm facing the challenge of trying to work on an Angular project without access to the node_modules folder, and unfortunately, I

Error report regarding npm resolution While resolving: [email protected] Found: @angular/[email protected] node_modules/@angular/common @angular/common@"^14.2.12" from the root project Could not resolve dependency: peer @angular/commo ...

How come this constant can be accessed before it has even been declared?

I find it fascinating that I can use this constant even before declaring it. The code below is functioning perfectly: import { relations } from 'drizzle-orm' import { index, integer, pgTable, serial, uniqueIndex, varchar } from 'drizzle-orm ...

Is there any need for transpiling .ts files to .js when Node is capable of running .ts files directly?

If you are using node version 12, try running the following command: node hello.ts I'm curious about the purpose of installing typescript globally with npm: npm install -g typescript After that, compiling your TypeScript file to JavaScript with: ...

Steps to resolve the issue: angular/[email protected] - unable to resolve the dependency

Encountering a challenging compiler error, I am determined to find a solution. Despite numerous attempts to install different library versions, the issue persists. It appears that the firebaseui-angular package necessitates an alternative angular/fire ver ...

Using browser.actions().mouseMove() in conjunction with sendKeys results in a syntax error

I am currently working on a test automation project and utilizing protractor with the jasmine framework. I am facing an issue while dealing with an autocomplete selection drop-down (for example, a countries' name drop-down). I want to input keys into ...

Developing React component libraries with TypeScript compared to Babel compiler

Currently, I'm utilizing the babel compiler for compiling my React component libraries. The initial choice was influenced by Create React App's use of the same compiler. However, I've encountered challenges with using babel for creating libr ...

Setting the data type of a value in a deeply nested object path using Typescript

I need to figure out how to determine the value types for all keys within nested object paths. While I have been successful in most cases, I am struggling with setting the value type for a deep nested property inside an array object. interface BoatDetails ...

Error message encountered in Nativescript app on Android only appears in Release build due to java.lang.Unsatisfied

I am encountering an issue with my NativeScript app where it runs smoothly in debug mode but crashes on startup in release mode. The logs reveal the following error message: 01-15 16:23:01.474 12229 12229 E script.demo: No implementation found for void co ...

This error message indicates that the certificate for Angular 13 has expired

After successfully installing Angular and verifying the version, I encountered an issue when attempting to run the command npm start. Despite multiple attempts at uninstalling and reinstalling everything, the problem persists. Running npm install also resu ...

Converting ISO date format to 'MM/DD/YYYY' format in a Bootstrap/Angular application

Is there a way to convert an ISO date string to 'MM/DD/YYYY' on load in a bootstrap/angular environment? Upon loading, the date picker currently displays like this: https://i.sstatic.net/g5MkI.jpg We want the user to input the date in 'MM/ ...

Exploring the automated retrieval of data from arrays in Java objects: A comprehensive guide

My goal is to automatically create Java objects from JSON data obtained from a REST API. The JSON array contains properties of different shops, and I aim to generate one object per shop with all its respective properties. The following code helped me achi ...

Display two elements from the array on each line, with the elements separated by a comma

Can anyone assist me with this issue? I have an array containing 6 items, and I would like to display 2 items per line separated by commas. Here is the code I am currently using: $rates[] = array("2020-01-01"=>3000); $rates[] = array("2020-01-02"=>30 ...

What methods does Angular use to determine the parameter types of a constructor?

I've been experimenting with replicating Angular's approach to interpreting the constructor in an injectable service. function Injectable() { return function<T extends { new (...args: any[]): {} }>(con: T) { return class extends con ...

Generate an interactive sitemap.xml in ReactJS for each request made to http://example.com/sitemap.xml

I am working on a single-page application (SPA) using reactjs, and I have links in the format of http://example.com/blog/:id. I want to dynamically generate a sitemap for this site. While I'm aware that there are npm packages like react-router-sitema ...