当地图旋转时,你如何找到谷歌地图V3的4个角

How do you find the 4 corners of a Google Map V3 when the map is rotated?

本文关键字:谷歌地图 V3 4个角 何找 旋转 地图      更新时间:2023-09-26

Google maps V3 API在地图上有一个getBounds方法,该方法返回视口的东北角和西南角。理论上,我可以通过使用相对点的经纬度来计算西北角和东南角,即

NE=(lat=37.5,lng=-97.5)
SW=(lat=37.0,lng=-96)
…因此
NW=(纬度=37.5,lng=-96)
SE=(lat=37.0,lng=-97.5)

(5年前甚至有一篇关于这个的帖子。)

但我在网上找到的所有答案都假设地图指向正北,意思是"东北"实际上意味着"右上角"。

但是如果旋转贴图会发生什么?我必须根据地图的方向使用trig来计算其他两个角吗?或者,谷歌会给我一个区域的实际东北和西南坐标,该区域包含我视口中的内容,即使这意味着生成的矩形的部分超出了旋转地图的边界?

或者谷歌给了我实际的东北和西南坐标包含我的视口中内容的区域

没错,getBounds函数返回基于当前视口的东北角和西南角。下面的示例对其进行了说明,特别是它绘制了包含当前视口的大小的矩形:

var map;
var area;
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 45.518, lng: -122.672},
    zoom: 18,
    mapTypeId: google.maps.MapTypeId.HYBRID,
    //heading: 0,
    //tilt: 45
  });
  google.maps.event.addListenerOnce(map, 'idle', function(){
       drawBounds(map);  
  });
  
}
function drawBounds(map)
{
    var bounds = map.getBounds();
    var areaBounds = {
         north: bounds.getNorthEast().lat(),
         south: bounds.getSouthWest().lat(),
         east: bounds.getNorthEast().lng(),
         west: bounds.getSouthWest().lng()
    };
    
    area = new google.maps.Rectangle({
       strokeColor: '#FF0000',
       strokeOpacity: 0.8,
       strokeWeight: 2,
       fillColor: '#FF0000',
       fillOpacity: 0.35,
       map: map,
       bounds:areaBounds
  });
  console.log(areaBounds);
}
function rotate() {
   var heading = map.getHeading() || 0;
   map.setHeading(heading + 90);
   area.setMap(null);
   drawBounds(map);
}
html, body {
   height: 100%;
   margin: 0;
   padding: 0;
}
#map {
   height: 100%;
}
#floating-panel {
   position: absolute;
   top: 10px;
   left: 25%;
   z-index: 5;
   background-color: #fff;
   padding: 5px;
   border: 1px solid #999;
   text-align: center;
   font-family: 'Roboto','sans-serif';
   line-height: 30px;
   padding-left: 10px;
}
<div id="floating-panel"><input type="button" value="Rotate" onclick="rotate();"></div>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>