1

I am using the the Leaflet Geocsv plug in to display markers with popups from a csv file. When trying to aacess the file my Chrome Browser puts out this error message:

Access to XMLHttpRequest at 'file:/........./test.csv' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

I want all of my files to be stored locally and not be hosted somewhere.

This is how I add the csv file to the map:

(function() {                                                                             
'use strict';            
$.get('data/test-csv.txt', function(csvContents) {
var geoLayer = L.geoCsv(csvContents, {firstLineTitles: true, fieldSeparator: ';'});
map.addLayer(geoLayer);
});
})();

And this is my test csv file:

lat;lng;title
52;8;test
8;52;test2

1 Answer 1

1

All modern browsers disable access to local files through AJAX (XMLHttpRequest) protocol for security reasons. If you don't want to set up local web server and want to use local file system to read your CSV data, to my knowledge this can be done only with some trickery, converting content of CSV to JS variable.

First you'll have to change content of your CSV file to JS script, something like this:

var csvContent = `lat;lng;title
52;8;test
8;52;test2`;

Then you rename it to text-csv.js and refer to it in your page:

<script src="data/test-csv.js"></script>

Final step is then to convert content of csvContent variable to object URL, which is then input to read CSV data (tested):

(function() {                                                                             
  'use strict';            
  var blob = new Blob([csvContent], { type: 'text/plain' });
  var blobUrl = URL.createObjectURL(blob);
  $.get(blobUrl, function(csvContents) {
    var geoLayer = L.geoCsv(csvContents, {firstLineTitles: true, fieldSeparator: ';'});
    map.addLayer(geoLayer);
  });
})();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.