Sending a JavaScript array to a different webpage

Is there a way to pass an array and its contents to another page for use?

I am utilizing an array to store coordinates for drawing a polyline on a Google map. The array works correctly on one page, but when attempting to call the array to draw the polyline points on a different map, it seems that the array is empty and no polyline points are drawn.

I tried using localStorage with JSON stringify, but faced several issues where Google Maps wouldn't accept the values because they contained unexpected values or were in an unrecognized format.

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

This code constructs the array from the provided coordinates, and the function is invoked within onSuccess of the watchPosition function as follows:

storeLatLng(lat, lon);

Subsequently, I aim to utilize the array values within the following function:

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

This function is called onLoad of another page.

Answer №1

Utilizing Session Storage or Local Storage to Pass Data: (simple example)

Data transfer between pages can be achieved using session storage. Another option is local storage, which operates in a similar manner but persists even after the session is closed.

To use local storage instead of session storage, simply replace sessionStorage with localStorage.

Array for Storage:

var testArray = ['test'];

Storing the Array:

$('#store').on('click', function(){
    sessionStorage.setItem('myArray', testArray);
});

Retrieving the Array:

$('#get').on('click', function(){
    var myArray = sessionStorage.getItem('myArray');
    alert(myArray);
});

Clearing Session Storage:

$('#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>

Verifying Stored Sessions in Chrome:

If storing data as strings, remember to convert it back to JSON format:

var mydata = localStorage.getItem("GoogleLatLng");
var myObject = JSON.parse(mydata);

DEMO:

http://jsfiddle.net/mdktpmw2/

Compatibility with Older Versions of Internet Explorer:

Additional Resources:

Answer №2

If you're looking to transfer data to another page, there are plenty of helpful resources available to guide you through the process. You can check out tutorials or refer to previous Stack Overflow answers that address similar queries:

how can i send the data to another page without appending it in url?

passing form data to another HTML page

To efficiently handle the transferred data, consider fetching it within the onLoad event of the subsequent page.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Top recommendation for showcasing a numerical figure with precision to two decimal points

Within my function, I am tasked with returning a string that includes a decimal number. If the number is whole, I simply return it as is along with additional strings. However, if it's not whole, I include the number along with the string up to 2 deci ...

Retain the contents of the shopping cart even when the page is refreshed

For a course project, I am recreating a grocery store website and need assistance on how to retain the shopping cart values even after refreshing the webpage. Please inform me if more information is required... <button type="button" id= ...

Utilizing React JS to dynamically adjust the z-index upon clicking a component

My goal is to create a functionality where clicking on a box will move it to the top, with the previous box now underneath. For a better understanding, please refer to the following code snippet. https://codesandbox.io/s/optimistic-payne-4644yf?file=/src/ ...

Trigger JavaScript when a specific division is loaded within a Rails 4 application

Is there a way to trigger a JavaScript function when a specific div with a certain class is loaded within my Rails 4 application? <div class="myClass"> hello world </div I am looking for a solution to execute some JavaScript code only when t ...

Facing a few hiccups in JavaScript or CSS code, but getting closer to making it work

Here is the code I currently have with HTML, CSS, and JavaScript. Everything is working correctly except for one small issue that I can't seem to resolve. I am new to JavaScript and believe that JavaScript is necessary to fix this problem. If not, the ...

Is it possible for the req.url path in expressjs to represent a different URL?

Recently, I discovered some suspicious requests being sent to my node-express server. In response, I created a middleware to record the request URLs. After logging these requests, I noticed that most of them started with '/', but there were also ...

Fulfill a pledge after a function has been run five times

I'm struggling to understand why my promise is not working as expected and how to resolve the issue. Here is the code snippet: let count = 0; function onLoad(){ count++ console.log(count); return new Promise((resolve) => { ...

Mastering JavaScript closures and scope management: Techniques for successfully passing an external scope variable into a callback function as an argument

Here is the code snippet I am working with: im.size((function(a, b) { console.log(b); console.log(im); })(im)); The Object "im" has a function called size, which requires a callback function. It passes the parameters a and b to this callback function ...

Set all form fields to ng-touched programmatically when the form is submitted

HTML: <div class="form-group" ng-class="{ 'has-error' : form.firstName.$invalid && form.firstName.$touched }"> <label for="firstName" class="control-label"> First Name </label> <input t ...

When using the jQuery ajax function to validate a form, it is important to note that the $_POST variables

I have an HTML form along with a jQuery function for form validation. After submitting the form values to my PHP files, I notice that the $_POST variable is not being set. What could be causing this issue? <form id="signup" class="dialog-form" action= ...

What is causing this JavaScript code to function properly in the browser console but fail in Selenium's JavascriptExecutor?

Recently, I've been incorporating the JavascriptExecutor class in my Selenium code to take advantage of JavaScript's efficient DOM manipulation abilities. I rely on XPaths to pinpoint elements, and this line of code showcases how JavaScript deals ...

The jquery function is not functioning properly within a javascript code block, however it performs perfectly when placed outside

In my php page, I have included jQuery and a script.js file. When I insert this function into my php file, it runs successfully: <script> $('#scoreboard-overview').load('getusers.php?q=<?php echo $NewString; ?>').fadeIn ...

Steps for concealing a specific field in StrongLoop's outcome

Currently, I am working on a project using strongloop to develop a web service for user login. While my code is functioning properly and producing the desired output, the issue lies in the fact that it does not hide the password. The result I am receiving ...

Creating a customized bundle with Bootstrap using the Rollup tool

In the official Bootstrap 5 documentation, it mentions that we can import pre-compiled js files from bootstrap/js/dist and create a custom bundle using tools like Webpack or rollup. https://getbootstrap.com/docs/5.0/getting-started/javascript/#individual- ...

Retrieve parameters from functions and convert them into coherent statements

As I delved into the world of THREE.js, I experimented with various geometries. However, manually writing out each geometry became tedious due to the vast array of options available. For example, creating a simple cube required these lines of code: var m ...

Retrieving the chosen value when there is a change in the select tag

Building a shop and almost done, but struggling with allowing customers to change product quantities in the cart and update prices dynamically. I've created a select-tag with 10 options for choosing quantities. I'd like users to be able to click ...

Utilize JavaScript and regular expressions to extract the query string

My URL will look like this: "Hospital" OR "Office" OR "Facility" I'm trying to extract everything after 'k=', excluding 'k=' itself. The regular expression I have so far is sort of working, but it captures everything with ' ...

How about using take(1) in conjunction with an Observable<boolean>?

After going through this insightful article, I came across the following implementation of a CanActivate check to determine whether the user can navigate to the home page: canActivate(): Observable<boolean> { return this.authQuery.isLoggedIn$.pipe( ...

The design of Foundation's 4 form dropdown is not displaying correctly on Internet Explorer versions 8 and below

During the development of a website using Foundation 4 framework, I encountered an issue with form dropdowns not displaying correctly on Internet Explorer 8 and older versions. Instead of using Foundation's javascript rendering, they appear as the def ...

When executing my code to delete a file and remove it from the database, an error message pops up in the console

I've been working on implementing a delete image feature on my website. Although my code successfully deletes the file from the images folder and removes the corresponding record from the database, I encounter an error in the console that prevents me ...