Google Maps Rectangle editable: how to lock (fixed) height from editing

独自空忆成欢 提交于 2019-12-10 14:18:24

问题


I have a Google Map, in it a rectangle which is editable, moveable and resizable etc. What I am looking for is a way to lock the given height of the rectangle, so only the width can be changed.


回答1:


You can prevent the rectangle from resizing the height with the bounds_changed Event in JavaScript.

Here is a working 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);


来源:https://stackoverflow.com/questions/25685320/google-maps-rectangle-editable-how-to-lock-fixed-height-from-editing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!