Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting the MousePosition control output in OpenLayers 3

Tags:

openlayers-3

I'm showing 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 rather than Lat,Lon.

Here's a jsfiddle example.

How can I reverse the order so that it's Lat,Lon?

like image 603
sfletche Avatar asked Nov 12 '14 06:11

sfletche


2 Answers

What works for me to add a variety of controls incl Lat, Long is:

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 the book of openlayers 3)
like image 140
Elleve Avatar answered Oct 30 '22 16:10

Elleve


You change your coordinateFormat - "standard function" to a custom 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 your modified fiddle

like image 26
Anders Finn Jørgensen Avatar answered Oct 30 '22 16:10

Anders Finn Jørgensen