1

I have a local folder on my network with my HTML file and two subfolders, one with the downloaded folder from OpenLayers (renamed ol) and the other with my GeoJSON file (data). When I try to load the HTML file in Chrome, I get a CORS error. Why do I get this even though the document is loading everything from the same file? Is there any way to load it with a JS file like you can with Leaflet? Here is my code:

<div id=map class=map><div>
        <script src="ol/ol.js"></script>
        <script type="text/javascript">
            var vectorSource = new ol.source.Vector({
                url: 'data/Hydrant.GeoJSON',
                format: new ol.format.GeoJSON()
            });

            var vectorLayer = new ol.layer.Vector({
                source: vectorSource
                });

            var map = new ol.Map({
                target: 'map',
                layers: [
                    new ol.layer.Tile({
                        source: new ol.source.OSM()
                    }),
                    vectorLayer
                ],
                view: new ol.View({
                    center: ol.proj.fromLonLat([-71.24, 42.06]),
                    zoom: 12
                })
            });
        </script>
    </div>
  • 1
    You can find answers to using Chrome and file protocol xhr on Stackoverflow, for example stackoverflow.com/questions/4819060/… Alternatively you can use another browser such as Edge which treats file protocol differently, or set up localhost to avoid using file protocol. – Mike Feb 19 at 18:34
1

Since you are only experimenting locally, one possibility is to edit your Hydrant.GeoJSON file and define geojson as JS object by adding var geojsonObject = at the beginning, rename file to Hydrant.GeoJSON.js and include it as JS code:

<script src="data/Hydrant.GeoJSON.js"></script>

Then you define your vector source as

var vectorSource = new ol.Source.Vector({
  features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
});

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.