简体   繁体   English

在本地存储中存储多边形

[英]Storing Polygons in localStorage

When a user zooms into my map, I send the current bounding box to get the polygons from the database and set them in localStorage. 当用户放大我的地图时,我发送当前的边界框以从数据库中获取多边形并将其设置在localStorage中。 They are transferred as JSON so something like [{"polygons":{"features":[{"geometry":{"coordinates":[...]] (with actual coordinates of course). 它们以JSON格式传输,因此类似[{"polygons":{"features":[{"geometry":{"coordinates":[...]] (当然还有实际坐标)。

bounds = getBounds();
$.ajax({
    url: '/getPolygons',
    type: 'POST',
    data: JSON.stringify(bounds),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (data) {
        polyArray = JSON.parse(localStorage.getItem('polygons')) || [];
        polygons = data;
        polyArray.push(polygons);
        localStorage.setItem('polygons', JSON.stringify(polyArray));
    }
});

As the user further explores (pan, zoom) the map, the polygons keep on adding to the same localStorage key. 当用户进一步浏览(平移,缩放)地图时,多边形会继续添加到同一localStorage键中。 My question is, how do I load these polygons now that they are in the localStorage? 我的问题是, 既然这些多边形位于localStorage中那么如何加载它们? I want to reduce the number of requests sent to the database. 我想减少发送到数据库的请求的数量。 If certain polygons have already loaded on the map, I do not want to request for those polygons again from the database. 如果某些多边形已经在地图上加载,我不想再次从数据库中请求这些多边形。

I am able to set and get the polygons from localStorage, but the problem I have is with logic, which is as follows. 我可以从localStorage设置和获取多边形,但是逻辑上存在问题,如下所示。 This is the complete function. 这是完整的功能。

google.maps.event.addListener(map, 'idle', function () {
    if (localStorage.getItem('polygons')) {
        var data = JSON.parse(localStorage.getItem('polygons'));
        map.data.addGeoJson(data['polygons']);
    } else {
        bounds = getBounds();
        $.ajax({
            url: '/getPolygons',
            type: 'POST',
            data: JSON.stringify(bounds),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (data) {
                addPolygons(data);
                polyArray = JSON.parse(localStorage.getItem('polygons')) || [];
                polygons = data;
                polyArray.push(polygons);
                localStorage.setItem('polygons', JSON.stringify(polyArray));
            }
        });
    }
});

This the addPolygons function as used above: 上面使用的addPolygons函数:

function addPolygons(json) {
    data = json;

    if (typeof polygons !== 'undefined') {
        map.data.forEach(function(feature) {
            map.data.remove(feature);
        });
    }

    polygons = map.data.addGeoJson(data['polygons']);   
}

The bounding box is defined as follows: 边界框定义如下:

function getBounds() {
    var boundsNE = map.getBounds().getNorthEast();
    var boundsSW = map.getBounds().getSouthWest();
    var ne = [ boundsNE.lng(), boundsNE.lat() ];
    var nw = [ boundsSW.lng(), boundsNE.lat() ];
    var sw = [ boundsSW.lng(), boundsSW.lat() ];
    var se = [ boundsNE.lng(), boundsSW.lat() ];
    var ne = [ boundsNE.lng(), boundsNE.lat() ];
    var boundsArray = [ ne, nw, sw, se, ne ];
    return boundsArray;
}

Edit : It worked using map.data.addGeoJson(data['polygons']); 编辑 :它使用map.data.addGeoJson(data['polygons']); (see 3rd line in the IF statement I have setup). (请参阅我已设置的IF语句中的第三行)。 But now when I start panning the map, I don't see new polygons being requested from the database (the ones that don't exist on the map). 但是现在,当我开始平移地图时,我看不到数据库中正在请求新的多边形(地图上不存在的多边形)。

Edit v2 : One thing I am experimenting with is tracking the change in map center. 编辑v2 :我正在尝试的一件事是跟踪地图中心的变化。 If the map center changes by X number of value, then request new polygons. 如果地图中心改变X值,则请求新的多边形。 Hope to update with answer if I can get this working. 希望我能解决这个问题,并提供答案。

Edit v3 : This is what polyArray looks like after second fetch. 编辑v3 :这是第二次获取后polyArray外观。 Initial fetch is empty. 初始提取为空。 [Object] 0: Object polygons: Object features: Array[209] type: "FeatureCollection" __proto__: Object __proto__: Object 1: Object polygons: Object features: Array[205] type: "FeatureCollection" __proto__: Object __proto__: Object length: 2 __proto__: Array[0]

Make this google.maps.event.addListener(map, 'idle', function () a bounds_changed function instead. Suggestion based on Google documentation : 根据Google 文档的建议google.maps.event.addListener(map, 'idle', function ()将此google.maps.event.addListener(map, 'idle', function ()改为bounds_changed函数。

the Maps API fires these latter events independently, getBounds() may not report useful results until after the viewport has authoritatively changed. Maps API会独立触发这些事件,直到视口经过权威性更改后,getBounds()才可能报告有用的结果。 If you wish to getBounds() after such an event, be sure to listen to the bounds_changed event instead. 如果您希望在此类事件之后获取getBounds(),请确保改为监听bounds_changed事件。

"latter" events means the zoom_changed or center_changed which may not be the most effective approach. “后期”事件表示zoom_changedcenter_changed可能不是最有效的方法。

EDITED SNIPPET (with a second of timeout): 编辑的片段 (超时时间为一秒):

 var timeout; google.maps.event.addListener(map, 'bounds_changed', function() { window.clearTimeout(timeout); timeout = window.setTimeout(function() { if (localStorage.getItem('polygons')) { ... } else { bounds = getBounds(); ... } }); }, 1000); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM