【问题标题】:How to make visible long lat coordinates after click to map and make visible until next click?单击地图后如何使长纬度坐标可见并在下次单击之前可见?
【发布时间】:2020-04-07 14:50:49
【问题描述】:

来自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>

【问题讨论】:

    标签: javascript events onclick openlayers getelementbyid


    【解决方案1】:

    在您的地图上使用singleclickclick 事件:

    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;
    });
    

    【讨论】:

    • 谢谢。我在找这个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多