[GIS] Problem loading a GeoJSON file using Openlayers

geojsonopenlayers-2

I am setting up a website using Openlayers and GeoJSON files. When I get the GeoJSON file using the code below it work as expected.

url: "./file.geojson",

But if I try and use the full domain call, see below, it does not work. Why?

url: "http://www.domain.com/file.geojson",

I need to use the full domain call because I am trying to test it locally on my computer. Is there a way to get the file locally from my computer?

<!DOCTYPE html>

var lon = -80.233,
lat = 40.665,
zoom = 15,
epsg4326 = new OpenLayers.Projection('EPSG:4326'),
epsg900913 = new OpenLayers.Projection('EPSG:900913');
var arrayAerial;
var select;

    function init(){
        var map = new OpenLayers.Map('map', {
            units: 'm',
            numZoomLevels: 19,
            controls: [
                new OpenLayers.Control.Navigation(),
                new OpenLayers.Control.ScaleLine(),
                new OpenLayers.Control.MousePosition(),
                new OpenLayers.Control.LayerSwitcher(),
                //new OpenLayers.Control.OverviewMap(),
                new OpenLayers.Control.PanZoomBar()
            ],
            projection: epsg900913,
            displayProjection: epsg4326 //Is used for displaying coordinates in appropriate CRS by MousePosition control
        });






        arrayOSM = ["http://otile1.mqcdn.com/tiles/1.0.0/map/${z}/${x}/${y}.jpg",
                "http://otile2.mqcdn.com/tiles/1.0.0/map/${z}/${x}/${y}.jpg",
                "http://otile3.mqcdn.com/tiles/1.0.0/map/${z}/${x}/${y}.jpg",
                "http://otile4.mqcdn.com/tiles/1.0.0/map/${z}/${x}/${y}.jpg"];


        arrayAerial = ["http://otile1.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.jpg",
                    "http://otile2.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.jpg",
                    "http://otile3.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.jpg",
                    "http://otile4.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.jpg"];

        baseOSM = new OpenLayers.Layer.OSM("MapQuest-OSM Tiles", arrayOSM);                        
        baseAerial = new OpenLayers.Layer.OSM("MapQuest Open Aerial Tiles", arrayAerial);

        var sanpipe_layer = new OpenLayers.Layer.Vector("San Sewer", {
            styleMap: new OpenLayers.StyleMap({
                    "default": new OpenLayers.Style({
                    pointRadius: 5,
                    fillColor: "#2da725",
                    fillOpacity: 0.8,
                    strokeColor: "#2da725",
                    strokeWidth: 3,
                    strokeOpacity: 0.8 } ),

                }),

            projection: epsg4326,
            strategies: [new OpenLayers.Strategy.Fixed()],
            protocol: new OpenLayers.Protocol.HTTP({
                url: "./sanpipe.geojson",
                format: new OpenLayers.Format.GeoJSON()
            })
        });

        var mh_layer = new OpenLayers.Layer.Vector("Manholes", {
            styleMap: new OpenLayers.StyleMap({
                    "default": new OpenLayers.Style({
                    pointRadius: 5,
                    fillColor: "#9de24f",
                    strokeColor: "#0d4cd6",
                    strokeWidth: 1,
                    strokeOpacity: 0.8 } ),

                }),

            projection: epsg4326,
            strategies: [new OpenLayers.Strategy.Fixed()],
            protocol: new OpenLayers.Protocol.HTTP({
                url: "./mh.geojson",
                format: new OpenLayers.Format.GeoJSON({
                    extractAttributes: true
                })
            })
        });

        var waterline_layer = new OpenLayers.Layer.Vector("waterline", {
            styleMap: new OpenLayers.StyleMap({
                    "default": new OpenLayers.Style({
                    pointRadius: 5,
                    fillColor: "#00FF01",
                    fillOpacity: 0.8,
                    strokeColor: "#0d4cd6",
                    strokeWidth: 3,
                    strokeOpacity: 0.8 } ),

                }),

            projection: epsg4326,
            strategies: [new OpenLayers.Strategy.Fixed()],
            protocol: new OpenLayers.Protocol.HTTP({
                url: "./waterline.geojson",
                format: new OpenLayers.Format.GeoJSON()
            })
        });

        var valves_layer = new OpenLayers.Layer.Vector("Valves", {
            styleMap: new OpenLayers.StyleMap({
                    "default": new OpenLayers.Style({
                    pointRadius: 3,
                    fillColor: "#fdf700",
                    strokeColor: "#0d4cd6",
                    strokeWidth: 1,
                    strokeOpacity: 0.8 } ),

                }),

            projection: epsg4326,
            strategies: [new OpenLayers.Strategy.Fixed()],
            protocol: new OpenLayers.Protocol.HTTP({
                url: "./valves.geojson",

                format: new OpenLayers.Format.GeoJSON()
            })
        });

        var hyd_layer = new OpenLayers.Layer.Vector("Hydrants", {
            styleMap: new OpenLayers.StyleMap({
                    "default": new OpenLayers.Style({
                    pointRadius: 5,
                    fillColor: "#d81417",
                    strokeColor: "#0d4cd6",
                    strokeWidth: 1,
                    strokeOpacity: 0.8 } ),

                }),

            projection: epsg4326,
            strategies: [new OpenLayers.Strategy.Fixed()],
            protocol: new OpenLayers.Protocol.HTTP({
                url: "./hyd.geojson",

                format: new OpenLayers.Format.GeoJSON()
            })
        });

        map.addLayer(baseOSM);
        map.addLayer(baseAerial);
        map.addLayer(sanpipe_layer);
        map.addLayer(mh_layer);
        map.addLayer(waterline_layer);
        map.addLayer(valves_layer);
        map.addLayer(hyd_layer);

        select = new OpenLayers.Control.SelectFeature(mh_layer);

        mh_layer.events.on({
            "featureselected": onFeatureSelect,
            "featureunselected": onFeatureUnselect
        });

        map.addControl(select);
        select.activate();  

        map.setCenter(new OpenLayers.LonLat(lon, lat).transform(epsg4326, epsg900913), zoom);
    }

    function onPopupClose(evt) {
        select.unselectAll();
    }
    function onFeatureSelect(event) {
        var feature = event.feature;
        popup = new OpenLayers.Popup.FramedCloud("chicken", 
            feature.geometry.getBounds().getCenterLonLat(),
            null,
            "<h2>"+feature.attributes.STRUCT_ID + "</h2>",
            null, true, onPopupClose);

        feature.popup = popup;
        map.addPopup(popup);
    }

    function onFeatureUnselect(event) {
        var feature = event.feature;
        if(feature.popup) {
            map.removePopup(feature.popup);
            feature.popup.destroy();
            delete feature.popup;
        }
    }
