I am using javascript and I have GPS coordinates in the form of a string and I am trying to put those into the google.maps.LatLng(59.327383, 18.06747)
format but am having trouble deciding how to do it. I have a variable:
GPSlocation = "(37.700421688980136, -81.84535319999998)"
and I need it to go into that google.maps.LatLng(num, num) format. How can I put this string in there?
Thanks!
I am using javascript and I have GPS coordinates in the form of a string and I am trying to put those into the google.maps.LatLng(59.327383, 18.06747)
format but am having trouble deciding how to do it. I have a variable:
GPSlocation = "(37.700421688980136, -81.84535319999998)"
and I need it to go into that google.maps.LatLng(num, num) format. How can I put this string in there?
Thanks!
Share Improve this question asked Sep 9, 2012 at 6:25 clifgrayclifgray 4,41911 gold badges68 silver badges125 bronze badges 1- I always laugh at the number of decimal places we get on lat/lon co-ords. Six DP is enough to pinpoint you to ten centimetres. I'm always amused when we get people insisting on eight or ten-digit co-ords. Your have even more than that, but that's more down to floating point inaccuracies than any kind of precision. – Spudley Commented Sep 9, 2012 at 7:51
2 Answers
Reset to default 14You can use standard string operations to extract the values:
var GPSlocation = "(37.700421688980136, -81.84535319999998)";
var LatLng = GPSlocation.replace("(", "").replace(")", "").split(", ")
var Lat = parseFloat(LatLng[0]);
var Lng = parseFloat(LatLng[1]);
google.maps.LatLng(Lat, Lng)
You can create an Array from it (using JSON.parse
), and then use apply
to 'feed' the coordinates to the method:
GPSlocation = JSON.parse( "(37.700421688980136, -81.84535319999998)"
.replace(/^\(/,'[')
.replace(/\)$/,']')
);
google.maps.LatLng.apply(null,GPSlocation);
Alternatively you can replace the brackets and use split
to create an Array, and call the method LatLng
the regular way. This method requires an extra conversion to Number
of the Array values.
GPSlocation = "(37.700421688980136, -81.84535319999998)"
.replace(/^\(|\)$/,'')
.split(',');
google.maps.LatLng(+GPSlocation[0],+GPSlocation[1]);
To retrieve an Array of coordinates from the string, you could also use:
GPSlocation = ''.slice.call('(37.700421688980136, -81.84535319999998)',
1,this.length-1)
.split(',')
.map(function(a){return +a;});
google.maps.LatLng(GPSlocation[0],GPSlocation[1]);