LatLng 对象的拆分字符串



我遇到了一个非常烦人的问题。这就是我想要实现的目标。我在两个文本框中读取纬度和经度,然后在逗号上拆分每个对,因为这是它们之间的分隔。然后我需要解析它们并创建一个 LatLng 对象来创建 Google 标记。由于某种原因,我的问题是拆分字符串。我知道我需要做的就是使用 String.split() 方法来实现它。这是我的工作:

 Lets say the value in text box is 26.2338, 81.2336
 //Reading the value in text boxes on HTML form
    var sourceLocation =document.getElementById("source").value;
//Remove any spaces in between coordinates
    var newString =sourceLocation.replace(/s/g, '');
//Split the string on ,
    newString.split(",");
//Creating latitude longitude objects of the source and destination
var newLoc =new google.maps.LatLng(parseFloat(newString[0]),parseFloat(newString[1]));

现在我无法理解为什么 newString[0] 只给我 2,而它应该给出 26.2338。类似地,newString[1] 给出 6 而不是 81.2336。我做错了什么??任何帮助将不胜感激。

String.split() 返回一个数组,它不会修改字符串以以某种方式使其成为数组。你想要

var parts = newString.split(",");
var newLoc = new google.maps.LatLng(parseFloat(parts[0]),parseFloat(parts[1]));

最新更新