OpenLayers Center View – How to Change OpenLayers 3 View Center

coordinate systemcoordinatesepsgopenlayersopenlayers-2

I'm using OpenLayers 3 to interact with some maps. I first declare my map:

map = new ol.Map({
            target: 'map',
            layers: [
              new ol.layer.Tile({
                  source: new ol.source.OSM()
              })
                ],
            view: new ol.View({
                center: [0, 0],
                zoom: 2
            })
        });

I've an event that triggers an action, to change my map's view center. This way, (my coordinates are in EPSG:4326 format):

function CenterMap(lat, long) {
     console.log("Lat: " + lat + " Long: " + long);
     map.setView(new ol.View({
            center: ol.proj.transform([lat, long], 'EPSG:3857', 'EPSG:4326'),
            zoom: 5
     }));
}

When the function runs I get this at the explorer console:

Lat: 9.0412851667 Long: -79.5658145000 

But the maps goes to [0,0], does anyone knows why this happen?

Best Answer

In ol.proj.transform you need to specify the fromProjection before the toProjection, then it should work.

As Michael Gentry explains in his answer, another Problem is that you have to specify the longitude (west-east thus x) first and then the latitude (south-north thus y).

And a better way to set the center is to get the current view and set the center there instead of always creating a new one.

function CenterMap(long, lat) {
    console.log("Long: " + long + " Lat: " + lat);
    map.getView().setCenter(ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857'));
    map.getView().setZoom(5);
}