根据缩放级别和中心点创建latLngBounds

时间:2015-09-26 15:55:34

标签: javascript leaflet gis

我有一个功能/多边形列表,我需要根据相对于要素的地图边界框运行操作,而不移动地图。

为了进一步解释我的问题,我可以举例说明如果移动地图不是一个问题,我该如何做到这一点:

features.forEach(function (feature) {
    var bbox,
        ne,
        sw,
        fBounds,
        zoom,
        mBounds;

    bbox = feature.geometry.bbox;
    sw = L.latLng(bbox[1], bbox[0]);
    ne = L.latLng(bbox[3], bbox[2]);
    fBounds = L.latLngBounds(sw, ne);
    map.fitBounds(bounds);
    mBounds = map.getBounds();
    zoom = map.getZoom();
    //Execute operation based on mBounds and zoom
}    

我已经测试了很多,这是我对工作代码片段最接近的事情:

        var self = this,
            bbox,
            sw,
            ne,
            bounds,
            zoom,
            swPoint,
            nePoint,
            center,
            factor,
            dw,
            dh,
            cpx;

        bbox = feature.geometry.bbox;
        sw = L.latLng(bbox[1], bbox[0]);
        ne = L.latLng(bbox[3], bbox[2]);
        bounds = L.latLngBounds(sw, ne);
        zoom = self.map.getBoundsZoom(bounds, false); //maxZoom?
        swPoint = self.map.project(bounds.getSouthWest(), zoom),
        nePoint = self.map.project(bounds.getNorthEast(), zoom),
        center = self.map.unproject(swPoint.add(nePoint).divideBy(2), zoom);

        factor = self.map.options.crs.scale(zoom) / 8388608;
        dw = self.map.getSize().x / 2*factor;
        dh = self.map.getSize().y / 2*factor;
        cpx = self.map.options.crs.latLngToPoint(center, zoom);            

        return {
            ne: self.map.options.crs.pointToLatLng(L.point(cpx.x + dw, cpx.y - dh, false), zoom),
            sw: self.map.options.crs.pointToLatLng(L.point(cpx.x - dw, cpx.y + dh, false), zoom),
            center: center,
            zoom: zoom
        }

        //Execute operation based on returned object, repeat for every feature

这个'工作'但它没有给出与第一个代码片段相同的结果(即结果是错误的)。

1 个答案:

答案 0 :(得分:0)

以下代码段为我工作,万一其他人应该有同样的问题:

var self = this,
    bbox,
    sw,
    ne,
    bounds,
    zoom,
    center;

bbox = feature.geometry.bbox;
sw = L.latLng(bbox[1], bbox[0]);
ne = L.latLng(bbox[3], bbox[2]);
bounds = L.latLngBounds(sw, ne);
zoom = self.map.getBoundsZoom(bounds, false); //maxZoom?
sw = self.map.project(bounds.getSouthWest(), zoom),
ne = self.map.project(bounds.getNorthEast(), zoom),
center = self.map.unproject(sw.add(ne).divideBy(2), zoom);

bounds = self.map.getPixelBounds(center, zoom),
sw = self.map.unproject(b2.getBottomLeft()),
ne = self.map.unproject(b2.getTopRight());

return new L.LatLngBounds(sw, ne);