Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reproject map extent in openlayers 3

I want to set an extend on my Openlayers 3.9.0 map.

When the page loads, I want the map to already be centered in that extend, no matter the layers. So I guess I will set an extend to the view, right?

Map contains a single OSM layer like

var layer = new ol.layer.Tile({
    source: new ol.source.OSM(

        {
        attributions: [
          new ol.Attribution({
            html: 'All maps © ' +
                '<a href="http://www.opencyclemap.org/">OpenCycleMap</a>'
          })
        ]            
      }             

    ),
    opacity: 0.8,
    brightness: 0.8
});

Then I set the view

var center = ol.proj.transform([21.54967, 38.70250], 'EPSG:4326', 'EPSG:3857');
    var view = new ol.View({
        center: center,
        zoom: 6,
        extent: [2297128.5,4618333.0 , 2459120.25,4763120.0]
    });

And then the map

var map = new ol.Map({
        target: 'map',
        layers: [layer],
        view: view,     
    });

I used my extend in an older project, with EPSG 900913. So to convert the extend from 900913 to default Openlayers 3 3857 I went here here and I put 2297128.5, 4618333 that convereted to 2297128.5,4618333.0

and then

2459120.25, 4763120that convereted to 2459120.25,4763120.0

my two problems

1- the converted coords look similar. Did I do something wrong?

2- the map is centered ok, but not zoomed in the extend. The coords define a county in Greece and the map does not zoom there, I see the whole Greece, along with Turkey and Italy.

What I did wrong? Thanks

like image 873
slevin Avatar asked Jan 07 '23 11:01

slevin


1 Answers

Thanks everyone. What I did was

Keep the OSM layer as is.

Define the limits of the county. Turns out it was EPSG 900913

var countyLimits= ol.proj.transformExtent([2297128.5, 4618333, 2459120.25, 4763120], 'EPSG:900913', 'EPSG:3857');

View is now

var view = new ol.View({
    center: center,
    zoom: 6,
    extent : countyLimits,
    maxZoom:20
});

map is

var map = new ol.Map({
    target: 'map',
    layers:[layer],
    view: view
});

After the map is defined, fit its view in the limits

    map.getView().fit(countyLimits, map.getSize()); 
//get the view of the map and fit it to the limits, according to the map's size

fitExtend is now deprecated, so I used fit. It is experimental , but I guess it will become standard since it replaced fitExtend.

Thanks anyway people

Sources

OL answer

OL3 API

like image 136
slevin Avatar answered Feb 16 '23 16:02

slevin