2

I have an object array like this

polyPaths: LatLngLiteral[] = [{lat: 12.994169219614097, lng: 77.62397007054658}
 {lat: 12.984802167360343, lng: 77.67581180638642}
 {lat: 12.957702635784846, lng: 77.65864566869111}
 {lat: 12.974765648082716, lng: 77.61538700169892}];

I want to show this object array as string in textarea

(12.994169219614097,77.62397007054658)
(12.984802167360343,77.67581180638642)
(12.957702635784846,77.65864566869111)
(12.974765648082716,77.61538700169892)

On text input change, I want string revert back to object array of polyPaths.

I tried with following js example:

let stringPath = this.polyPaths.map(path => {
    return '(' + path.lat + ',' + path.lng + ')';
});
var convertedPath = stringPath.join('');
this.polyControls.area.setValue(convertedPath);

But not able to revert it back on input change.

2 Answers 2

3

Try the following, it's basic string/array manipulation

const polyPaths = [{
  lat: 12.994169219614097,
  lng: 77.62397007054658
}, {
  lat: 12.984802167360343,
  lng: 77.67581180638642
}, {
  lat: 12.957702635784846,
  lng: 77.65864566869111
}, {
  lat: 12.974765648082716,
  lng: 77.61538700169892
}]


// converting it to a string
const convertedPath = polyPaths.map(path => `(${path.lat},${path.lng})`).join('\n');
console.log(convertedPath)


// reversing it back
const reversed = convertedPath.split('\n').map(x => {
  const [lat, lng] = x.slice(1, x.length - 1).split(",").map(Number)
  return {
    lat,
    lng
  }
})

console.log(reversed)

Sign up to request clarification or add additional context in comments.

Comments

1

Try like below. Explanation is in comments.

let polyPaths = [{
  lat: 12.994169219614097,
  lng: 77.62397007054658
}, {
  lat: 12.984802167360343,
  lng: 77.67581180638642
}, {
  lat: 12.957702635784846,
  lng: 77.65864566869111
}, {
  lat: 12.974765648082716,
  lng: 77.61538700169892
}];

let stringPath = polyPaths.map(path => {
  return '(' + path.lat + ',' + path.lng + ')';
});

var convertedPath = stringPath.join('');
console.log(convertedPath);

// split your string with (
polyPaths = convertedPath.split('(') 
  .filter(path => path.includes(')')) // remove first entry which will be empty string
  .map(path => ({
    lat: path.split(',')[0].trim(), // get lat from each record
    lng: path.split(',')[1].replace(')', '').trim(), // get lng from each record, remove )
  }));

console.log(polyPaths);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.