[GIS] Projecting EPSG:4326 with OpenLayers 2 and GeoJSON

coordinate systemgeojsonjavascriptopenlayers-2

I'm trying to project some GeoJSON data but it ends up at 0,0. I've looked at other posts and tried those solutions to no avail.

Can anyone help?

Here is the code:

<html>
<head>
  <title>OpenLayers Example</title>
    <script src="../lib/OpenLayers.js"></script>
</head>
<body>
  <div style="width:100%; height:100%" id="map"></div>
  <script defer='defer' type='text/javascript'>
    var featurecollection = {
        "type": "Feature",
        "geometry": { "type": "Point", "coordinates": [15.87646484375, 44.1748046875]},
         properties": {"id": "1", "Tradnummer": "1", "Art": "Betula pendula" } 
    };    
    var map = new OpenLayers.Map('map', {
      projection: new OpenLayers.Projection("EPSG:900913")
    });    
    var layer = new OpenLayers.Layer.OSM("Open Street Map");
    map.addLayer(layer);
    //map.zoomToMaxExtent();    
    var layerProj = new OpenLayers.Projection("EPSG:4326");
    var targetProj = new OpenLayers.Projection("EPSG:900913");
    var geojson_format = new OpenLayers.Format.GeoJSON();
    var geojson = new OpenLayers.Layer.Vector("GeoJSON", {
      projection: new OpenLayers.Projection("EPSG:4326"),
      format: OpenLayers.Format.GeoJSON
    });    
    geojson.addFeatures(geojson_format.read(featurecollection));
    // Need to transform the features geometry here?
    var feature = geojson.features[0];
    var geometry = feature.geometry.clone();
    geometry.transform(layerProj, targetProj);    
    map.addLayer(geojson);    
  </script>
</body>
</html>

Best Answer

Found a solution here.

Have amended my code to this:

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

  projection: new OpenLayers.Projection("EPSG:3857"),
  units: "m",
  maxResolution: 156543.0339,
my      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()
      ]
    });

var osm = new OpenLayers.Layer.OSM("Open Street Map");

var vectorlyr = new OpenLayers.Layer.Vector(
  "test",{
    protocol: new OpenLayers.Protocol.HTTP({
    url: 'json1.php',
    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*/
});

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(11.59, 57.43).transform(
  new OpenLayers.Projection("EPSG:4326"),
  map.getProjectionObject()
), 4);

Hope this helps someone else :)