Reputation: 1993
I have got rectangle bounds, used
map.getBounds();
Now I would like to calculate distance (in meters) between rectangle center and shorter middle point.
Already have some code:
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);
But I don't know how to get shorter distance (from center) middle point.
Upvotes: 0
Views: 545
Reputation: 161334
The latitude of the "top" of the bounds is the northern latitude of the bounds: mapBounds.getNorthEast().lat()
. The longitude of the center of the bounds is the longitude of the center of the bounds mapBounds.getCenter().lng()
(if you don't know which side is the "shorter" one, calculate both and use the shorter value)
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);
code snippet:
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>
Upvotes: 2