Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Openlayers 3.6: Getting the center of the current map view

Tags:

openlayers-3

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!

like image 201
Crankycyclops Avatar asked Jul 10 '15 19:07

Crankycyclops


3 Answers

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.

like image 195
joe.dawley Avatar answered Sep 27 '22 18:09

joe.dawley


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',
)
like image 42
Raphaël Balet Avatar answered Sep 27 '22 17:09

Raphaël Balet


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() )
like image 21
Dean Jenkins Avatar answered Sep 27 '22 17:09

Dean Jenkins