Search code examples
javascripteventsonclickopenlayersgetelementbyid

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


from this code for make visible long lat coordinate after moving the mouse over the map. And I rewrite to HTML page with newest OpenLayers version.

I would like to show this long lat coordinates after click to some place in map, not after move mouse on map as in the code. And make visible last coordinate until someone click to next place, nothing. I don't want the coordinates to disappear right away as in code.

<!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>

Solution

  • Use singleclick or click event on your map:

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