1

I've written some code to create a vector layer based on a GeoJSON file located on my computer. I've deployed the tomcat server and put my GeoJSON file in some path like:

webapps/OpenLayersAsset/countries.geojson

Next using the following code to show the file but I get the error "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/OpenLayersAssets/countries.geojson". Does it cause the byGeoJSON location or something else?

var countrySource = new ol.source.Vector({
    format: new ol.format.GeoJSON(),
    url: 'http://localhost:8080/OpenLayersAssets/countries.geojson',
    projection: 'EPSG:3857'
});
var countryLayer = new ol.layer.Vector({
    source: countrySource
});

var center = ol.proj.transform([51.34, 35.65], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
    center: center,
    zoom: 8
});

var map = new ol.Map({
    target: 'map',
    layers: [countryLayer],
    view: view
});
1

If you have found the "Cross domain" error, you are requesting resources from different base URLs. The browser imposes the same origin policy.

The port counts (using 8080 makes its a different URL). So, if you request things from http://localhost/ol3.js and from http://localhost:8080/OpenLayersAssets/countries.geojson you will end up with the "Cross domain" error.

To prevent same origin policy protecting, you can:

  • Make sure you serve all your resources from the same base URL, like http://localhost:8080/...
  • Use a proxy and request all external resources using the proxy (it is more complicated)
  • Configure tomcat to allow CORS requests. Edit the $CATALINA_HOME/conf/web.xml file to add another filter, as explained in https://stackoverflow.com/questions/22363192/cors-tomcat-geoserver/25025579
  • Thanks, jgrocha. I chose the third option as it was explained.Also I had added the "cors-filter" for another we.xml file related to Geoserver before but it differs. Thanks again! – nasser tahani Oct 17 '17 at 8:12

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.