如何在OpenLayers中相互独立地移动两个图层?

时间:2013-01-20 09:12:09

标签: javascript maps gis openlayers

是否可以在OpenLayers中创建两个图层(其中一个是半透明的)并单独移动它们?如果是这样,怎么样? 我想让用户选择要移动的图层,或者如果不可能,请通过我自己的JavaScript代码移动一个图层,而另一个图层由用户控制。

如果这很重要,两者都会被预渲染像素图层。

1 个答案:

答案 0 :(得分:2)

这是我提出的解决方案。它不漂亮,但它适用于我的目的。

非常欢迎更好的替代品......

/**
* @requires OpenLayers/Layer/TMS.js
*/
MyLayer = OpenLayers.Class(OpenLayers.Layer.TMS, {
    latShift: 0.0,
    latShiftPx: 0,

    setMap: function(map) {
        OpenLayers.Layer.TMS.prototype.setMap.apply(this, arguments);
        map.events.register("moveend", this, this.mapMoveEvent)
    },
    // This is the function you will want to modify for your needs
    mapMoveEvent: function(event) {
        var resolution = this.map.getResolution();
        var center = this.map.getCenter();

        // This is some calculation I use, replace it whatever you like:
        var h = center.clone().transform(projmerc, proj4326);
        var elliptical = EllipticalMercator.fromLonLat(h.lon, h.lat);
        var myCenter = new OpenLayers.LonLat(elliptical.x, elliptical.y);

        this.latShift = myCenter.lat - center.lat;
        this.latShiftPx = Math.round(this.latShift/resolution);

        this.div.style.top = this.latShiftPx + "px";
    },
    moveTo: function(bounds, zoomChanged, dragging) {
        bounds = bounds.add(0, this.latShift);
        OpenLayers.Layer.TMS.prototype.moveTo.apply(this, [bounds, zoomChanged, dragging]);
    },
    // mostly copied and pasted from Grid.js ...
    moveGriddedTiles: function() {
        var buffer = this.buffer + 1;
        while(true) {
            var tlTile = this.grid[0][0];
            var tlViewPort = {
                x: tlTile.position.x +
                    this.map.layerContainerOriginPx.x,
                y: tlTile.position.y +
                    this.map.layerContainerOriginPx.y + this.latShiftPx // ... except this line
            };
            var ratio = this.getServerResolution() / this.map.getResolution();
            var tileSize = {
                w: Math.round(this.tileSize.w * ratio),
                h: Math.round(this.tileSize.h * ratio)
            };
            if (tlViewPort.x > -tileSize.w * (buffer - 1)) {
                this.shiftColumn(true, tileSize);
            } else if (tlViewPort.x < -tileSize.w * buffer) {
                this.shiftColumn(false, tileSize);
            } else if (tlViewPort.y > -tileSize.h * (buffer - 1)) {
                this.shiftRow(true, tileSize);
            } else if (tlViewPort.y < -tileSize.h * buffer) {
                this.shiftRow(false, tileSize);
            } else {
                break;
            }
        }
    },
    CLASS_NAME: "MyLayer"
});

请注意,这仅适用于OpenLayers 2.13或更新版