我按照示例here创建了一系列放置在网页上的Google地图上的标记。
在过去的几个小时中,我在开放式网络上以及在SO上都找到了很多示例,但我没有尝试过。
我需要:
1)将Google Maps标记对象的Javascript数组保存在隐藏的输入字段中
2)然后检索隐藏输入字段的“值”并将其转换回Marker对象数组,以便我可以从地图中删除这些标记
这是我的代码,其中一些基于上面的Google Maps示例:
theMarkersArray = new Array();
for(var i = 0; i < 5; i++)
{
marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
shape: shape,
title: "aMarker",
zIndex: 1000});
theMarkersArray.push(marker);
}
theMarkersArrayField = document.getElementById('markersArray');
// I'm using Firefox v28.0, the following line of code halts code executing,
// I'm thinking that 'JSON.stringify()' is not defined for FF 28.0..?)
//theMarkersArrayField.value = JSON.stringify(theMarkersArray);
// this executes, but I don't think it's saving the array of Marker objects
// correctly
theMarkersArrayField.value = theMarkersArray;
alert("the theMarkersArray is: "+ theMarkersArray);
当我使用alert()显示MarkersArrayField.value的内容时,它看起来像这样:
[object Object],[object Object],[object Object],[object Object],[object Object]
当我尝试使用eval()或JSON.parse()将MarkersArrayField.value转换回Javascript数组时,都失败了。
var theMarkersArrayField = document.getElementById('markersArray');
// DOES NOT WORK
//var theMarkersArray = JSON.parse(theMarkersArrayField.value);
// THIS doesn't work either
//var theMarkersArray = eval(theMarkersArrayField.value);
// IS NOT AN ARRAY OF 'Marker' objects, just a text string it seems...?
var theMarkersArray = document.getElementById('markersArray').value;
// RETURNS '79' INSTEAD OF 5 (only 5 markers were stored in the array, not 79) --
// 79 is the count of characters in:
// [object Object],[object Object],[object Object],[object Object],[object Object]
var numMarkers = theMarkersArray.length;
我需要将一个Marker对象数组存储在一个数组中,然后将该数组保存在页面上的隐藏字段中,然后稍后从该隐藏字段中检索该数组,将其转换回Marker对象数组-我缺少什么?
最佳答案
function addMarker(location) {
for(var i = 0; i < 5; i++) {
var marker = new google.maps.Marker({
position: location,
map: map
});
// of course if you need only the position you can avoid looping and just get
// marker.position.k and marker.position.A , this example dimostrate
// how to iterate and get data from the object and build a custom array...
for (var o in marker) {
if (typeof marker[o] === 'object') {
if (o === 'position') {
var position = marker[o];
markers.push({'k' : position.k, 'A' : position.A});
}
}
}
}
document.getElementById('markersArray').value = JSON.stringify(markers);
}
关于javascript - 无法将Google Maps标记对象保存到隐藏的html字段中的数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22773789/