【问题标题】:How do you find the 4 corners of a Google Map V3 when the map is rotated?旋转地图时如何找到 Google Map V3 的 4 个角?
【发布时间】:2015-11-12 22:21:58
【问题描述】:

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

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

(甚至还有post about this 5 years ago。)

但我在网上任何地方找到的所有答案都假设地图指向正北,这意味着“东北”实际上意味着“右上角”。

但是如果地图旋转了会发生什么?我是否必须根据地图的方向使用三角函数来确定其他两个角?或者 Google 是否会为我提供包含我的视口中的区域的实际东北和西南坐标,即使这意味着生成的矩形的部分超出了旋转地图的范围?

【问题讨论】:

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


    【解决方案1】:

    或者 Google 会给我实际的东北和西南坐标吗? 包含我视口中的内容的区域

    没错,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>

    【讨论】:

    • 太棒了! (不知道为什么我不认为这样做)。这非常有用,谢谢
    猜你喜欢
    • 1970-01-01
    • 2012-11-03
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 2013-07-10
    相关资源
    最近更新 更多