我在javascript中有一系列纬度和经度,如下所示:
a = [lat1, lon1, lat2, lon2, lat3, lon3, ...] // assert(a.length % 2 = 0)
我想创建一个这样的字符串:
s = "lat1,lon1 lat2,lon2 lat3,lon3 ..."
也就是说,每个latlon对都有一个逗号分隔该对,并且这些对由空格分隔。
我有点卡在这里(主要是因为我对javascript知之甚少):
function polylineToKml(p)
{
var s = "";
for (var i = 0; i < p.length; i+=2)
{
var lat = p[i];
var lon = p[i+1]
// now what?
}
}
答案 0 :(得分:2)
以更具功能性的方式:
function polylineToKml(p) {
return p.map(function(el, i) {
return el + (i % 2 > 0 ? " " : ",");
}).join("").trim();
}
如果您的环境支持ES6:
var polylineToKml = p =>
p.map((el, i) => el + (i % 2 > 0 ? " " : ",")).join("").trim();
答案 1 :(得分:1)
function polylineToKml(p) {
var s = "";
for (var i = 0, l = p.length; i < l; i += 2) {
var lat = p[i];
var lon = p[i + 1];
s += lat + ',' + lon;
// don't add a space at the end
if (i !== l - 2) s += ' ';
}
return s;
}
答案 2 :(得分:1)
一种方式:
var s = [];
for (var i = 0; i < a.length; i+=2)
{
s.push(a[i] + "," + a[i+1]);
}
s = s.join(" ");
答案 3 :(得分:0)
还有一种方式......
function polylineToKml(p){
var s = "";
for (var i = 0; i < p.length - 1; i++){
s += p[i] + ",";
}
s += p[p.length - 1];
return s;
}
答案 4 :(得分:0)
您应采用适当的方式来组织数据集,一种方法是使用带有键值对的JSON数组,例如
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var a = [1.234, 2.345, 3.456, 5.456, 4.653, 2.567]
var coordinates = [];
for (var i=0; i < a.length; i=i+2){
coordinates[i/2] = {"latitude":a[i], "longitude":a[i+1]}
}
for (var i=0; i < coordinates.length; i++){
document.getElementById("demo").innerHTML +=
coordinates[i].latitude + ", " + coordinates[i].longitude + "<br>";
}
</script>
</body>
</html>
这样,坐标将表示为:
coordinates = [
{"latitude":"1.234", "longitude":"2.345"},
{"latitude":"3.456", "longitude":"5.456"},
{"latitude":"4.653", "longitude":"2.567"}
];
的更多信息