Search code examples
coordinatesopenlayersgeojsontransformation

Open Layers: how to do coordinate system transformation on vector-source


I am trying to include a map in my application. I load data from a postgis database, where it is stored as wgs84. The data is loaded as geojson and displayed by open layers. The problem is that the data is currently being projected somewhere in the ocean, I therefore suspect the data needs to be translated into a different coordinate system. This is the code to create the map object:

var map = new ol.Map({
        projection: 'EPSG:4326',
        target: 'map',
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM(),
          })
        ],
        view: new ol.View({
          center: ol.proj.fromLonLat([5, 52]),
          zoom: 4
        })
      });

And this is the code I use to load the data:

function addObjectsToMap()
        {
            var vectorSource = new ol.source.Vector({
                features: new ol.format.GeoJSON().readFeatures( <?php print_r($object->getLocationsAsGeoJson()); ?> )
            });
            var vectorLayer = new ol.layer.Vector(
            {
                source: vectorSource
            });
            map.addLayer(vectorLayer);
        }

I have already tried setting the coordinate system of the map to epsg:900913, I tried adding this in the vectorLayer:

preFeatureInsert: function(feature) 
            {
                feature.geometry.transform(new ol.proj.Projection("EPSG:4326"),new ol.proj.Projection("EPSG:900913"));
            },

I tried adding: .transform('EPSG:4326','EPSG:900913') to the dataimport (where the vector source is created) And I tried looping over the the data in my vectorsource like this:

vectorSource.getFeatures()[i].setGeometry(vectorSource.getFeatures()[i].getGeometry().transform(new ol.proj.Projection("EPSG:4326"),new ol.proj.Projection("EPSG:900913")));

I would really appreciate it if someone could point me in the right direction. Surely this is something common and should be very easy to deal with. But I cannot find anything about it in the documentation or examples of open layers.


Solution

  • The features can be transformed to the view projection using dataProjection and featureProjectiion options when reading the features

               features: new ol.format.GeoJSON().readFeatures( <?php print_r($object->getLocationsAsGeoJson()); ?> , {
                  dataProjection: 'EPSG:4326',
                  featureProjection: map.getView().getProjection()
               })