I have a draggable rectangle on my map. If the user drags the rectangle into a square shape, I know both sides are equal. How can I determine the length of one side compared to the other? I can use getBounds and probably work something out with that but I assume there is an easier way. I don't need the actual number, I only need to know relative to each other. For example the rectangle is twice as wide as it is high, or three times as high as it is wide.
Assuming you have a draggable rectangle, you could get its bounds when the user's finished dragging it. Then you could use the Geometry library to get the length of its sides. Something like:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 90% }
body { height: 100%; margin: 0; padding: 0 }
#map { height: 100% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
function initialize() {
var myOptions = {
zoom: 14,
center: {lat: 51.476706, lng: 0},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var rectangle = new google.maps.Rectangle({
bounds: new google.maps.LatLngBounds(
{lat: 51.4721885614119, lng: -0.029311180114746094},
{lat: 51.48122299123414, lng: 0.029311180114746094}
),
editable: true,
map: map
});
rectangle.addListener('bounds_changed', function() {
var bounds = this.getBounds();
var proportion = getSideProportions(bounds);
$('#proportion').text('The width is ' + proportion + ' times the height');
});
}
/* Imagine a rectangle with these corners:
* A--B
* | |
* C--D
* PointB = the North-East corner,
* PointC = the South-West corner
*/
function getSideProportions(bounds) {
var PointA, PointB, PointC, NorthEastLatitude, SouthWestLongitude, horizontalDistance, verticalDistance, proportion;
// get the coordinates for the NE and SW corners
PointB = bounds.getNorthEast();
PointC = bounds.getSouthWest();
// from that, figure out the latitudes and the longitudes
NorthEastLatitude = PointB.lat();
SouthWestLongitude = PointC.lng();
PointA = new google.maps.LatLng(NorthEastLatitude, SouthWestLongitude);
horizontalDistance = getDistance(PointA, PointB);
verticalDistance = getDistance(PointA, PointC);
proportion = horizontalDistance / verticalDistance;
return Math.round(proportion * 10) / 10;
}
function getDistance(point1, point2) {
return google.maps.geometry.spherical.computeDistanceBetween(point1, point2);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
<div id="proportion"></div>
</body>
</html>
Ref: https://duncan99.wordpress.com/2013/10/19/google-maps-size/