This is a static archive of our old OSM Help Site. Please post any new questions and answers at community.openstreetmap.org.

openlayers - parameters for mapCenter

2

Hi, I am trying to run this very simple code:

var map;

function init()
{
    map = new OpenLayers.Map('map');

    layerMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik", {buffer: 4});
    map.addLayer(layerMapnik);

    map.setCenter(new OpenLayers.LonLat(16.5, 49.2), 5);
}

$(function(){
    init();
});

Everything is ok, map is displayed but it is still centered here http://img35.imageshack.us/img35/5333/6e03cfcd14e24b2c9e6c32e.png instead of here http://img338.imageshack.us/img338/4448/a501b38ec63e4da494b68da.png

Any thoughts what I am doing wrong?

asked 08 Feb '12, 12:05

Pirozek's gravatar image

Pirozek
35225
accept rate: 0%

edited 08 Feb '12, 12:33

SomeoneElse's gravatar image

SomeoneElse ♦
36.9k71370866


One Answer:

3

Your map is in spherical Mercator coordinates and you're setting it to a centre given in degrees. Try this:

var proj4326 = new OpenLayers.Projection("EPSG:4326");
var projmerc = new OpenLayers.Projection("EPSG:900913");
var lonlat = new OpenLayers.LonLat(16.5, 49.2);
lonlat.transform(proj4326, projmerc);
map.setCenter(lonlat, 5);

The problem you are seeing is a general OpenLayers issue when dealing with projections, and not limited to OpenStreetMap. Using a simpler toolbox like Leaflet would help you avoid these issues.

answered 08 Feb '12, 12:17

Frederik%20Ramm's gravatar image

Frederik Ramm ♦
82.5k927201273
accept rate: 23%

It works like a charm! Thanks man

(08 Feb '12, 12:20) Pirozek