10

I want to convert a String with a pattern like "(53.324523, 43.252352)" into a latlng. I already found the right function:

var input = latlngArray[i];
var latlngStr = input.split(",",2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
latlngArray[i] = new google.maps.LatLng(lat, lng);

The problem is that I can't get a proper lat. When I use alert to display it it only says NaN, while the lng variable displays the right value.

Got it. Thx for the help.

var input = latlngArray[i].substring(1, latlngArray[i].length-1);
var latlngStr = input.split(",",2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
latlngArray[i] = new google.maps.LatLng(lat, lng);
OhSnap
  • 376
  • 2
  • 10
  • 30
  • I already thought that it might be something like that. I guess I need to look for a function that deletes those. – OhSnap Jul 21 '11 at 15:05

2 Answers2

2

Quick fix after var input. Looks like the '(' is messing up the lat conversion:

input = input.replace('(','');
TreyA
  • 3,339
  • 2
  • 20
  • 26
  • 1
    Note that your solution assumes that the '(' is always at position 0. White space at the beginning will break your code. Also, you don't really need to remove the trailing ')' because the first char in the parse string is a number, thus all remaining chars in the strings are ignored. – TreyA Jul 22 '11 at 13:29
0

A general solution can be:

var locationToStringed = "(53.324523, 43.252352)";
var input = locationToStringed.replace('(', '');
var latlngStr = input.split(",", 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var parsedPosition = new google.maps.LatLng(lat, lng);
Soldeplata Saketos
  • 3,212
  • 1
  • 25
  • 38