Openlayers 3.6: Getting the center of the current map view
Asked Answered
W

3

8

I'm trying to get the current center of an Openlayers map in lat/lon coordinates. I've got the following event handler setup:

this.map.on('pointermove', function (e) {
    if (e.dragging) {
        console.log(that.map.getView().getCenter());
    }
});

This works, but I'm getting weird values. Here's an example:

[9318218.659044644, 3274618.6225819485]

Those are obviously not lat/lon values :) Do I need to transform this somehow? Thanks!

Waziristan answered 10/7, 2015 at 19:9 Comment(0)
S
17

I'm not super familiar with openlayers but it sounds like the map is in different projection.

Check out the following on spherical_mercator, transform, Open Layers projections

UPDATED
I've done a little more research, check out this example. Not sure what the projection your view is in. the map in this example is in ''EPSG:21781' if you go to a js console and enter map.getView().getCenter() you get [693230.7161150641, 179010.3389264635] but if you enter ol.proj.transform(map.getView().getCenter(), 'EPSG:21781', 'EPSG:4326') you get [8.658936030357363, 46.75575224283748] hope that helps.

Solidago answered 10/7, 2015 at 19:27 Comment(2)
Doh! My map was in EPSG:3857. The following line worked for me: ol.proj.transform(map.getView().getCenter(), 'EPSG:3857', 'EPSG:4326') Thank you!Waziristan
OpenLayers looks cool. I've only ever used google maps but I might have to play around.Solidago
E
4

For those who are working with angular.
Also, I would consider searching the projection of the map, instead of entering it manually.

import * as olProj from 'ol/proj'
import Map from 'ol/Map'

// ...

olProj.transform(
    this.map.getView().getCenter(),
    this.map.getView().getProjection(),
    'EPSG:4326',
)
Euchre answered 29/4, 2021 at 12:38 Comment(0)
S
2

Update for OpenLayers 6 (assuming your map is called 'map') the following gives an array of [lon, lat] for the centre of your map's view.

ol.proj.toLonLat( map.getView().getCenter() )
Snowonthemountain answered 18/5, 2020 at 11:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.