javascriptopenlayersopenlayers-7

Get openlayers map data live while user interacts with map


I'm creating a webapp using openlayers (version 7.2) and I'm trying to figure out how to have a live output of the current center, zoom & rotation. I have found the 'movestart' and 'moveend' events however these both fire only once either at the beginning or end of the user interaction. I'm trying to find a way to continually update the information while the user is interacting. Any help would be appreciated.

Here is what I have using 'moveend' can anyone help me have this update while the user is still dragging/repositioning the map?

Here is my current code as well as alink to a JSFiddle. Thanks.

HTML

<div id="map" class="map"></div>
<div id="output">
    <h2>Map Information</h2>
    Center Position: <span id="center" class="info"></span><br>
    Current Zoom: <span id="zoom" class="info"></span><br>
    Current Rotation: <span id="rotation" class="info"></span>
</div>





CSS

#map{
    width: 300px;
    height: 300px;
}

#output{
    position: absolute;
    top: 8px;
    right: 8px;
    width: calc(100% - 340px);
    height: 150px;
    padding: 0 8px;
    background-color: lightgray;
    border: 1px dashed black;
}

#output h2{
    font-size: small;
    text-decoration:underline;
}

.info{
    font-size: smaller;
}

JS

var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    }),
    new ol.layer.Vector({
      source: new ol.source.Vector({
        url: 'data/geojson/countries.geojson',
        format: new ol.format.GeoJSON()
      })
    })
  ],
  target: 'map',
  
  view: new ol.View({
    center: ol.proj.fromLonLat([-63.5859487, 44.648618]), //halifax
    zoom: 14
  })
});

map.on("moveend", function() {
  var view = map.getView();
  var center = ol.proj.transform(view.getCenter(), 'EPSG:3857', 'EPSG:4326');
  var zoom = view.getZoom();
  var zoomInfo = 'Zoom level = ' + zoom;
    var rotation = view.getRotation();
  document.getElementById('center').innerHTML = center;
  document.getElementById('zoom').innerHTML = zoom;
    document.getElementById('rotation').innerHTML = rotation;


});

https://jsfiddle.net/chudnovskym/d9cjzb03/21/


Solution

  • You can use change events on the view

    map.getView().on(['change:center', 'change:resolution', 'change:rotation'], function() {
      var view = map.getView();
      var center = ol.proj.transform(view.getCenter(), 'EPSG:3857', 'EPSG:4326');
      var zoom = view.getZoom();
      var zoomInfo = 'Zoom level = ' + zoom;
      var rotation = view.getRotation();
      document.getElementById('center').innerHTML = center;
      document.getElementById('zoom').innerHTML = zoom;
      document.getElementById('rotation').innerHTML = rotation;
    });
    

    https://jsfiddle.net/nvtf26h0/