使用 FileReader 加载 CSV 以制作用于地图标记的 JS 对象(地图 API) [英] Loading CSV with FileReader to make JS Objects for Map Markers (Maps API)

查看:10
本文介绍了使用 FileReader 加载 CSV 以制作用于地图标记的 JS 对象(地图 API)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我正在尝试加载一个 csv 文件,将其解析为一组 js 对象,并使用这些对象通过 Google Maps API 制作地图标记.

加载工作,解析工作,所有值都是正确的(据我所知),我一直在控制台登录到死,我得到了我想要的值,但是......我的地图没有加载.

我想可能是因为时间问题?就像地图未初始化或未正确加载一样.

我偶尔会收到来自 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 公司;//检查 csv 文件.如果是,则运行程序.如果不是,则显示错误.如果(文件.类型.匹配(文本类型)){var reader = new FileReader();reader.onload = function(e) {var text = reader.result;//记录调试.成功.//控制台日志(文本);//解析 csv 文件并使对象存储在公司数组中.函数 csvParse(csv) {var 行 = csv.split("
");//记录调试.成功.//console.log(lines);var 结果 = [];var headers = lines[0].split(",");for (var i = 1; i 

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

非常感谢!

解决方案

您发布的代码未包含所有问题.

  1. 我注释掉了 if (file.type.match(textType)) { 测试,这给了我一个错误:文件不受支持!"小提琴

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

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

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

致:

var latitude = parseFloat(companys[company].lat);var longitude = parseFloat(companys[company].long);

  1. 您的地图没有大小,所以一旦经度"问题得到解决,您就看不到它了.

  2. 顺便说一句,您的 css 有问题,下面的行会导致地图控件出现伪影,我已将其删除:

    img {最大宽度:100%;}

工作jsfiddle

使用的数据文件:

name,type,sites,lat,long,dummyYum Brands,QSR,36000,38.198117,-85.695723,nothing麦当劳,QSR,11772,41.848117,-87.944818,nothingDollar General,Discount,8414,36.309512,-86.699107,nothingWalMart,Big Box,7873,36.365399,-94.217752,nothingWalgreens,药店,7500,42.156776,-87.871079,nothing星巴克,QSR,6793,47.581000,-122.335855,没有Dunkin Brands,QSR,6500,42.207285,-71.129786,nothingCVS,药店,6301,41.990542,-71.477562,没有Gamestop,Specialty,6207,32.902302,-97.087347,nothing7-11,C-Store,6100,32.791810,-96.795768,无Family Dollar,Discount,6000,35.131827,-80.731703,nothingCouche 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 公司;//检查 csv 文件.如果是,则运行程序.如果不是,则显示错误.//if (file.type.match(textType)) {var reader = new FileReader();reader.onload = function(e) {var text = reader.result;//记录调试.成功.//控制台日志(文本);//解析 csv 文件并使对象存储在公司数组中.函数 csvParse(csv) {var 行 = csv.split("
");//记录调试.成功.//console.log(lines);var 结果 = [];var headers = lines[0].split(",");for (var i = 1; i 

html {字体系列:Helvetica、Arial、sans-serif;字体大小:100%;背景:#333;}html,{高度:100%;宽度:100%;}#page-wrapper {宽度:600px;背景:#FFF;填充:1em;保证金:1em 自动;最小高度:300px;边框顶部:5px 实心 #69c773;box-shadow: 0 2px 10px rgba(0, 0, 0, 0.8);}h1{边距顶部:0;}#fileDisplayArea {边距顶部:2em;宽度:100%;溢出-x:自动;}#地图画布{高度:100%;边距:0px;填充:0px}

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></脚本><div id="page-wrapper"><h1>CSV 文件到 JS 对象测试</h1><div>选择一个 CSV 文件:<input type="file" id="fileInput"/>

<pre id="fileDisplayArea"><pre>

<div id="map-canvas" style="height: 500px; width: 500px;"></div>

Basically I'm trying to load a csv file, parse it to an array of js objects and use those objects to make map markers with the Google Maps API.

The loading works, the parsing works, all the values are correct (to my knowledge), I've been console logging to death and I get the values that I want but... my map isn't loading.

I think it may be because of timing? Like the map isn't initializing or being loaded correctly.

I occasionally get errors about connections timing out and security errors from the Maps API but refreshing the page and reloading the csv seems to clear that up. The errors come and go.

Here's the 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("
");

          // 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!";
    }
  });
}

Also here is a gist with all the files : https://gist.github.com/mhelmetag/20eeae8cd4c901fb1094

Thanks so much in advance!

解决方案

Your posted code does not contain all the issues.

  1. I commented out the if (file.type.match(textType)) { test, that was giving me an error: "File not supported!" fiddle

  2. the csvParse function doesn't correctly parse the last entry of the file, you are getting NaN for the longitude (so the google.maps.LatLngs are not valid)

  3. removed the .toFixed(6) after the parseFloat call, changed:

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

To:

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

  1. your map doesn't have a size, so once the issue with "longitude" is fixed, you can't see it.

  2. as an aside you have an issue with your css, the line below causes artifacts with the map controls, I removed it:

    img { max-width: 100%; }

working jsfiddle

Data file used:

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

working code snippet:

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("
");

        // 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?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></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>

这篇关于使用 FileReader 加载 CSV 以制作用于地图标记的 JS 对象(地图 API)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