4
votes

this is the first time i use OpenLayers and i don't understand what i'm doing wrong.

I try to display a simple point parsed from GeoJSON. The data seems to be parsed correctly (i checked with the console) but whatever point i give, it always displays at a position i guess to be LonLat(0,0) on my vector layer.

What am i doing wrong ?

var map, baseLayer, placesLayer, geojsonParser ;
// data below have been simplified and reformated to enhance readability
var geojsonData = 
{
    "type":"Feature",
     "geometry":
     {
        "type":"Point",
        "coordinates":[-4.0280599594116,5.3411102294922]
     },
     "properties":
     {
        "id":273,
        "name":"ABIDJAN"
     }
};

$(document).ready(function(){

map = new OpenLayers.Map('map');
  baseLayer = new OpenLayers.Layer.OSM();
  placesLayer = new OpenLayers.Layer.Vector();

  geojsonParser = new OpenLayers.Format.GeoJSON();
  placesLayer.addFeatures(geojsonParser.read(geojsonData));

  map.addLayers([baseLayer,placesLayer]);
  map.setCenter(
    new OpenLayers.LonLat(-4, 5.3).transform(
      new OpenLayers.Projection("EPSG:4326"),
      map.getProjectionObject()
    ), 5
  );

}); // document ready
2

2 Answers

7
votes

This is the right solution:

var geojson_format = new OpenLayers.Format.GeoJSON({
                'internalProjection': new OpenLayers.Projection("EPSG:900913"),
                'externalProjection': new OpenLayers.Projection("EPSG:4326")
            });

source: https://gist.github.com/1118357

3
votes

Hi it sounds like you need to transform the long/lat coordinaites into the correct display coordinates:

You can either declare the projections and then transform your geometry feature:

var projWGS84 = new OpenLayers.Projection("EPSG:4326");
var proj900913 = new OpenLayers.Projection("EPSG:900913");

feature.geometry.transform(projWGS84, proj900913);

Or get the map projection "on the fly" more like this:

var projWGS84 = new OpenLayers.Projection("EPSG:4326");    
feature.geometry.transform(projWGS84, map.getProjectionObject());

Obviously if you are using a different input projection from me change "ESPG:4326" to whatever you require.

HTH

C

EDIT:

In your case you would need to write something like:

geojsonData.geometry.transform(projWGS84, map.getProjectionObject());