基于缩放级别和中心点创建latlnbounds

Create latLngBounds based on zoom level and a center point

本文关键字:中心点 创建 latlnbounds 于缩放 缩放      更新时间:2023-09-26

我有一个特征/多边形列表,我需要基于相对于特征的地图边界框运行操作,而不移动地图。

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

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

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

下面的代码段对我有用,以防其他人也有同样的问题:

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);