繁体   English   中英

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

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

在将鼠标移到 map 上后, 从此代码中可以看到长纬度坐标。 我用最新的 OpenLayers 版本重写到 HTML 页面。

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

<!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上使用单击或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;
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM