Home > Mobile >  Extract lat/lng coordinates from a string
Extract lat/lng coordinates from a string

Time:08-09

I've got a string which contains several coordinates. It is just random human readable text. For example:

Bla bla bla 35.45672,-162.91938 yadda yadda yadda -6.53197, 132.07407 bla bla

I would like to extract all the coordinates from the text to an array. The coordinates are seperated by a comma, or a comma and a space (As in the example above). There is no fixed length or seperators. There is no fixed amount of coordinates. It is just random text containing lat/lng coordinates.

What would be the best way to extract all coordinates from the text into an array?

CodePudding user response:

You could use match() here with an appropriate regex pattern:

var input = "Bla bla bla 35.45672,-162.91938 yadda yadda yadda -6.53197, 132.07407 bla bla";
var matches = input.match(/-?\d (?:\.\d )?,\s*-?\d (?:\.\d )?/g);
console.log(matches);

Once you have isolated the lat/lng pairs in the above string array, it is only a bit more work to obtain separate numbers in whatever format you need.

CodePudding user response:

You could write a regular expression to find the pattern you want and extract it.

In javascript a regular expression can be written as such:

const re = /ab c/;

... where the expression is written between the two forward slashes. The formatting of regular expression are documented extensively in many places.

I have used the MDN resource for documentation on this feature.

  • Related