OpenLayer3 - how to get the coordinates of the viewport

I have MapQuest displayed with OpenLayer3. I want to get viewport coordinates (map display area). For the whole card, this should be as follows: (180.90) x (-180, -90).

but I got: Upper right longitude: 37570328.14272983 Upper right latitude: 18941707.105292957 Left longitude: -37570328.14272983 Left latitude: -18941707.105292957

I have jsFiddle for it: http://jsfiddle.net/0d6d6kxf/2/

(click "Get coordinates of the viewport" to get the coordinates of the current map)

The command I use to get the coordinates: var extent = map.getView (). calculateExtent (map.getSize ());

Why is this result not in degrees? How to get the degree of coordination?

JS Code:

$(document).ready(function(){ object = new QuestMapWrapper(); object.openMap(); object.getViewportCords(); }); function QuestMapWrapper() { //private var var map; var view; //public var this.wrapperName="QuestMapWrapper"; //methods this.openMap = function() { //$('#ol-viewport').show(); //$('#gmap').hide(); //set layers of one var layers = [ new ol.layer.Tile({ style: 'Road', source: new ol.source.MapQuest({layer: 'osm'}) })] view = new ol.View({ //center: ol.proj.transform([20, 52.702222], 'EPSG:4326', 'EPSG:3857'), center: ol.proj.transform([0., 0.0], 'EPSG:4326', 'EPSG:3857'), //center: [-73.979378, 40.702222], zoom: 1 }); map = new ol.Map({ layers: layers, //renderer: exampleNS.getRendererFromQueryString(), target: 'map', view: view }); }; /** Set viewport details */ this.getViewportCords = function() { //var extent = view.calculateExtent( map.getSize() ); var extent = map.getView().calculateExtent(map.getSize()); //var extent = map.getExtent().transform(map.projection, map.displayProjection) var factor = 1; // coordinates must be devided by 100000 to get real coord $('#tr-lon').text(extent[2] / factor); $('#tr-lat').text(extent[3] / factor); $('#dl-lon').text(extent[0] / factor); $('#dl-lat').text(extent[1] / factor); } } 
+6
source share
1 answer

You are almost there.

 var extent = map.getView().calculateExtent(map.getSize()); 

This line is correct, but the coordinates you get are in the projection used by the map (EPSG: 3857), and you need to convert it back to normal lon / lat (WGS84 / EPSG: 4326).

enter the following line after the degree conversion:

 extent = ol.proj.transformExtent(extent, 'EPSG:3857', 'EPSG:4326'); 

As you can see, when you created the view, you use the conversion function to convert the center coordinates to EPSG: 3857, which is the format that the map understands. Whenever you send coordinates to a view, you need to send it to this projection. Whenever you read from a view, you need to convert it back to the projection you are using, in this case EPSG: 4326.

+18
source

Source: https://habr.com/ru/post/981596/


All Articles