如何在javascript中从此字符串获取lat long?

时间:2016-08-28 16:38:52

标签: javascript

我希望此字符串中的lat long在地图上设置多个pal标记。 var str ="(09:07:24,12.8937357,77.6321656),(09:08:51,12.8936567,77.6335833),(09:09:32,12.89458,77.6344317),(09:10:02, 12.8950417,77.6353917),(09:11:02,12.8961483,77.6354217),(09:11:22,12.8974533,77.63467),(09:11:52,12.8991467,77.6338017),(09:12:02,12.9003433, 77.6331133),(09:12:12,12.9015583,77.6323683),(09:12:22,12.902765,77.6316267),(09:12:32,12.90401,77.6308283),(09:12:42,12.9049567,77.63017) ,(09:14:02,12.9057717,77.6297133),(09:16:52,12.9065883,77.629245),(09:17:41,12.9065317,77.6303717),(09:18:02,12.9066083,77.6314783),( 09:18:32,12.906975,77.6325317),(09:18:52,12.9086617,77.6325217),(09:19:02,12.909605,77.6325117),(09:19:22,12.9105083,77.63271)" ;

1 个答案:

答案 0 :(得分:2)

假设字符串中的集合的格式为(时间,纬度和经度),您可以将它们拆分并转换为可以轻松操作的数组结构:

var latLongArray = str.slice(1, -1).split('),(').map(function(setString) {
  var setArray = setString.split(',');
  return {
    "time": setArray[0],
    "latitude": setArray[1],
    "longitude": setArray[2]
  };
});

这为您提供了一系列包含时间,纬度和经度的结构。

演示:



var str = "(09:07:24,12.8937357,77.6321656),(09:08:51,12.8936567,77.6335833),(09:09:32,12.89458,77.6344317),(09:10:02,12.8950417,77.6353917),(09:11:02,12.8961483,77.6354217),(09:11:22,12.8974533,77.63467),(09:11:52,12.8991467,77.6338017),(09:12:02,12.9003433,77.6331133),(09:12:12,12.9015583,77.6323683),(09:12:22,12.902765,77.6316267),(09:12:32,12.90401,77.6308283),(09:12:42,12.9049567,77.63017),(09:14:02,12.9057717,77.6297133),(09:16:52,12.9065883,77.629245),(09:17:41,12.9065317,77.6303717),(09:18:02,12.9066083,77.6314783),(09:18:32,12.906975,77.6325317),(09:18:52,12.9086617,77.6325217),(09:19:02,12.909605,77.6325117),(09:19:22,12.9105083,77.63271)";

//remove open and close parentheses from the start and end of the string
//then split the string into an array based on ),(.
//lastly, split each string in the temporary array by commas to get your 
//time/latitude/longitude
var latLongArray = str.slice(1, -1).split('),(').map(function(setString) {
  var setArray = setString.split(',');
  return {
    "time": setArray[0],
    "latitude": setArray[1],
    "longitude": setArray[2]
  };
});

//loop to illustrate data access
latLongArray.forEach(function(latLong) {
  console.log("Time: ", latLong.time, " Latitude: ", latLong.latitude, " Longitude: ", latLong.longitude);
});