[英]Localstorage not working in openlayers geolocation
這里是我從openlayers3示例頁面提取的一個小演示,您可以在下面看到一些示例代碼:
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map',
controls: ol.control.defaults({
attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
view: view
});
現在我想使用localStorage,因此我將代碼修改如下:
if(!localStorage.layer) {
localStorage.layer = new ol.layer.Tile({ source: new ol.source.OSM() })
}
// creating the map
var map = new ol.Map({
layers: localStorage.layer ? [ localStorage.layer ] : [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map',
controls: ol.control.defaults({
attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
view: view
});
現在由於某種原因這不起作用,現在如果我進行一些調試,則會得到以下結果
現在,如果我在控制台中鍵入以下內容:
new ol.layer.Tile({ source: new ol.source.OSM() })
我懂了
G {ca: false, ka: undefined, fb: Kc, pd: G, Ma: null…}
但是如果我這樣做
localStorage.layer = new ol.layer.Tile({ source: new ol.source.OSM() })
然后輸入:
localStorage.layer
我懂了
"[object Object]"
那么為什么localStorage.layer
不等於new ol.layer.Tile({ source: new ol.source.OSM() })
? 我相信這就是導致地圖無法加載的原因。 當然,如果我刪除localStorage代碼,則地理位置地圖就可以正常工作。 那么為什么localStorage.layer
不等於new ol.layer.Tile({ source: new ol.source.OSM() })
?
Tile
返回某種對象,而localStorage.getItem(layerStr)
值為字符串。 要從字符串中提取存儲的對象,可以執行JSON.parse(localStorage.getItem(layerStr))
,其中layerStr = JSON.stringify(layer)
。 這是一個非常人為的示例,用於存儲和從localStorage中檢索對象:
var person = {first: 'Tenali', last: 'Raman'};
localStorage.setItem('person', JSON.stringify(person));
JSON.parse(localStorage.getItem('person')); // => {first: 'Tenali', ...}
但是不幸的是,即使如此,您仍然無法獲得想要的答案,這表明:
var storedTile = JSON.parse(localStorage.getItem(layer));
var storedTile2 = JSON.parse(localStorage.getItem(layer));
storedTile == storedTile2; // => false
storedTile === storedTile2; // => false; follows from the line above
通常,對象是通過標識而不是值進行比較的。 有關兩個javascript對象之間的相等關系,請查看此答案 。
localStorage
對象只能存儲字符串,請參閱doc 。
localStorage.layer = new ol.layer.Tile({ source: new ol.source.OSM() })
當您執行localStorage.layer = new ol.layer.Tile({ source: new ol.source.OSM() })
,您會存儲(new ol.layer.Tile({ source: new ol.source.OSM() })).toString()
因此localStorage.layer = "[object Object]"
,顯然不能等於您的圖層對象。
您根本無法將對象存儲在本地存儲中,只能存儲字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.