Search code examples
mapscoordinatesmouseeventopenlayers-6

How to convert Openlayers 6.5 Mouse position control from LonLat to MGRS?


im using this control

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


Solution

  • If you use the mgrs library https://github.com/proj4js/mgrs which takes a [lon, lat] coordinate array and returns a MGRS string you can use its forward method as the coordinateFormat

    <!doctype html>
    <html lang="en">
      <head>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.5.0/css/ol.css" type="text/css">
        <style>
          html, body, .map {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
          }
        </style>
        <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.5.0/build/ol.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/mgrs.min.js"></script>
      </head>
      <body>
        <div id="map" class="map"></div>
        <script type="text/javascript">
          var mousePositionControl = new ol.control.MousePosition({
            coordinateFormat: mgrs.forward,
            projection: 'EPSG:4326',
            undefinedHTML: '&nbsp;'
          });
          var map = new ol.Map({
            target: 'map',
            controls: ol.control.defaults().extend([mousePositionControl]),
            layers: [
              new ol.layer.Tile({
                source: new ol.source.OSM()
              })
            ],
            view: new ol.View({
              center: [0, 0],
              zoom: 2
            })
          });
        </script>
      </body>
    </html>