谷歌地图坐标视图



我有一个常规的地图,我可以放大/缩小,移动到北,南,东,西。每次我做任何动作时,我都想获得一个新的地图矩形视图坐标,例如:lat from: x1, lat to: x2, lg from: y1, lg to: y2。

这是我如何初始化地图在我的网站:

function initMap() {
    var latLng = new google.maps.LatLng(49.47805, -123.84716);    
    map = new google.maps.Map(document.getElementById('map'), {
        zoom: 12,
        center: latLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
}

你能告诉我如何才能做到这一点吗?

当中心或边界发生变化时向地图添加监听器,获取地图的边界并显示四个角的坐标

google.maps.event.addListener(map,'zoom_changed', displayBounds);
google.maps.event.addListener(map,'center_changed', displayBounds);
function displayBounds() {
    var bounds = map.getBounds();
    var north = bounds.getNorthEast().lat();
    var east = bounds.getNorthEast().lng();
    var south = bounds.getSouthWest().lat();
    var west = bounds.getSouthWest().lng();
    var northEast = new google.maps.LatLng(north,east);
    var northWest = new google.maps.LatLng(north,west);
    var southEast = new google.maps.LatLng(south,east);
    var southWest = new google.maps.LatLng(south,west);
    // NorthEast, NorthWest, SouthEast, SouthWest
    document.getElementById('coords').innerHTML = "NorthEast: "+northEast.toUrlValue(6)+"<br>NorthWest:" + northWest.toUrlValue(6) + "<br>SouthEast: "+southEast.toUrlValue(6) + "<br>SouthWest:"+southWest.toUrlValue(6)+"<br>";
}

代码片段:

function initMap() {
  var latLng = new google.maps.LatLng(49.47805, -123.84716);
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: latLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  google.maps.event.addListener(map, 'zoom_changed', displayBounds);
  google.maps.event.addListener(map, 'center_changed', displayBounds);
  google.maps.event.addListenerOnce(map, 'idle', displayBounds);
}
function displayBounds() {
  var bounds = map.getBounds();
  var north = bounds.getNorthEast().lat();
  var east = bounds.getNorthEast().lng();
  var south = bounds.getSouthWest().lat();
  var west = bounds.getSouthWest().lng();
  var northEast = new google.maps.LatLng(north, east);
  var northWest = new google.maps.LatLng(north, west);
  var southEast = new google.maps.LatLng(south, east);
  var southWest = new google.maps.LatLng(south, west);
  // NorthEast, NorthWest, SouthEast, SouthWest
  document.getElementById('coords').innerHTML = "NorthEast: " + northEast.toUrlValue(6) + "<br>NorthWest:" + northWest.toUrlValue(6) + "<br>SouthEast: " + southEast.toUrlValue(6) + "<br>SouthWest:" + southWest.toUrlValue(6) + "<br>";
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="coords"></div>
<div id="map"></div>

最新更新