如何获得矩形中心和中间点之间的距离

时间:2017-02-07 12:55:55

标签: javascript google-maps

我有矩形边界,使用

map.getBounds();

现在我想计算矩形中心和较短中间点之间的距离(以米为单位)。

已经有一些代码:

var mapCenter = this.map.getCenter()
var mapBounds = this.map.getBounds();
var southEast = mapBounds.getSouthWest();
var middlePoint = ??;
var radius = google.maps.geometry.spherical.computeDistanceBetween(mapCenter, middlePoint);

但我不知道如何缩短距离(从中间点)中点。

enter image description here

1 个答案:

答案 0 :(得分:2)

边界“顶部”的纬度是边界的北纬度:mapBounds.getNorthEast().lat()。边界中心的经度是边界中心的经度mapBounds.getCenter().lng()

(如果您不知道哪一侧是“较短”的一侧,请计算两者并使用较短的值)

var mapCenter = map.getCenter()
var mapBounds = map.getBounds();
var southEast = mapBounds.getSouthWest();
var middlePoint = new google.maps.LatLng(mapBounds.getNorthEast().lat(), mapBounds.getCenter().lng());
var radius = google.maps.geometry.spherical.computeDistanceBetween(mapCenter, middlePoint);

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: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

  google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
    var mapCenter = map.getCenter()
    var mapBounds = map.getBounds();
    var rectangle = new google.maps.Rectangle({
      map: map,
      bounds: mapBounds
    });
    var southEast = mapBounds.getSouthWest();
    var middlePoint = new google.maps.LatLng(mapBounds.getNorthEast().lat(), mapBounds.getCenter().lng());
    var radius = google.maps.geometry.spherical.computeDistanceBetween(mapCenter, middlePoint);
    var circle = new google.maps.Circle({
      center: mapCenter,
      radius: radius,
      map: map
    });
    var marker = new google.maps.Marker({
      position: middlePoint,
      map: map
    });
    var line = new google.maps.Polyline({
      map: map,
      path: [mapCenter, middlePoint]
    });
    document.getElementById('info').innerHTML = radius.toFixed(2);
    map.setZoom(12);
  });
}
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="info"></div>
<div id="map_canvas"></div>