如何将 Openlayers 6.5 鼠标位置控制从 LonLat 转换为 MGRS?

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

我正在使用这个控件

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

如果您使用带有 [lon, lat] 坐标数组和 returns MGRS 字符串的 mgrs 库 https://github.com/proj4js/mgrs,您可以使用它的 forward 方法作为 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/mgrs@1.0.0/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>