How to know if the user change zoom (Google Maps V3)

那年仲夏 提交于 2020-07-11 04:23:08

问题


I'm developing an app with Google Maps and Angularjs. I have this code to control whether the zoom is changed

google.maps.event.addListener(map, 'zoom_changed', function(){

  });

The question is, I need to execute this event only when the user changes the zoom. I have in my code a fitBounds() that change the zoom as well.

var latlngbounds = new google.maps.LatLngBounds();
  for (var i = 0; i < latlng.length; i++) {
    latlngbounds.extend(latlng[i]);
  }

  map.fitBounds(latlngbounds);

Is there an option to distinguish between user action and not?


回答1:


The current accepted solution may not properly solve this question in a general case. Go to the interactive demo for map UI events in the Google Maps API docs. Note that if you position your cursor on the map and scroll with your mouse's scroll wheel, none of the mouse or drag events are fired because the mouse remains stationary.

The current solution assumes that no programmatic map updates will occur after the mouseover event, which may be true for the original poster's application but might not be true in a more general application.

I propose the alternate solution below.

First, wherever you programmatically update the map in your code, set a custom property on the map—we'll call ours systemZoomChange—that indicates the change was initiated programmatically.

var latlngbounds = new google.maps.LatLngBounds();
for (var i = 0; i < latlng.length; i++) {
  latlngbounds.extend(latlng[i]);
}

map.systemZoomChange = true
map.fitBounds(latlngbounds);

Then on any event listeners, add a check for the custom systemZoomChange property, and reset it if flagged, to avoid acting on system events.

map.addListener('zoom_changed', function () {
  if (map.systemZoomChange) {
    map.systemZoomChange = false  // Reset the flag for a system-initiated event
  } else {
    // Handle the user-initiated event
  }
});



回答2:


Ok, I found the way

google.maps.event.addListenerOnce(map, 'mousemove', function(){

    google.maps.event.addListener(map, 'zoom_changed', function(){

    });

  });

First, it detects if the mouse moves and then if the zoom if changed and works properly!



来源:https://stackoverflow.com/questions/38442051/how-to-know-if-the-user-change-zoom-google-maps-v3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!