使用尺寸而非 LatLon 将矩形添加到 Google 地图

Add rectangle to Google Maps using dimensions not LatLon

我在网页上有一张地图,我希望能够添加一个特定大小的矩形。目前做的如下。

var rectangle = new google.maps.Rectangle({
        strokeColor: '#FF0000',
        fillColor: '#FF0000',
        fillOpacity: 0.35,
        map: map,
        bounds: {
            north: 33.685,
            south: 33.671,
            east: -116.224,
            west: -116.251
        }
    });

是否可以使用尺寸而不是坐标向 Google 地图添加矩形?

例如,假设我想在地图上画一个 250 英尺高 x 600 英尺宽的矩形?

谢谢

您需要根据尺寸(和定位点,中心或已知顶点)计算坐标。您可以使用几何库来做到这一点。

// 250ft high x 600ft wide
// 1 ft = 0.3048 meters
var rectBounds = new google.maps.LatLngBounds(
  new google.maps.LatLng(
    google.maps.geometry.spherical.computeOffset(map.getCenter(), 250*0.3048, 180).lat(), // south
    google.maps.geometry.spherical.computeOffset(map.getCenter(), 600*0.3048, 270).lng()), // west
  map.getCenter() /* NE */);
var rectangle = new google.maps.Rectangle({
map: map,
bounds: rectBounds
});

proof of concept fiddle

代码片段:

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 16,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  // 250ft high x 600ft wide
  // 1 ft = 0.3048 meters
  var rectBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(
      google.maps.geometry.spherical.computeOffset(map.getCenter(), 250 * 0.3048, 180).lat(), // south
      google.maps.geometry.spherical.computeOffset(map.getCenter(), 600 * 0.3048, 270).lng()), // west
    map.getCenter() /* NE */ );
  var rectangle = new google.maps.Rectangle({
    map: map,
    bounds: rectBounds
  });

}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map_canvas"></div>