Formatting MousePosition control output in OpenLayers 3

I show the mouse position in OpenLayers 3 with the following control

var mousePositionControl = new ol.control.MousePosition({ coordinateFormat: ol.coordinate.createStringXY(2), projection: 'EPSG:4326', undefinedHTML: ' ' }); 

But the result shows the mouse position as Lon, Lat, not Lat, Lon.

Here is a jsfiddle example .

How can I cancel the order so that it is Lat, Lon?

+7
openlayers-3
source share
5 answers

What works for me to add various controls, including Lat, Long:

 var controls = [ new ol.control.Attribution(), new ol.control.MousePosition({ projection: 'EPSG:4326', coordinateFormat: function(coordinate) { return ol.coordinate.format(coordinate, '{y}, {x}', 4); } }), new ol.control.ScaleLine(), new ol.control.Zoom(), new ol.control.ZoomSlider(), new ol.control.ZoomToExtent(), new ol.control.FullScreen() ]; 
(modified from openlayers 3 book )
+8
source share

You change your coordinate Format - "standard function" to a user-defined function:

 var myFormat = function(dgts) { return ( function(coord1) { var coord2 = [coord1[1], coord1[0]]; return ol.coordinate.toStringXY(coord2,dgts); }); } var mousePositionControl = new ol.control.MousePosition({ coordinateFormat: myFormat(2), // <--- change here projection: 'EPSG:4326', className: 'custom-mouse-position', target: document.getElementById('mouse-position'), undefinedHTML: '&nbsp;' }); 

see modified fiddle

+4
source share

Alternative:

 var template = 'LatLon: {y}, {x}'; var mousePositionControl = new ol.control.MousePosition({ coordinateFormat: function(coord) {return ol.coordinate.format(coord, template, 2);}, projection: 'EPSG:4326', undefinedHTML: '&nbsp;' }); 
+3
source share

It is also useful to display in degrees, minutes, seconds:

 controls: ol.control.defaults().extend([ new ol.control.ScaleLine({ units: 'nautical' }), new ol.control.MousePosition({ coordinateFormat: function(coord) { return ol.coordinate.toStringHDMS(coord); }, projection: 'EPSG:4326', className: 'custom-mouse-position', target: document.getElementById('mouse-position'), undefinedHTML: '&nbsp;' }) ]), 
+2
source share

Works in OpenLayers 3.7.0. Using proj4js to reprogram coordinates for another projector due to map display in "EGPS: 3857":

 var proj1 = proj4.defs('EPSG:4326'); var proj2 = proj4.defs('EPSG:3857'); var myFormat = function(digits) { return ( function(originalCoordinates) { var reprojectedCoordinates = proj4(proj2, proj1).forward(originalCoordinates); var switchedCoordinates = [reprojectedCoordinates[1], reprojectedCoordinates[0]]; return ol.coordinate.toStringXY(switchedCoordinates, digits); } ); } var mousePositionControl = new ol.control.MousePosition({ coordinateFormat: mojFormat(10), projection: 'ESPG:4326', undefinedHTML: '&nbsp' }); // map.addControl(mousePositionControl); //equivalent to setMap mousePositionControl.setMap(map); 
0
source share

All Articles