tyr*_*ter 5 javascript google-maps bounds
我使用的是Google Maps v3 API.我目前正在请求每次更改视口时(通过缩放或移动地图)获取新数据并丢弃我的旧数据.这很好用,但现在我想缓存数据,以便每次视口更改时都不需要获取数据.Google Maps API通过其东北和西南坐标定义视口,该坐标由纬度和经度组成.它们存储在名为LatLngBounds的对象中.
我想出了两种可以做到这一点的方法:
如果有人能想出更好的方法来做到这一点,请随意提出新的方法.
我的问题是,在更好的性能/内存使用和整体速度方面哪一个会更好?它们都是类似的算法,所以它真的重要吗?
此外,现在两种算法都依赖于基于旧视口划分新视口.划分新视口的算法是什么样的?(假设我实现了我的第二个算法)
var prevBounds = [ /* Array of previously seen bounds */ ];
var newViewport = map.getBounds(); // New Viewport to divide up
var sw = newViewport.getSouthWest();
var swlat = sw.lat();
var swlng = sw.lng();
var ne = newViewport.getNorthEast();
var nelat = ne.lat();
var nelng = ne.lng();
// newViewport.intersects(bounds)
// Returns true if this bounds shares any points with this bounds.
Run Code Online (Sandbox Code Playgroud)
我可能会考虑或多或少地按照 Google 提供地图图块的方式进行此操作 - 不是立即加载整个视口的数据,而是将整个地图划分为方形区域(尽管可能比 Google 的 256x256 图块更大的区域),确定哪些区域位于当前视口中,并加载这些区域的数据。当用户平移和缩放地图时,检查视口边界以查看新区域是否已进入框架,并根据需要加载它们。粗略的伪代码:
var cache = {}
function onViewportChange() {
// get new bounds
var bounds = map.getBounds();
// identify all the areas in the bounds
var areas = getAreas(bounds);
areas.forEach(function(area) {
if (area.key in cache) {
// do nothing, or load items from cache
} else {
// load new data, storing the key (and maybe the data)
// to the cache
}
})
}
function getAreas(bounds) {
/* given a set of bounds, return an array of objects like:
[
{
x: 1,
y: 2,
zoom: 4,
key: "4-1,2",
bounds: b // lat/lon bounds of this area
},
...
]
*/
}
Run Code Online (Sandbox Code Playgroud)
(有关如何实现的想法,请参阅地图坐标的 Google 解释和此示例getAreas。)
这样做的吸引力在于,您要检索的区域要简单得多,并且检查您是否已经加载给定区域的数据变得非常容易 - 每个区域可以有一个简单的唯一键,可能是由x/y/缩放坐标,并且在加载每个新区域时,您将密钥(或者可能是密钥和数据 - 这取决于您是从地图中删除旧数据还是只是将其留在那里)保存到某个缓存中目的。然后,当视口移动到新区域时,您所要做的就是检查缓存中是否存在该键。
缺点是您可能经常在当前视口之外加载数据,并且您向服务器发送的请求可能比您建议的实现更多。如果您在不同的缩放级别提供不同的数据,则此方法可能效果最佳 - 否则您可能会在尝试选择在不同缩放下运行良好的单一大小的缓存区域时陷入困境。
| 归档时间: |
|
| 查看次数: |
1255 次 |
| 最近记录: |