Google地图矩形可编辑:如何锁定(固定)编辑的高度

时间:2014-09-05 11:53:34

标签: google-maps height

我有一张谷歌地图,里面有一个可编辑,可移动和可调整大小的矩形等。 我正在寻找的方法是锁定矩形的给定高度,所以只有 宽度可以改变。

1 个答案:

答案 0 :(得分:3)

您可以使用JavaScript中的bounds_changed事件阻止矩形调整高度。

这是一个有效的jsfiddle:http://jsfiddle.net/h7ee4368/

Rectangle api reference:https://developers.google.com/maps/documentation/javascript/reference?hl=de#Rectangle

JavaScript src:

var rectangle;
var originalBounds;
var map;

function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(44.5452, -78.5389),
        zoom: 9
    };
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    var bounds = new google.maps.LatLngBounds(
        new google.maps.LatLng(44.490, -78.649),
        new google.maps.LatLng(44.599, -78.443)
    );

    originalBounds = bounds;

    // Define the rectangle and set its editable property to true.
    rectangle = new google.maps.Rectangle({
        bounds: bounds,
        editable: true,
        draggable: true
    });

    rectangle.setMap(map);

    // Add an event listener on the rectangle.
    google.maps.event.addListener(rectangle, 'bounds_changed', boundsChangedCb);
}

var skipBoundsChangedCb = false;
function boundsChangedCb(event) {
    if(skipBoundsChangedCb) return;

    var ne = rectangle.getBounds().getNorthEast();
    var sw = rectangle.getBounds().getSouthWest();

    var origNe = originalBounds.getNorthEast();
    var origSw = originalBounds.getSouthWest();

    //avoid recursion
    skipBoundsChangedCb = true;

    rectangle.setBounds(new google.maps.LatLngBounds(
        new google.maps.LatLng(ne.lat() - origNe.lat() + origSw.lat(), sw.lng()),
        ne        
    ));

    skipBoundsChangedCb = false;

    origNe = ne;
    origSw = sw;
}

google.maps.event.addDomListener(window, 'load', initialize);