如何通过单击按钮控件将地图平移到左侧

时间:2018-01-03 21:47:51

标签: google-maps-api-3

请您查看this demo并告诉我如何通过点击#pan按钮在地图左侧添加平滑的动画效果?



var map;
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -34.397, lng: 150.644},
    zoom: 8
  });
}

$("#pan").on("click", function(){
    //map.pan
});

 * element that contains the map. */
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="pan">Pan to Left</button>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

在我对问题的回答中http://www.geocodezip.com/scripts/PanControl.jsGoogle maps custom control always appears below the default controls,下面的代码是点击平移控件时平移地图的代码:

/** @param {PanDirection} direction */
PanControl.prototype.pan = function(direction) {
    var panDistance = 50;
    if (direction == PanDirection.UP || direction == PanDirection.DOWN) {
        panDistance = Math.round(this.map.getDiv().offsetHeight / 2);
        this.map.panBy(0, direction == PanDirection.DOWN ? panDistance : -1 * panDistance);
    }
    else {
        panDistance = Math.round(this.map.getDiv().offsetWidth / 2);
        this.map.panBy(direction == PanDirection.RIGHT ? panDistance : -1 * panDistance, 0);
    }
}

按钮单击侦听器功能中带有“pan left”代码的代码段

var map;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: -34.397,
      lng: 150.644
    },
    zoom: 8
  });
}

$("#pan").on("click", function() {
  var panDistance = Math.round(map.getDiv().offsetWidth / 2);
  map.panBy(-1 * panDistance, 0);
});
#map {
  height: 100%;
}

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="pan">Pan to Left</button>
<div id="map"></div>