我的地图上有一个可拖动的矩形。如果用户将矩形拖成正方形,我知道两边是相等的。如何确定一侧与另一侧相比的长度?我可以使用 getBounds 并且可能会解决一些问题,但我认为有一种更简单的方法。我不需要实际的数字,我只需要知道相对于彼此。例如,矩形的宽度是高度的两倍,或者是宽度的三倍。
问问题
487 次
1 回答
2
假设您有一个可拖动的矩形,您可以在用户完成拖动时获得它的边界。然后你可以使用几何库来获得它的边长。就像是:
<!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>
参考:https ://duncan99.wordpress.com/2013/10/19/google-maps-size/
于 2016-04-11T18:43:04.020 回答