对于从文件中读取的最后一个值,无法读取未定义的长度属性

时间:2015-11-11 16:43:34

标签: javascript mapbox

我正在尝试阅读包含

等内容的文本文件
$A,12.23,21.23

$A,12.21,21.22

$A,12.21,21.24

等等。

如果文件有6行文本,则会读取6行,然后控制台显示

未捕获的TypeError:无法读取属性'长度'未定义的。

我是JS的新手,任何人都可以指出出了什么问题?

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Leaflet Label</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src='https://api.mapbox.com/mapbox.js/v2.2.3/mapbox.js'></script>
<link href='https://api.mapbox.com/mapbox.js/v2.2.3/mapbox.css' rel='stylesheet' />
<style>
  body { margin:0; padding:0; }
  #map { position:relative;height:500px ;top:50; bottom:0; width:100%; }
</style>

<script>
$(window).resize(function() {
   $('#map').height($(window).height() / 1.5);
});

$(window).trigger('resize');

</script>

<script> $(window).ready(function() { $('#map').height($(window).height() / 1.5); }); </script>


</head>
<body>
<script src='https://api.mapbox.com/mapbox.js/plugins/leaflet-label/v0.2.1/leaflet.label.js'></script>
<link href='https://api.mapbox.com/mapbox.js/plugins/leaflet-label/v0.2.1/leaflet.label.css' rel='stylesheet' />
<div id='map'></div>

<input type='file' accept='text/plain' onchange='openFile(event)'><br>
<img id='output'>
<script>

  L.mapbox.accessToken = 'pk.eyJ1IjoicGVnYXN1cyIsImEiOiJjaWd1bjlvdmIwN3Izd3dtMDluYW1lMGlrIn0.QTR6xEpvu5bsXGeYn5jgjg';
    var map = L.mapbox.map('map', 'mapbox.streets').setView([15.199358, 73.626172], 17);

  var openFile = function(event) {
    var input = event.target;

    var reader = new FileReader();
    reader.onload = function(){

      var text = reader.result;
      var line_points = [];

      var res = text.split("\r\n");

      for(i=0;i<res.length;i++)
      {

        if(res[i]!="")
        {
        var inside_array = res[i].split(",");
        console.log(" Lat : " + inside_array[1] + " Lon : " + inside_array[2]);
        var arr1 = [inside_array[1],inside_array[2]];
        line_points.push(arr1);
        }
        //L.marker([inside_array[1], inside_array[2]]).bindLabel('P1').addTo(map);
      }
      var polyline_options = {  color: '#000' };

        L.polyline(line_points, polyline_options).addTo(map);
        console.log(line_points.length);

    };
    reader.readAsText(input.files[0]);
  };
</script>
</body>
</html>

编辑: 生成错误

要重现数据使用该代码(制作.html文件)并运行它,它会要求您上传文件,填写如下内容并上传文件,错误将显示在控制台中。

$ P,17.2335,21.12547

$ P,17.23351,21.125471

$ P,17.23352,21.125472

$ P,17.23353,21.125473

$ P,17.23354,21.125474

SO_

1 个答案:

答案 0 :(得分:0)

var arr1 = [inside_array[1],inside_array[2]];

应改为

var arr1 = new L.LatLng(inside_array[1], inside_array[2]);
line_points.push(arr1);

它需要一个LatLng数组而不是2个字符串。

Reference