Google Maps Api - 不要在缩放时更改地图中心

时间:2017-07-21 19:35:00

标签: javascript google-maps google-maps-api-3

是否可以在放大/缩小事件中保留相同的地图中心?无论是使用滚轮,双击还是使用缩放控件,它都应该表现相同。

我注意到当使用滚轮放大/缩小时,地图上的鼠标指针位置有偏差,我没有在文档上找到任何选项,但是覆盖这种偏差是理想的。

here is a simple fiddle我如何初始化我的地图。

var map = new google.maps.Map(document.getElementById("map_div"), {
    center: new google.maps.LatLng(33.808678, -117.918921),
    zoom: 15,
    disableDefaultUI: true
  });

1 个答案:

答案 0 :(得分:2)

按照@ Adam对评论的建议,我禁用了滚轮缩放,加上实例化地图时的双击缩放,并添加了事件监听器来处理这些事件与我自己的实现。

这是working fiddle,代码解释为:

/*
 * declare map as a global variable
 */
var map;
/*
 * use google maps api built-in mechanism to attach dom events
 */
google.maps.event.addDomListener(window, "load", function() {
  var myMap = document.getElementById("map_div");
  /*
   * create map
   */
  var map = new google.maps.Map(myMap, {
    center: new google.maps.LatLng(33.808678, -117.918921),
    zoom: 15,
    disableDefaultUI: true,
    scrollwheel: false,
    disableDoubleClickZoom: true
  });
    //function that will handle the wheelEvent
  function wheelEvent(event) {
    var e = window.event || e; // old IE support
    var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail))); //to know whether it was wheel up or down
    map.setZoom(map.getZoom() + delta);
  }

  function zoomIn() {
    map.setZoom(map.getZoom() + 1);
  }

  //add a normal event listener on the map container
  myMap.addEventListener('mousewheel', wheelEvent, true);
  myMap.addEventListener('DOMMouseScroll', wheelEvent, true);

  //same with the double click
  myMap.addEventListener('dblclick', zoomIn, true);

  //add center changed listener for testing
  google.maps.event.addListener(map, 'center_changed', function() {
    console.log("this is what i'm trying to avoid");
  });
});