简体   繁体   English

从可变长度字符串中提取经纬度

[英]Extract lat, lng from a variable length string

I want extract lat. 我要提取lat。 and longitude vals from a string like this: 和来自以下字符串的经度值:

var data = "(-20.210696507479017, -70.14000177383423),(-20.21202551027535, -70.14246940612793),(-20.21385790460967, -70.14066696166992),(-20.21168319245841, -70.13901472091675)" 

How can I extract these pairs and push them into a array if these points can change in quantity? 如果这些点的数量可以改变,我如何提取这些对并将它们推入数组?

Thanks 谢谢

Split the pairs, then split each pair and parse the values. 拆分对,然后拆分每个对并解析值。 This produces an array of objects that have a lat and lng property that are numbers: 这将生成具有latlng属性的数字对象数组:

var coors = data.split('),(');
for (var i = 0; i < coors.length; i++) {
  var c = coors[i].replace('(', '').replace(')', '').split(',');
  coors[i] = { lat: parseFloat(c[0]), lng: parseFloat(c[1]) };
}

Demo: http://jsfiddle.net/Guffa/EV2h4/ 演示: http//jsfiddle.net/Guffa/EV2h4/

Why not transform it into a json string array, then parse it to an object. 为什么不将其转换为json字符串数组,然后将其解析为一个对象。

var data = "(-20.210696507479017, -70.14000177383423),(-20.21202551027535, -70.14246940612793),(-20.21385790460967, -70.14066696166992),(-20.21168319245841, -70.13901472091675)";
var arr = JSON.parse("[" + data.replace(/[)(]/g, "") + "]");
for(var x=0; x<arr.length-1; x+=2)
    console.log("lat " + arr[x] + ", lon " + arr[x+1]);

edit x+=2, good catch Iftah 编辑 x + = 2,很好抓住Iftah

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM