[GIS] Trouble displaying GeoJSON file in OpenLayers

geojsonopenlayers-2

I am noobie to OpenLayers and can not for the life of me figure out how to display a GeoJSON file. This seems like it should be easy but I have been banging my head for a day. I'm sure I am missing something obvious. I have my GeoJSON file (countries.json) on a server and basically followed the instructions in "OpenLayers:beginners guide" word for word so I don't know why the thing won't display. Here is my code:

function init(){
    map = new OpenLayers.Map('map_element', {});        
    var vector_strategies = [new OpenLayers.Strategy.Fixed()];
    var vector_format = new OpenLayers.Format.GeoJSON({
        externalProjection: new OpenLayers.Projection("EPSG:4326"),
        internalProject: new OpenLayers.Projection("EPSG:900913")
    });
    var vector_protocol = new OpenLayers.Protocol.HTTP({
        url: 'ne_50m_admin_WM.json',
        format: vector_format
    });

    vector_layer = new OpenLayers.Layer.Vector('Countries',{
        protocol:  vector_protocol,
        strategies: vector_strategies
    });

    map.addLayer(vector_layer);
    if(!map.getCenter()){
    map.zoomToMaxExtent();

I keep getting thrown this error: mapProjection is null

Does anybody have any ideas what may be going astray?

Best Answer

DSaeger,

I've used the book too, but it looks like you're attempting to switch to the Spherical Meractor projection for your GeoJSON layer (as described in the one section of the book). So, I first would define your map as such:

map = new OpenLayers.Map("map", {

    projection: new OpenLayers.Projection("EPSG:3857"),
    units: "m",
    maxResolution: 156543.0339,
    maxExtent: new OpenLayers.Bounds(
        -20037508, -20037508, 20037508, 20037508.34),
    displayProjection: new OpenLayers.Projection("EPSG:4326"),
    controls: [
        new OpenLayers.Control.Navigation(),
        new OpenLayers.Control.KeyboardDefaults(),
        new OpenLayers.Control.PanZoomBar(),
        new OpenLayers.Control.Scale(),
        new OpenLayers.Control.Attribution()
    ]

});

This will define your map for spherical mercator so that you can display map backgrounds from Google Maps as well. The controls are just what I include as well as the maxResolution. BTW, with OL 2.11, the latest Spherical Mercator EPSG 3857 is coded into OL. So, no need to use a Proj4js defs statement if that's the projection of the map you wish to display your data in. After that, you can add a baselayer from OpenStreetMap:

var osm = new OpenLayers.Layer.OSM("OpenStreetMap");

Then, as I was testing this at one time after reading the book, I defined the vector Style and StyleMap:

var vector_style = new OpenLayers.Style({
          strokeWidth:2, fillOpacity:0, strokeColor: '#008000'});


var vector_style_map = new OpenLayers.StyleMap({
         'default': vector_style,
         'select': {strokeColor: '#0000FF'}
});

So, this will plot my GeoJSON vector layer in green and if it's a polygon, won't fill it. If I had a selectfeature function defined, it would highlight it in blue.

Next comes your vector layer with your GeoJSON file and transformed from 4326 to 3857:

var vectorlyr = new OpenLayers.Layer.Vector(
                  "test",{
                   protocol: new OpenLayers.Protocol.HTTP({
                      url: 'myfile.geojson',
                      format: new OpenLayers.Format.GeoJSON({
                          internalProjection: new OpenLayers.Projection("EPSG:3857"),
                          externalProjection: new OpenLayers.Projection("EPSG:4326")})
                  }),
                  strategies: [new OpenLayers.Strategy.Fixed()],
                  styleMap: vector_style_map


                 });            

Note that the GeoJSON file should be on your server. For my test page, it's in the same location on the server as the page.

Finally, add the layers to the map, center it, and set the zoom level. As the map is defined for spherical mercator, you have to transform the map.setCenter from lon/lat to the coordinates in map units. Now, this code was taken from one of my test pages for GeoJSON vectors and I probably could add the LayerSwitcher control when I define the map controls above.

// add layers to the map

map.addLayers([osm, vectorlyr]);

map.addControl(new OpenLayers.Control.LayerSwitcher());

// transform coordinates for centering the map and set zoom level

map.setCenter(new OpenLayers.LonLat(-120, 40).transform(
    new OpenLayers.Projection("EPSG:4326"),
    map.getProjectionObject()
), 4);

If you've followed what's necessary for the rest of the page (i.e. HTML, OL, etc), then hopefully, this should help get you going.