使用FileReader加载CSV以制作地图标记的JS对象(Maps API)

时间:2015-03-07 23:02:14

标签: javascript google-maps csv google-maps-api-3 filereader

基本上我尝试加载csv文件,将其解析为js对象数组,并使用这些对象使用Google Maps API制作地图标记。

加载工作,解析工作,所有值都是正确的(据我所知),我已经控制台记录到死亡,我得到了我想要的值但是...我的地图不是' t loading。

我认为可能是因为时间安排?就像地图没有正确初始化或正确加载一样。

我偶尔会从Maps API获得有关连接超时和安全错误的错误,但刷新页面并重新加载csv似乎可以清除它。错误来来往往。

这是JS:

window.onload = function() {
  var fileInput = document.getElementById('fileInput');
  var fileDisplayArea = document.getElementById('fileDisplayArea');

  fileInput.addEventListener('change', function(e) {
    var file = fileInput.files[0];
    var textType = /csv.*/;
    var companies;

    // Check if csv file. If so, then run program. If not, show error.
    if (file.type.match(textType)) {
      var reader = new FileReader();

      reader.onload = function(e) {
        var text = reader.result;

        // Log for debug. Success.
        // console.log(text);

        // Parse csv file and make objects to store in companies array.
        function csvParse(csv) {
          var lines = csv.split("\n");

          // Log for debug. Success.
          // console.log(lines);

          var result = [];
          var headers = lines[0].split(",");

          for (var i = 1; i < lines.length; i++) {
            var obj = {};
            var currentline = lines[i].split(",");

            for (var j = 0; j < headers.length; j++) {
              obj[headers[j]] = currentline[j];
            }

            result.push(obj);
          }

          return result;
        }

        // Store objects in companies.
        companies = csvParse(text);

        // Log for debug. Success.
        // console.log(companies);

        var siteCircle;
        var companyMarker;

        // Log for debug. Success.
        // console.log(companies[1].sites);

        function initialize() {
          // Create the map of north america.
          var mapOptions = {
            zoom: 5,
            center: new google.maps.LatLng(37.09024, -95.712891),
            mapTypeId: google.maps.MapTypeId.TERRAIN
          }

          var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

          // Construct a circle and marker for each value in companies.
          for (var company in companies) {
            var latitude = (parseFloat(companies[company].lat)).toFixed(6);
            var longitude = (parseFloat(companies[company].long)).toFixed(6);

            // Log for debug. Success.
            // console.log(latitude);
            // console.log(longitude);
            // console.log(parseInt(companies[company].sites));

            var circleStyle = {
              // Set constant options.
              strokeColor: '#000000',
              fillColor: '#000000',
              strokeOpacity: 0.8,
              strokeWeight: 2,
              fillOpacity: 0.35,
              map: map,
              center: new google.maps.LatLng(latitude, longitude),
              radius: parseInt(companies[company].sites) * 100
            };

            // Not yet. circles first.
            /*
            var markerOptions = {
              // Place marker at same loacation and with a label.
              position: new google.maps.LatLng(parseFloat(companies[company].lat), parseFloat(companies[company].long)),
              map: map,
              title: companies[company].name,
            };
            */

            // Log for debug. Success.
            // console.log(circleStyle)

            // Add circle and marker to map. Repeat.
            siteCircle = new google.maps.Circle(circleStyle);

            // Circles need to populate first.
            // companyMarker = new google.maps.Marker(markerOptions);
          }
        }

        // Run mapping.
        initialize();
      }

      reader.readAsText(file);
    } else {
      fileDisplayArea.innerText = "File not supported!";
    }
  });
}

这里还有一个包含所有文件的要点:https://gist.github.com/mhelmetag/20eeae8cd4c901fb1094

提前非常感谢!

1 个答案:

答案 0 :(得分:2)

