Search code examples
openlayersgeojson

OpenLayers want to access multiple GeoJSON files to create one or more vector layers


If I had 200+ GeoJSON files defining borders of the world's countries, how would I get this data to appear on the map? Reading the multiple files is the part I cannot figure out. I know how to do this for a single GeoJSON file. Here's my single-file example:

var map, layer;

function init() {
  layer = new OpenLayers.Layer.WMS("OpenLayers WMS",
    "http://vmap0.tiles.osgeo.org/wms/vmap0", {
      layers: 'basic'
    }, {
      style: 'min-height:700px'
    });

  map = new OpenLayers.Map('map');
  map.addLayer(layer);
  createCountryBorders(map);

  map.setCenter(new OpenLayers.LonLat(0, 0), 4);
  map.zoomToMaxExtent();
}

function createCountryBorders(map) {
  var geoJsonLayer = new OpenLayers.Layer.Vector("Country Borders", {
    strategies: [new OpenLayers.Strategy.Fixed()],
    protocol: new OpenLayers.Protocol.HTTP({
      url: "countryborders/sub/countries-hires-line.json",
      format: new OpenLayers.Format.GeoJSON()
    })
  });
  map.addLayer(geoJsonLayer);
}

Solution

  • What kryger said in the answer above:

    Note that transferring 200 files over the network and then processing each of them is going to make initialization noticeable (and perhaps even unbearable!)

    I'de say unbearable and skip the noticable part. You should take full advantage of the capabilities of GeoJSON, one countryborder should be nothing more than one polygon or a multipolygon. that's one feature. You can create a GeoJSON featurecollection with multiple features, up to thousands if you want and put the entire collection in one file.

    {
        "type": "FeatureCollection",
        "features": [{
            "type": "Feature",
            "id": "AFG",
            "properties": {
                "Afghanistan"
            },
            "geometry": {
                "type": "MultiPolygon".
                "coordinates": [......]
            }
        }, {
            "type": "Feature",
            "id": "ALB",
            "properties": {
                "Albania"
            },
            "geometry": {
                "type": "MultiPolygon",
                "coordinates": [......]
            }
        }]
    }
    

    Check the GeoJSON spec for FeatureCollection: http://geojson.org/geojson-spec.html#feature-collection-objects

    As a matter of fact you don't have to do that yourself. There are many to find on the net. Like the one i used in this example i made for someone here on SO (mind you, it's leaflet but it should get the point across) Here on Plunker: http://plnkr.co/edit/UGQ9xt?p=preview and here's the repo i used on Github: https://github.com/johan/world.geo.json But it you take a look around there are lots of other sources for those world boundary shapes, even in very high detail.