[GIS] cross domain problem with :OpenLayers.Protocol.HTTP

kmlopenlayers-2

this code works with local kml files, but not when the kml files are on my other server,
I got 3 error :

OPTIONS http://192.168.0.150:9000/files/anonymous/AVGHDOP.kml 404 (Not Found) XMLHttpRequest.js:220
OPTIONS http://192.168.0.150:9000/files/anonymous/AVGHDOP.kml Origin http://localhost is not allowed by Access-Control-Allow-Origin. XMLHttpRequest.js:220
XMLHttpRequest cannot load http://192.168.0.150:9000/files/anonymous/AVGHDOP.kml. Origin http://localhost is not allowed by Access-Control-Allow-Origin. 

so, I try to put headers in the OpenLayers.Protocol.HTTP. but it still is not working -_-.
here is my code:

map = new OpenLayers.Map('map');
osm = new OpenLayers.Layer.OSM();
vectors = new OpenLayers.Layer.Vector("KML", {
    strategies: [new OpenLayers.Strategy.Fixed()],
    protocol: new OpenLayers.Protocol.HTTP({
        url: url_file,//the file is on an other_server(a play server).
        headers: {
            "Access-Control-Allow-Origin":"*",
            "Access-Control-Allow-Headers":"Access-Control-Allow-Origin"},
        format: new OpenLayers.Format.KML({
            extractStyles: true,
            extractAttributes: true,
            maxDepth: 2
        })
    })
});
map.addLayers([osm, vectors]);
map.addControl(new OpenLayers.Control.MousePosition());
map.addControl(new OpenLayers.Control.EditingToolbar(osm));
vectors .events.register("loadend", vectors , function (e) {
    map.zoomToExtent(vectors .getDataExtent());
});

I dont know if I can configure a proxy. So if I can solve this problem without it it would be great 🙂

Best Answer

You would solve this using OpenLayers.request methods, check this out:

The above types of request are useful because they are asynchonous. That is, the user can continue to view and interact with the original page while additional data is being requested. A more common way to request data asynchronously is to use the XMLHttpRequst object. With an XMLHttpRequest object, you can open a conection to a server and send or receive data via HTTP (or HTTPS). XMLHttpRequest objects are a bit awkward to use and are unfortunately not supported in all browsers. OpenLayers provides a cross-browser XMLHttpRequest function and wraps it in some convenient OpenLayers.Request methods.

In this link you can find some examples to deal with your issue:

http://docs.openlayers.org/library/request.html

I think with this you can avoid using a proxy, but proxies are not a big deal in OpenLayers, check this out also:

https://collab.itc.virginia.edu/wiki/toolbox/Using%20A%20Proxy%20Script%20With%20Openlayers.html

Hope this helps,