I'm new to OpenLayers, so I'm sure this will be an easy win for someone :)

I'm trying to center a map on a point (and place markers) using lon/lat but it appears to take everything as meters?

    map = new OpenLayers.Map("map",{
    projection: new OpenLayers.Projection("EPSG:3857"),
    units: "dd",
    numZoomLevels: 18,
    maxResolution: 156543.0339,
    layers: [
        new OpenLayers.Layer.OSM("OpenStreetMap", null, {
            transitionEffect: 'resize'
    center: new OpenLayers.LonLat(-2.626944, 57.563222),
    zoom: 7
var markers = new OpenLayers.Layer.Markers( "Markers" );

N.B. this code isn't designed to add markers, I will need to but the problem is clearly with this chunk as I'm being centered (almost) at the 0,0 I've tryed the following code

var size = new OpenLayers.Size(21,25);
var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
var icon = new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png', size, offset);
var i=0;
function Go() {
    x = document.getElementById("x");
    x.innerHTML = i;
    markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(i,10),icon));

Calling go on a mouse click, and indeed my marker moves a small amount (I'm guessing 10 meters) to the right every click.


It's a projection problem, you just need to transform the coordinates. When you give the marker position as longitude/latitude, you are meaning the markers are in "EPSG:4326", while you base layer projection is "EPSG:900913". By applying a transform function you may get the right coordinates:

var sourcePrj = new OpenLayers.Projection("EPSG:4326");
markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(i,10).transform(sourcePrj, map.getProjectionObject()),icon));

And something out of the scope of this problem but also worth to mention is that your map projection is usually determined by current base layer's projection, so it's no use to define the projection as OpenLayers.Projection("EPSG:3857") in map object though "EPSG:3857" is an alias to "EPSG:900913". "EPSG:900913" is used by most of the commercial base maps and osm base maps, and if you need to combine overlay layers that are using either an alias or the official EPSG code with an OpenLayers SphericalMercator layer, you have to make sure that OpenLayers requests EPSG:3857 or other alias in stead of EPSG:900913. You can get more details from here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.