I am using Leaflet and I am trying to create a polyline and marker points but it gives opposite lat and long so I have to swap them. Creating a marker is easy because it only has one pair of lat and long but creating a polyline is complicated because has a lot of points.
Below is what I am currently using to swap lat and long for marker points.
var splitObj = objVal.toString().split("],[");
var latlng = splitObj.map(function(x)
{
var couple= (/\d+.\d+, \d+.\d+/g).exec(x).toString();
var splitted = couple.split(", ");
return "["+splitted[1]+","+splitted[0]+"]";
});
latlng.join();
Result:
['[[a, b], [c, d], [e, f]]'] // this is the objVal
expectation:
['[[b,a], [d,c], [f,e]]']
reality:
['[b,a]']
map over the array it and, for each inner array, return a new array after swapping the elements around.
const data = [[124.432841, 8.3963], [124.496898, 8.3963], [124.571937, 8.40898]];
const result = data.map(arr => {
return [arr[1], arr[0]];
});
console.log(result);
Assuming the input is a string of nested-array-like values, the below solution may help in transforming/swapping latitude-longitude values.
Code Snippet
const inpVal = ['[[a, b], [c, d], [e, f]]'];
// helper method to strip first & last char of a string
const stripFirstLast = s => s.slice(1, s.length - 1);
// helper method to swap lat & longitutde values
const swapLatLon = ([lat, lon]) => [lon, lat];
// place holder to safe-keep value of input
const tmp = stripFirstLast(inpVal[0])
.replaceAll('], ', '] | ')
.split(' | ');
// calculate the result
const res = ["[" +
tmp.map(
x => '[' +
swapLatLon(
stripFirstLast(x).split(', ')
).join(', ') +
']'
).join(', ') +
"]"
];
// console-log to validate/verify
console.log(
'input: ', inpVal,
'\nresult: ', res
);
Explanation
Comments inline explain the approach used.
Swap with actual values (and not string)
This is an almost-exact replica of Andy's solution/answer with only one change instead of handling the inner array as
arr, the iterator directly accesses the lat & lon values. I think it makes the solution a little more easier to read.
// Previous solution where the orig data was not taken as a string
const swapLoLa = arr => arr.map(([lon, lat]) => [lat, lon]);
const orig = [[124.432841, 8.3963], [124.496898, 8.3963], [124.571937, 8.40898]];
console.log(
'orig arr: ', orig,
'\nswapped arr: ', swapLoLa(orig)
);