[英]Pass javascript array to another page
我想知道是否有一种方法将数组及其内容传递给另一个页面供使用。
我正在使用数组来存储用于将折线绘制到谷歌地图上的坐标。 数组在一个页面上工作正常,但是当我尝试调用数组在另一个地图上绘制折线点时,数据显示已清空并且没有绘制折线点。
我曾尝试将localStorage与JSON stringify一起使用,但遇到了很多问题,谷歌地图不会接受以太值,因为它们包含了不期望的值,或者因为它根本无法识别格式。
var googleLatLng = [],
latlngs = [];
function storeLatLng( lat, lng ) {
googleLatLng.push(new google.maps.LatLng(lat, lng));
latlngs.push([lat, lng]);
// setcoords = JSON.stringify(googleLatLng);
// localStorage.setItem('GoogleLatLng', setcoords);
// console.log(localStorage.getItem("GoogleLatLng"));
console.log(googleLatLng);
}
此代码从给定坐标构建数组,该函数从watchPosition函数的onSuccess内部调用
storeLatLng(lat, lon);
然后我想在以下函数中使用数组值
function finishedWalk() {
// storedCoords = localStorage.getItem('GoogleLatLng');
// if(storedCoords) storedCoords = JSON.parse(storedCoords);
navigator.geolocation.getCurrentPosition(onFinishedSuccess, onFinishedError);
}
function onFinishedSuccess(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
storeLatLng(latitude, longitude);
var mapOptions = {
zoom: 17,
center: coords,
mapTypeControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//create the map, and place it in the HTML map div
map = new google.maps.Map(document.getElementById("mapPlaceholder"), mapOptions);
if (googleLatLng.length > 0) {
var path = new google.maps.Polyline({
path: googleLatLng,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 5
});
path.setMap(map);
}
}
这被称为onLoad的另一页
使用会话存储或本地存储传递数据:(基本示例)
您可以使用会话存储将数据从一个页面传递到下一个页面。 或者,您也可以使用类似方式的本地存储。 会话结束时,不会清除本地存储。
对于本地存储,只需将sessionStorage
替换为localStorage
。
要存储的数组:
var testArray = ['test'];
存储阵列:
$('#store').on('click', function(){
sessionStorage.setItem('myArray', testArray);
});
获取阵列:
$('#get').on('click', function(){
var myArray = sessionStorage.getItem('myArray');
alert(myArray);
});
清除会话存储:
$('#clear').on('click', function(){
sessionStorage.clear();
});
HTML:
<a href="javascript:void(0);" id="store">Store Array</a>
<a href="javascript:void(0);" id="get">Get Array</a>
<a href="javascript:void(0);" id="clear">Clear</a>
检查以查看chrome中存储的会话:
如果存储字符串化数据,请确保转换回JSON:
var mydata = localStorage.getItem("GoogleLatLng");
var myObject = JSON.parse(mydata);
DEMO:
支持旧版Internet Explorer:
一些资源:
您需要将数据发布到其他页面。 有大量的教程可以引导您完成它,包括已经回答的一些Stack答案:
你可能想要在下一页的onLoad中获取数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.