您发布的代码不包含所有问题。

  1. 我评论了if (file.type.match(textType)) {测试,这给了我一个错误:“文件不受支持!” fiddle

  2. csvParse函数无法正确解析文件的最后一个条目,您获得经度的NaN(因此google.maps.LatLngs无效)

  3. 在parseFloat调用后删除.toFixed(6),更改:

  4. var latitude = (parseFloat(companies[company].lat)).toFixed(6); 
    var longitude = (parseFloat(companies[company].long)).toFixed(6);
    

    要:

    var latitude = parseFloat(companies[company].lat);
    var longitude = parseFloat(companies[company].long);
    
    1. 你的地图没有大小,所以一旦“经度”问题得到修复,你就看不到了。

    2. 作为旁白你的css有问题,下面的行导致了地图控件的工件,我删除了它:

      img {   最大宽度:100%; }

    3. working jsfiddle

      使用的数据文件:

      name,type,sites,lat,long,dummy
      Yum Brands,QSR,36000,38.198117,-85.695723,nothing
      McDonalds,QSR,11772,41.848117,-87.944818,nothing
      Dollar General,Discount,8414,36.309512,-86.699107,nothing
      WalMart,Big Box,7873,36.365399,-94.217752,nothing
      Walgreens,Drug Store,7500,42.156776,-87.871079,nothing
      Starbucks,QSR,6793,47.581000,-122.335855,nothing
      Dunkin Brands,QSR,6500,42.207285,-71.129786,nothing
      CVS,Drug Store,6301,41.990542,-71.477562,nothing
      Gamestop,Specialty,6207,32.902302,-97.087347,nothing
      7-Eleven,C-Store,6100,32.791810,-96.795768,nothing
      Family Dollar,Discount,6000,35.131827,-80.731703,nothing
      Couche Tarde,C-Store,5600,33.335586,-111.955955,nothing
      

      工作代码段:

      window.onload = function() {
        var fileInput = document.getElementById('fileInput');
        var fileDisplayArea = document.getElementById('fileDisplayArea');
      
        fileInput.addEventListener('change', function(e) {
          var file = fileInput.files[0];
          var textType = /csv.*/;
          var companies;
      
          // Check if csv file. If so, then run program. If not, show error.
          //     if (file.type.match(textType)) {
          var reader = new FileReader();
      
          reader.onload = function(e) {
            var text = reader.result;
      
            // Log for debug. Success.
            // console.log(text);
      
            // Parse csv file and make objects to store in companies array.
            function csvParse(csv) {
              var lines = csv.split("\n");
      
              // Log for debug. Success.
              // console.log(lines);
      
              var result = [];
              var headers = lines[0].split(",");
      
              for (var i = 1; i < lines.length; i++) {
                var obj = {};
                var currentline = lines[i].split(",");
      
                for (var j = 0; j < headers.length; j++) {
                  obj[headers[j]] = currentline[j];
                }
      
                result.push(obj);
              }
      
              return result;
            }
      
            // Store objects in companies.
            companies = csvParse(text);
      
            // Log for debug. Success.
            // console.log(companies);
      
            var siteCircle;
            var companyMarker;
      
            // Log for debug. Success.
            // console.log(companies[1].sites);
      
            function initialize() {
              // Create the map of north america.
              var mapOptions = {
                zoom: 5,
                center: new google.maps.LatLng(37.09024, -95.712891),
                mapTypeId: google.maps.MapTypeId.TERRAIN
              }
      
              var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
      
              // Construct a circle and marker for each value in companies.
              for (var company in companies) {
                var latitude = parseFloat(companies[company].lat);
                var longitude = parseFloat(companies[company].long);
      
                // Log for debug. Success.
                // console.log(latitude);
                // console.log(longitude);
                // console.log(parseInt(companies[company].sites));
      
                var circleStyle = {
                  // Set constant options.
                  strokeColor: '#000000',
                  fillColor: '#000000',
                  strokeOpacity: 0.8,
                  strokeWeight: 2,
                  fillOpacity: 0.35,
                  map: map,
                  center: new google.maps.LatLng(latitude, longitude),
                  radius: parseInt(companies[company].sites) * 100
                };
      
                // Not yet. circles first.
                /*
                var markerOptions = {
                  // Place marker at same loacation and with a label.
                  position: new google.maps.LatLng(parseFloat(companies[company].lat), parseFloat(companies[company].long)),
                  map: map,
                  title: companies[company].name,
                };
                */
      
                // Log for debug. Success.
                // console.log(circleStyle)
      
                // Add circle and marker to map. Repeat.
                siteCircle = new google.maps.Circle(circleStyle);
      
                // Circles need to populate first.
                // companyMarker = new google.maps.Marker(markerOptions);
              }
            }
      
            // Run mapping.
            initialize();
          }
      
          reader.readAsText(file);
          /*    } else {
                fileDisplayArea.innerText = "File not supported!";
              }
          */
        });
      }
      
      /* test.csv
      name,type,sites,lat,long
      Yum Brands,QSR,36000,38.198117,-85.695723
      McDonalds,QSR,11772,41.848117,-87.944818
      Dollar General,Discount,8414,36.309512,-86.699107
      WalMart,Big Box,7873,36.365399,-94.217752
      Walgreens,Drug Store,7500,42.156776,-87.871079
      Starbucks,QSR,6793,47.581000,-122.335855
      Dunkin Brands,QSR,6500,42.207285,-71.129786
      CVS,Drug Store,6301,41.990542,-71.477562
      Gamestop,Specialty,6207,32.902302,-97.087347
      7-Eleven,C-Store,6100,32.791810,-96.795768
      Family Dollar,Discount,6000,35.131827,-80.731703
      Couche Tarde,C-Store,5600,33.335586,-111.955955
      */
      html {
        font-family: Helvetica, Arial, sans-serif;
        font-size: 100%;
        background: #333;
      }
      html,
      bofy {
        height: 100%;
        width: 100%;
      }
      #page-wrapper {
        width: 600px;
        background: #FFF;
        padding: 1em;
        margin: 1em auto;
        min-height: 300px;
        border-top: 5px solid #69c773;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.8);
      }
      h1 {
        margin-top: 0;
      }
      #fileDisplayArea {
        margin-top: 2em;
        width: 100%;
        overflow-x: auto;
      }
      #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
      <script src="https://maps.googleapis.com/maps/api/js"></script>
      <div id="page-wrapper">
      
        <h1>CSV File to JS Object Test</h1>
        <div>
          Select a CSV file:
          <input type="file" id="fileInput" />
        </div>
        <pre id="fileDisplayArea"><pre>
       
        </div>
        <div id="map-canvas" style="height: 500px; width: 500px;"></div>