0

I'm using D3 library to make a GeoMap chart. I downloaded a dataset from github "geonames" and wanted to use this data set in my map to check if my code works. I've used console.log to check if everything is going fine and IT IS! but the problem is that usin D3.CSV I cant access any file from my local directory, even if its saved on the same folder. I'm new to d3 but have been using JS, not professionally. would really appreciate help or suggestions.

These are both the options I've tried, first is from my local directory Second is from that github account from where I downloaded thew CSV file.

  1. d3.csv("geonames_cities100000.csv",type, render);

  2. d3.csv("https://github.com/curran/data/blob/gh-pages/geonames/cities1000000.csv",type,render);

I'm getting an error "Blocked by CORS policy: No 'Access-Control-Allow-Origin' , and thus my data is passing null.

Tejas
  • 894
  • 7
  • 24
Dehya Rao
  • 13
  • 3

2 Answers2

0

This can be solved using FileReader API.

Here is how to use the readAsBinaryString() from the FileReader API to load a local file.

<p>Select local CSV File:</p>
<input id="csv" type="file">

<output id="out">
    file contents will appear here
</output>

You would need to listen to change event in and call the readFile function.

var fileInput = document.getElementById("csv"),

    readFile = function () {
        var reader = new FileReader();
        reader.onload = function () {
            document.getElementById('out').innerHTML = reader.result;
        };
        // start reading the file. When it is done, calls the onload event defined above.
        reader.readAsBinaryString(fileInput.files[0]);
    };

fileInput.addEventListener('change', readFile);
Karan Verma
  • 158
  • 2
  • 6
0

You can also save your csv data as a GitHub Gist, which is very quick and easy.

This ObservableHQ - Introduction to Data is a really excellent tutorial, with screenshots, and will tell you how to overcome the CORS error issue.

Here is the Gist-related text from the tutorial:

A good choice is GitHub Gist. Simply drag-and-drop a file from your desktop onto the browser to upload it to GitHub.

Click the button to create the gist. Then on the next page, right-click the “Raw” button for your file, and select “Copy Link Address”.

Now you have a link to your file like this:

https://gist.github.com/mbostock/4063570/raw/11847750012dfe5351ee1eb290d2a254a67051d0/flare.csv

Unfortunately, this link doesn’t support CORS, so you’ll need to replace the “gist.github.com” domain with “gist.githubusercontent.com”

https://gist.githubusercontent.com/mbostock/4063570/raw/11847750012dfe5351ee1eb290d2a254a67051d0/flare.csv

At last! You have a publicly-accessible data URL.

Community
  • 1
  • 1
lemming
  • 1,753
  • 14
  • 12