0

How to format this array:

array = ["37.772, -122.214", "-27.467, 153.027"]

into Lat/Lng for google map API that look like this:

flightPlanCoordinates = [
{lat: 37.772, lng: -122.214},
{lat: -27.467, lng: 153.027}];

I'm trying this code:

let latLngArray = [];
for (let i = 0; i < array.length; i++) {
  const gData = new google.maps.LatLng(array[i][0], array[i][1]);
  latLngArray.push(gData);
}

but it resulting lat lng without value:

Screenshot

0

3 Answers 3

2

Using map, split and destructing

const flightPlanCoordinates = ["37.772, -122.214", "-27.467, 153.027"]
  .map(coor => { 
    const [lat,lng] = coor.split(","); 
    return {lat:+lat,lng:+lng} 
  })

console.log(flightPlanCoordinates)

// OR mapping to number after splitting

const flightPlanCoordinates1 = ["37.772, -122.214", "-27.467, 153.027"]
  .map(coor => { 
    const [lat,lng] = coor.split(",").map(Number); 
    return {lat,lng} 
  })

console.log(flightPlanCoordinates1)

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

1 Comment

Downvoters may comment as to what is the problem with above working solution
1

Use map and split methods.

const array = ["37.772, -122.214", "-27.467, 153.027"];

const updated = array.map(item => {
  const [lat, lng] = item.split(", ").map(x => Number(x));
  return { lat, lng };
});

console.log(updated);

3 Comments

Beat you to it ;)
item.split(",").map(Number); is more elegant, but don't steal it ;)
most of the answer can give the formatted value i want, but this just matched my case very well...
0

Another approach with slice could be:

const array = ["37.772, -122.214", "-27.467, 153.027"];

let flightPlanCoordinates = array.map(coor => ({lat: +coor.slice(0, coor.indexOf(',')),
                                        	lng: +coor.slice(coor.indexOf(',') +1)}));

console.log(flightPlanCoordinates)

5 Comments

Split is neater than slice, and you access the string twice
I agree! It's just for the sake of variant :)
Ok. I just wanted to point it out. I think the nicest version so far is my .map(coor => { const [lat,lng] = coor.split(",").map(Number); return {lat,lng} })
You do not need the , -1 by the way
Yes, that one is more elegant

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.