首页 > 解决方案 > 当用户使用 javascript 和 openlayers 在网页中单击地图时获取鼠标位置

问题描述

在 openlayers.org 网站上,有一个代码显示了鼠标在地图上的位置。但它不会将位置存储在变量中以供用户使用。当用户单击地图时,我希望有一个代码在窗口中显示用户的位置。请帮我。

我已将提供的代码 openlayers.org 用于显示鼠标的位置。

<!DOCTYPE html>
<html>
  <head>
    <title>Mouse Position</title>
    <link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
    <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
    <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
    <style>
      html, body {
        height: 100%;
        width: 100%;
    padding: 0px;
    margin: 0px;
      } 
      .map {
        height: 90%;
        width: 100%;
      }
    </style>
    <script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>
  </head>
  <body>
    <div id="map" class="map" "></div>

    <div id="mouse-position"></div>
    <form>
      <label>Projection </label>
      <select id="projection">
        <option value="EPSG:4326">EPSG:4326</option>
        <option value="EPSG:3857">EPSG:3857</option>
      </select>
      <label>Precision </label>
      <input id="precision" type="number" min="0" max="12" value="6"/>
    </form>
    <script>
      var mousePositionControl = new ol.control.MousePosition({
        coordinateFormat: ol.coordinate.createStringXY(6),
        projection: 'EPSG:4326',
        // comment the following two lines to have the mouse position
        // be placed within the map.
        className: 'custom-mouse-position',
        target: document.getElementById('mouse-position'),
        undefinedHTML: '&nbsp;'
      });

      var map = new ol.Map({
        controls: ol.control.defaults({
          attributionOptions: {
            collapsible: false
          }
        }).extend([mousePositionControl]),
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
        target: 'map',
        view: new ol.View({
          center: ol.proj.fromLonLat([51.39, 35.70]),
          zoom: 13
        })
      });

      var projectionSelect = document.getElementById('projection');
      projectionSelect.addEventListener('change', function(event) {
        mousePositionControl.setProjection(event.target.value);
      });

      var precisionInput = document.getElementById('precision');
      precisionInput.addEventListener('change', function(event) {
        var format = ol.coordinate.createStringXY(event.target.valueAsNumber);
        mousePositionControl.setCoordinateFormat(format);
      });


    </script>

</script> 
  </body>
</html>

结果是: 在此处输入图像描述

标签: javascriptopenlayers

解决方案


推荐阅读