How to detect Map's Zoom In / Out?

2550
1
04-22-2021 04:37 AM
ShaningYu
Frequent Contributor

In my App, I need a function to detect map's zoom in/out.  Referring to

https://community.esri.com/t5/arcgis-api-for-javascript/detect-change-in-zoom-when-complete/m-p/5406...

I added the following code in the script:

$('#viewDiv').mousedown(function() {
context._mapClick(context);
});
$("#viewDiv").on('wheel', function() {
context._mapClick(context);
});

......

_mapClick: function (context) {
  debugger;
  context.esriModules.watchUtils.watch(context.view, "zoom", onZoomChange);

  function onZoomChange(newValue, oldValue, propertyName, target) {
     debugger;
     if (!target.updating && oldValue > newValue) {
         contx.crimeTable.clearSelection();
     }

  }
},

In Chrome's debugging, the _mapClick: function () does fire, but after   debugging;  the function onZoomChange() is not implemented.   What's wrong in my coding?  Thanks if you can help. 

0 Kudos
1 Reply
UndralBatsukh
Esri Regular Contributor

Hi there, 

You do not need to set up the watchUtils whenever you click or use mouse wheel on the viewDiv. You can set your logic to watch the zoom property as soon as the view is initialized and you set this only once. 

The following logic will be very chatty. Your onZoomChange will trigger many times until the view is zoomed into its final level. 

context.esriModules.watchUtils.watch(context.view, "zoom", onZoomChange);

 

If you want to run the code when the view is done zooming then you can do the following. Instead of watching view's zoom property, watch the view's updating property. The view.updating will become true while user is zooming in or out. Then its value will change to false once the zoom ends. Now you can get the view's new zoom level and run your logic.

 const view = new MapView({
  container: "viewDiv",
  map: map,
  zoom: 4,
  center: [15, 65] // longitude, latitude
});

// Watch view's updating event
watchUtils.watch(view, "updating", onZoomChange);
function onZoomChange(newValue, oldValue, propertyName, target) {
 if (!view.updating){
  // View just finished updating. Get the new zoom value from the view
    console.log("view.stationary", view.stationary, "view.updating", view.updating, view.zoom)
 }
}

 

Hope this helps,

-Undral

0 Kudos