![](/img/trans.png)
[英]How to convert Position and Zoom Level to LatLngBounds with Google Maps Javascript?
[英]Create latLngBounds based on zoom level and a center point
我有一個列表,其中列出了我需要在不移動地圖的情況下基於相對於地圖項的地圖邊界框運行操作的地圖項/多邊形。
為了進一步解釋我的問題,我可以舉一個例子,說明在移動地圖不是問題的情況下如何執行此操作:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.