Tuesday 10 January 2017

coordinate system - Change OpenLayers 3 view center


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?



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);
}

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...