只知道两个点绘制矩形

时间:2016-02-24 16:17:14

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

我试图编写一个围绕两点画一个矩形的程序。离开Google Maps example,我想在宾州车站(40.7506,73.9939)和市政厅(40.7127,74.0059)周围绘制一个矩形。基本上,我想模仿这两个地方的裁剪图像:

enter image description here

此图像的边框为矩形。我遇到麻烦的部分是建立一个,因为我只知道上面提到的两点。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

要在Penn Station(40.7506,73.9939)和City Hall(40.7127,74.0059)周围绘制一个矩形,请将这两个坐标添加到空边界对象,然后将其用作{{3}的bounds选项}}

// Penn Station (40.7506, 73.9939) 
// City Hall (40.7127, 74.0059)
var bounds = new google.maps.LatLngBounds();
var pennStation = new google.maps.LatLng(40.7506, -73.9939);
bounds.extend(pennStation);
var cityHall = new google.maps.LatLng(40.7127, -74.0059);
bounds.extend(cityHall);
var rectangle = new google.maps.Rectangle({
  map: map,
  bounds: bounds
});

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  // Penn Station (40.7506, 73.9939) 
  // City Hall (40.7127, 74.0059)
  var bounds = new google.maps.LatLngBounds();
  var pennStation = new google.maps.LatLng(40.7506, -73.9939);
  bounds.extend(pennStation);
  var cityHall = new google.maps.LatLng(40.7127, -74.0059);
  bounds.extend(cityHall);
  map.fitBounds(bounds);
  var rectangle = new google.maps.Rectangle({
    map: map,
    bounds: bounds
  });
}
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"></script>
<div id="map_canvas"></div>