0

I have an output array from my controller like this :

[
  ["48.85585695936588,2.317734961729684"],
  ["48.87234429654349,2.351466422300973"],
  ["48.85376742273335,2.3639977028185513"]
]

I want to create a polygon from this coordinates, so this data structure (array) :

array pos

This is my code :

for(var j = 0; j < output.length; j++) {
    var points = [];
    var quart = JSON.parse(output[j]['polygon']);
    for (var i = 0; i < quart.length; i = i+2) {
        points.push({
           lat: parseFloat(quart[i]),
           lng: parseFloat(quart[i+1])
       });
 }

I can't get the value of the longitude (the one after the comma)...

Thank you.

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
  • 2
    Few pieces of advice when you ask question on StackOverflow: ask the question :) and put your code in a block so others can easily copy that, otherwise people need to print it manually from your picture. – andnik Dec 09 '18 at 16:46
  • 5
    Can you post your Array as text, and not a picture? That way it’s easier us to help. – David Thomas Dec 09 '18 at 16:47
  • Yes of course sorry I just did;) –  Dec 09 '18 at 16:48
  • 2
    Use string.split(","); – Darkrum Dec 09 '18 at 16:48
  • So your first pic is the output of `console.log(quart)`? – Bergi Dec 09 '18 at 16:48
  • Yes first pic is "console.log(quart)" but it's also stored in this form in the database –  Dec 09 '18 at 16:50
  • Possible duplicate of [How to split a comma separated string and process in a loop using JavaScript](https://stackoverflow.com/questions/3245088/how-to-split-a-comma-separated-string-and-process-in-a-loop-using-javascript) – Darkrum Dec 09 '18 at 16:51
  • In provided `output` variable there is no `polygon` field, as you do `JSON.parse(output[j]['polygon'])` – andnik Dec 09 '18 at 16:54

5 Answers5

1

One approach is the following:

// original array:
let twoDimensionalArray = [
    ["48.85585695936588,2.317734961729684"],
    ["48.87234429654349,2.351466422300973"],
    ["48.85376742273335,2.3639977028185513"]
  ],
// using Array.prototype.map() to iterate over the
// Array, returning a new Array (assigned to the
// variable):
  coordsArray = twoDimensionalArray.map(

    // using an Arrow function to pass the current
    // Array into the function:
    (coords) => {

      // here we use destructuring to assign
      // values to a and b; to do this we take the last
      // (and only) entry of of the coords Array, and
      // split on the comma character. The first element
      // of the Array created by String.prototype.split(),
      // we then use Array.prototype.map() - along with
      // another Arrow function to iterate over the returned
      // Array to convert the Strings to numbers, with
      // parseFloat():
      [a, b] = coords.pop().split(',').map((xy)=>parseFloat(xy))

      // here we return an Object with named 'lat' and 'lng'
      // properties, assigning the relevant values to each:
      return {
        'lat': a,
        'lng': b
      }
    });

console.log(coordsArray);

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
0

Just loop through the array, get the first element of each inner array and split the string:

var quart = [
  ["48.85585695936588,2.317734961729684"],
  ["48.87234429654349,2.351466422300973"],
  ["48.85376742273335,2.3639977028185513"]
];

var points = [];
quart.forEach(function(item) {
  var coords = item[0].split(',');
  points.push({
    lat: parseFloat(coords[0]), // added float parsing in Edit
    lng: parseFloat(coords[1])
  });
})
console.log(points);
Steve T
  • 570
  • 4
  • 13
0

I don't see polygon field in your provided output variable, so I don't understand this line JSON.parse(output[j]['polygon']). But for the provided input variable you can use the following code:

points = output.map(function(row) {
    coordinates = row[0].split(',');
    return {lat: parseFloat(coordinates[0]), lng: parseFloat(coordinates[1])};
});

Maybe you want to add some checks for the input variables.

andnik
  • 2,405
  • 2
  • 22
  • 33
0

so basically your data consist of array which means , data is having 3 arrays. so first you need to go to the data (which has the three sub arrays). data.map

you can use array.map which will return a new array, since we need the points array as array of objects having property of lat and lng, we can use array.map.

so after looping through item we get each array, we need to split it with comma and assign to variable since once we split it, we will have lat value in item[0] and lng in item1.

Note we need to do item[0], since the three arrays are in the the first index of each item

so then we can create the object and return the object.

I hope the below solution will solve the issue.

let data = [
  ["48.85585695936588,2.317734961729684"],
  ["48.87234429654349,2.351466422300973"],
  ["48.85376742273335,2.3639977028185513"]
];

let points =  data.map(item => {
  var eachCoordinates = item[0].split(',');
  return{
    lat: eachCoordinates[0],
    lng: eachCoordinates[1]
  }
})

console.log(points);


// one line code, but two times we are calling the split functionality

let pointsOneLineCode =  data.map(item => ({
    lat: item[0].split(",")[0],
    lng: item[0].split(",")[1]
  })
)

console.log("one line code",pointsOneLineCode)
Learner
  • 8,379
  • 7
  • 44
  • 82
0

You can also achieve this in a very concise way with Array.map and Array.reduce:

const data = [ ["48.85585695936588,2.317734961729684"], ["48.87234429654349,2.351466422300973"], ["48.85376742273335,2.3639977028185513"] ]

const result = data.map(x => x[0].split(',').reduce((lat, lng) => 
  ({ lat: parseFloat(lat), lng: parseFloat(lng) })))

console.log(result)

The idea is to mao through the array and for each item split and then reduce the parts to a single object via the Array.reduce.

Akrion
  • 18,117
  • 1
  • 34
  • 54