【问题标题】:Put coordinates from .txt file to Javascript array将 .txt 文件中的坐标放入 Javascript 数组
【发布时间】:2017-04-23 22:21:09
【问题描述】:

我得到了这样坐标的txt文件:

21.178797 56.888384
21.373250 56.588044
24.136921 56.965521
26.231814 56.858971
24.123382 56.951146
25.399601 57.540989
24.542900 57.090442

我需要把它们放在这种类型的数组中:

var locations = [
 ['Title A', 3.180967,101.715546, 1],
 ['Title B', 3.200848,101.616669, 2],
 ['Title C', 3.147372,101.597443, 3],
 ['Title D', 3.19125,101.710052, 4]
 ];

所以我可以像这样使用循环放置多个标记:

for (i = 0; i < locations.length; i++) {  
markers = new google.maps.Marker({
     position: new google.maps.LatLng(locations[i][1], locations[i][2]),
     map: map
     });

     google.maps.event.addListener(marker, 'click', (function(markers, i) {
     return function() {
         infowindow.setContent(locations[i][0]);
         infowindow.open(map, marker);
     }
})(marker, i));

  }

}

有什么想法可以让它发挥作用吗?

谢谢!:)

感谢您的快速回复。

我会为自己简化一点(这是我第一次使用 JS)

我有相同的文件:

21.178797 56.888384
21.373250 56.588044
24.136921 56.965521
26.231814 56.858971
24.123382 56.951146
25.399601 57.540989
24.542900 57.090442

我需要数组看起来像这样:

var locations = [
[3.180967,101.715546],
[3.200848,101.616669],
[3.147372,101.597443],
[3.19125,101.710052]
];

提前致谢)

【问题讨论】:

  • 文件在服务器上吗?还是“用户”将从他们的机器上加载的本地文件?
  • 现在它与 .js 文件(在机器上)在同一个文件夹中,我使用 Python 从 Api 获取坐标并将它们放入 txt 文件中。

标签: javascript arrays google-maps coordinates google-maps-markers


【解决方案1】:

解析数据

使用String#split将文本拆分为行数组,然后将每一行拆分为数组:

var str = `21.178797 56.888384
21.373250 56.588044
24.136921 56.965521
26.231814 56.858971
24.123382 56.951146
25.399601 57.540989
24.542900 57.090442`;

var result = str.split('\n').map(function(line, index) {
  return ['Title ' + String.fromCharCode(index + 65)].concat(line.split(' '));  
});

console.log(result);

获取数据

根据您计划支持的浏览器,您可以XMLHttpRequest 或更新的fetch。如果可以,这个简单的方法将使用fetch,并回退到XMLHttpRequest:

function getData(path, cb) {
    var oReq;

    if (window.fetch) {
        window.fetch(path)
            .then(function(response) {
                return response.text();
            })
            .then(cb);
    } else {
        oReq = new XMLHttpRequest();
        oReq.addEventListener("load", function() {
            cb(this.responseText);
        });
        oReq.open("GET", path);
        oReq.send();
    }
}

function parseData(data) {
    var coo = str.split('\n').map(function(line, index) {
        return ['Title ' + String.fromCharCode(index + 65)].concat(line.split(' '));  
    });

    // your code that uses coo
}

getData('coo.txt', parseData);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    相关资源
    最近更新 更多