Transform a string into an array using Angular 2 and TypeScript

JSON.stringify(this.p)
console.log(this.p + " " + typeof(this.p))

When I execute these commands, the output is:

[{lat:52.52193980072258,lng:13.401432037353516},{lat:52.52319316685915,lng:13.407096862792969},{lat:52.51969409696076,lng:13.407225608825684}] string

This indicates that this.p is a string. However, when attempting to draw a polygon on my google map using this string, it results in an exception due to the expected data type being an Array.

How can I convert this string into an array (such as google.maps.LatLngLiteral or another compatible format)?

Please note: If I try to parse the string using JSON.parse(this.p):

JSON.parse(this.p)
console.log(this.p + " " + typeof( this.p))

I encounter the following error:

SyntaxError: Unexpected token l in JSON at position 2

What could be causing this issue and how can I resolve it?

The code snippet for utilizing this in my polygon is as follows:

 var polygon = new google.maps.Polygon({
          paths: this.p,
          strokeColor: '#FF0000',
          strokeOpacity: 0.8,
          strokeWeight: 3,
          fillColor: '#FF0000',
          fillOpacity: 0.35,
          map: this.map
        });

Answer №1

Here is the entire procedure in its entirety:

let newArray=[]

    this.otherService.fetchData()
    .subscribe(

      result => {       

        this.objects = result;
        console.log(this.objects)

        for(let x = 0; x < this.objects.length; x++){

          newArray.push(JSON.parse(this.objects[x].path)) 

        }

        var polygon = new google.maps.Polygon({
          paths: newArray,
          strokeColor: '#FF0000',
          strokeOpacity: 0.8,
          strokeWeight: 3,
          fillColor: '#FF0000',
          fillOpacity: 0.35,
          map: this.map
        });
      },

      fail =>  {
        console.log("An error occurred")
        this.errorMessage = <any>fail; 

      }

      )

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

Leverage the power of the MEAN stack with Angular 2 to seamlessly retrieve data from multiple APIs

Using angular2, nodejs, expressjs, and mongodb for development. I need all APIs to fetch data and display it on an HTML page. Below is the code snippet from my .ts file. view image description here All APIs have been tested and are s ...

Is it possible to create a sync function that includes a subscription to an observable?

Consider the following code snippet: observableMethod(): Observably { ... Return of([1, 2, 3]); } notObservableMethod(): integer { Let myVal; if (isOM) { this.observableMethod().pipe( first() ).subscribe( val => myVal = val; }); } else { myVal = thi ...

React Native error - Numeric literals cannot be followed by identifiers directly

I encountered an issue while utilizing a data file for mapping over in a React Native component. The error message displayed is as follows: The error states: "No identifiers allowed directly after numeric literal." File processed with loaders: "../. ...

Is it possible to build a Node.js (Express) application using a combination of JavaScript and TypeScript?

Currently, I have a Node.js project (Express REST API) that is written in JavaScript. My team and I have made the decision to gradually rewrite the entire project into TypeScript. Is it possible to do this incrementally, part by part, while still being ab ...

Is it possible to utilize ion-input's form validation while utilizing an HTML pattern for input?

I am working on validating an ion-input using a regex pattern in the HTML code. The purpose of this is to only allow numbers from 0 to 24 as input. Currently, this validation is functioning correctly and displays an error message if an incorrect number or ...

Slideshow through each item using Typescript and Angular8

I came across a solution in this carousel on by one link, but I'm struggling to work with the jQuery code even though I have JQuery installed in my project. For example: const next = jQuery(this).next(); I am looking to convert the JQuery code from ...

After populating the grid with data, there are no scroll bars present

I'm facing some challenges while integrating ag-grid into my Angular application. Although I can successfully load data onto the grid, I encounter a problem where there are no scroll bars present after loading my dataset. Furthermore, attempting keyb ...

Top method for retrieving the most recent artifact version from Azure Artifacts within Azure Pipelines

I am in the process of uploading a Universal package to Azure Artifacts through an Azure Pipeline. My goal is to embed the patched version number in the source of the artifact for display purposes. What is the best way to achieve this? The project in que ...

Exploring the process of updating the background color of a specific component in Angular

I'm currently working on a website that will feature alternating colors of white and black. However, I am facing an issue where I can only apply background color changes globally in the CSS file. Does anyone know how to address this problem? ...

Using Angular 8, remember to not only create a model but also to properly set it

hello Here is a sample of the model I am working with: export interface SiteSetting { postSetting: PostSetting; } export interface PostSetting { showDataRecordAfterSomeDay: number; } I am trying to populate this model in a component and set it ...

Is it time to launch your React TypeScript application on AWS S3?

I need help transitioning my deployment from AWS S3 using JavaScript to TypeScript. What specific code should I incorporate in TypeScript to facilitate this transition? 1) I have downloaded files with a .ts extension. https://i.sstatic.net/He49G.jpg 2) H ...

Experience the power of transforming nested forkjoin operations into observables

Trying to implement a solution in my resolver that involves nested forkjoins and subscribes has been challenging. I attempted using maps, but I still need to fully grasp the concepts of maps/switchMaps/mergeMaps. Even though the code doesn't currently ...

Guide to retrieving an array of arrays in Angular 2

How do I retrieve an array of array data in Angular 2? The JSON data I have is as shown below, [[{ "pk_emp_id":5, "tenant_id":"Zone1", "location_id":1, "emp_number":"sk44", "prefix":"", "first_name":"qqqqq", "middle_name":"www", "last_nam ...

Angular directive utilizing model reference for improved functionality

In my Angular 15 project, I am facing an issue with obtaining a reference to the ngModel in a custom directive. The goal is to create a directive that trims the input value before validation and triggers a data changed event to update the model. While I ca ...

Troubleshooting why the Angular innerHTML function is failing to render the specified

I'm encountering this problem where I am receiving a string const str = '<p>Please ensure Process Model diagram represents Functions adequately (boxes that represent an activity or group of activities that produce an outcome):</p>< ...

Is it possible to multitask within a structural directive by performing two actions simultaneously?

I want to develop a custom structural directive with the following behavior: <p *myDirective="condition">This is some text</p> If condition is false, the <p> tag will not be displayed at all. If condition is true, the <p> tag wi ...

Switch the Follow/Following button depending on the user's current follow status with the individual

I am currently working on a functionality to toggle between the Follow and Following buttons based on whether the current user is following another individual. I have implemented an NgIF statement in my code, but I am facing challenges in properly checking ...

Issue with mssql.connect await causing timeout in Jest

Testing some functionality in a nextjs Typescript project that needs to interact with the database directly, not relying on mocked sql query results. But encountering issues with it actually writing to the database. A brief example of the problem: /* @/li ...

What steps can I take to resolve the issue of the Error value not being iterable?

I encountered an issue in my table where I get the error message value is not iterable when there is no value to iterate through. How can I handle this error in my code? Snippet of Code: if (null != data && data) { data = data.map((item) => ...

Is it possible to create a single model with different variations, each with specific required fields?

If you're working with our API, you'll likely need to create an Order. While the order model remains consistent across different endpoints, the required fields may vary: For a POST request, only a few fields are required. With a PATCH request, ...