1

I'm fetching some data from an API and the response includes the user location in longitude and latitude.

This is to render an icon on a map according to the user's coordinates

That's the JSON object:

{
  ...
  "lonlat": "POINT (-42.796763 -5.077056)",
}

I want to be able to parse this POINT object and get the value of latitude and longitude.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Bruno
  • 348
  • 5
  • 21
  • You should show what you have tried so far and explain why it didn't work. – Tibrogargan Jun 01 '19 at 03:46
  • Sorry, I'm just looking for help because I don't have any idea how to handle this kind of structure. – Bruno Jun 01 '19 at 03:48
  • 1
    Does the API you're consuming not have a library to help you consume this `POINT(n n)` format? It's frankly kind of a whack way to send _generic_ coordinates, and looks like something preformatted for another consumer. – msanford Jun 01 '19 at 03:57

3 Answers3

4

You can replace all values other then space, digits and - and decimal and then trim leading and trailing whitespace and then split on space

[^\d .-]
  • [^\d .-] - Match anything except digit, space, . and -

const data = {
  "lonlat": "POINT (-42.796763 -5.077056)"
};

let [lat,lng] = data.lonlat.replace(/[^\d .-]/g,'').trim().split(/\s+/)
console.log(lat);
console.log(lng);
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • 2
    Side-note: I particularly enjoy the elegant destructuring assignment. – msanford Jun 01 '19 at 04:00
  • 1
    @msanford than you will enjoy reading [this](https://stackoverflow.com/questions/54605286/what-is-destructuring-assignment-and-its-uses) and [this too](https://stackoverflow.com/questions/55194118/how-do-i-parse-a-string-to-number-while-destructuring) – Code Maniac Jun 01 '19 at 04:01
2

You can use a regex to get the values, assuming they're always separated by a space.

const data = {
  "lonlat": "POINT (-42.796763 -5.077056)"
};

const regex = /[A-Z]+\s\((-?\d+\.\d+)\s(-?\d+\.\d+)\)/;
const [, longitude, latitude] = data.lonlat.match(regex);
console.log(longitude);
console.log(latitude);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

You can try getting the characters between parenthesis first like the following way:

var obj = {
  "lonlat": "POINT (-42.796763 -5.077056)",
}
var regExp = /\((.*?)\)/;
var lonlat = obj.lonlat.match(regExp)[1].split(' ');
console.log(lonlat);
Mamun
  • 66,969
  • 9
  • 47
  • 59