lundi 31 mars 2014

can't save Google maps marker objects to array in hidden html field


Vote count:

0




I followed the example here to create an array of the markers that I put on my Google map on my web page.


I've looked for the past few hours at a lot of example both on the open web and here on SO and nothing I've tried works.


I need to:


1) save a Javascript array of Google Maps marker objects in a hidden input field


2) then retrieve the 'value' of the hidden input field and convert that back to the array of Marker objects so that I can remove these markers from the map


Here's my code, some is based on the Google Maps sample above:



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);


When I display the contents of theMarkersArrayField.value using alert(), it looks like this:



[object Object],[object Object],[object Object],[object Object],[object Object]


and when I try to convert theMarkersArrayField.value back into a Javascript array using either eval() or JSON.parse(), both fail.



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;


I need to store an array of Marker objects in an array then save that array in a hidden field on the page, then later retrieve that from the hidden field, convert it back to an array of Marker objects -- what am I missing?



asked 1 min ago






Aucun commentaire:

Enregistrer un commentaire