-2

I've been trying to load a load a local geoJSON and i keep recieving the following error:

leaflet/geojson/3_mittel.geojson' 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 have tried a number of examples from this thread: https://gis.stackexchange.com/questions/68489/loading-external-geojson-file-into-leaflet-map

but i always get the same Error (CORS policy)

I can get it to work when using the raw.github link of the geoJSON but i dont want to use that method.

I also found another Post which is about this problem, but for OpenLayer and not for leaflet :

https://gis.stackexchange.com/questions/312776/cors-issue-loading-an-external-local-geojson-into-openllayers-5/312817#312817?newreg=0921159296a1468da296ed372b1d92b9

Maybe someone knows how to adjust the Code so that it works for leaflet.

let xhr = new XMLHttpRequest();
xhr.open('GET', 'geojson/3_mittel.geojson');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = 'json';
xhr.onload = function() {
if (xhr.status !== 200) return
L.geoJSON(xhr.response).addTo(map);
};
xhr.send();

This is my current code ( one example from the first link)

CLa
  • 7
  • 3
  • 1
    _"from origin 'null'"_ This is a little weird, can you show us the code you are using. – phuzi May 30 '22 at 11:53
  • 1
    Could you edit the question and add it there please? It doesn't look like you're doing anything to modify the origin header (not even sure if you could!) Are you loading the page from the local filesystem? – phuzi May 30 '22 at 12:28
  • Yes i am loading the page from a local filesystem – CLa May 30 '22 at 12:46
  • 2
    Unfortunatley CORS policies will prevent you from making AJAX requests to local filesystem content, notice the list of supported protocol schemes doesn't inlcude `file`. You will need to load this page over http(s) from a local server. – phuzi May 30 '22 at 12:48
  • Thanks for your help first of all! But there is no way of loading a local geoJSON file into leaflet ? It seemed like a pretty "normal" thing to me – CLa May 30 '22 at 12:57
  • 2
    The problem is not loading geoJSON in to leaflet! it's the loading of local data. The browser is protecting you from having your filesystem read by a bad actor. By loading files over HTTP(S) then the scope of available resources is limited and controllable. – phuzi May 30 '22 at 13:00
  • 1
    How do you plan to use this? The user will visit your page and then your page will automatically load a file from his local drive? This is obviously not permitted. If you simply want to include a GeoJSON file along with your application, one way to do it is by using a bundler - check this React example - it uses a GeoJSON file packaged with the application by a bundler. – mmomtchev May 30 '22 at 20:53

0 Answers0