</script>

Best Answer

To get the file properly, you need to follow these steps:

  1. Always use a webserver to host your own files. These kinds of calls will not be made if your browser is opening the html using the file protocol.

  2. If in your url (http://www.domain.com/file.geojson) the domain is not the same as the domain of your webserver, JavaScript cannot directly access the data. Due to Javascript security rules, you are not allowed to make an XMLHttpRequest to another server. For example, if you have your openlayers application running off your webserver, and you are accessing it as http://localhost/map.html, the JavaScript won't be able to access an location such as http://www.example.com/file.geojson.

    In this case you will be required to use a proxy. The OpenLayers FAQ has a section on setting up your own ProxyHost. Here's the relevant excerpt:

How do I set up a ProxyHost?

An example proxy host script is available here: trunk/openlayers/examples/proxy.cgi

For the standard Apache configuration, you would place proxy.cgi into your /usr/lib/cgi-bin/ directory.

Once a proxy host script has been installed, you must then edit the OpenLayers.ProxyHost variable to match that URL.

Given the above standard Apache configuration:

OpenLayers.ProxyHost = "/cgi-bin/proxy.cgi?url=";

If you have done something like this, you should be able to visit:

http://YourDomain.example.com/cgi-bin/proxy.cgi

The resulting content at that page should be the openlayers.org website.

If you get a 404 error instead, either the proxy script is not in the right location, or your webserver is not configured correctly.