单击映射后如何使长纬度坐标可见并在下次单击之前可见?

How to make visible long lat coordinates after click to map and make visible until next click?

来自 this 代码,用于在将鼠标移到地图上后显示长纬度坐标。我用最新的 OpenLayers 版本重写了 HTML 页面。

我想在点击地图中的某个地方后显示这个长纬度坐标,而不是像代码中那样在地图上移动鼠标后。并且 使最后一个坐标可见,直到有人点击 到下一个地方,什么都没有。我不希望坐标像代码中那样立即消失。

<!doctype html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.0/css/ol.css" type="text/css">
    <style>
      .map {
        height: 400px;
        width: 100%;
      }
    </style>
    <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.0/build/ol.js"></script>
    <title>OpenLayers example</title>
  </head>
  <body>
  <div id="myposition"></div>
    <h2>My Map</h2>
    <div id="map" class="map"></div>
    <script type="text/javascript">
      var osm_default = new ol.layer.Tile({
        source: new ol.source.OSM()
      });

      var map = new ol.Map({
        layers: [osm_default],
        target: 'map',
        view: new ol.View({
          center: ol.proj.transform([-1.81185, 52.443141], 'EPSG:4326', 'EPSG:3857'),
          zoom: 6
        })
      });

      var mousePosition = new ol.control.MousePosition({
        coordinateFormat: ol.coordinate.createStringXY(2),
        projection: 'EPSG:4326',
        target: document.getElementById('myposition'),
        innerHTML: '&nbsp;'
      });

      map.addControl(mousePosition);
    </script>
  </body>
</html>

在您的地图上使用 singleclick or click 事件:

map.on('singleclick', event => { 
  const coordinate = ol.proj.toLonLat(event.coordinate);
  const innerText = `Lon: ${coordinate[0].toFixed(4)}, Lat: ${coordinate[1].toFixed(4)}`;

  document.getElementById('myposition').innerText = innerText;
});