Storing the location information in an array results in the output of [object, Object]

I've been searching everywhere for a solution to this problem, but it seems elusive.

My current code saves data to the browser's local storage as jSon, and it works perfectly. However, I need to incorporate geolocation into each piece of saved data. While I can display coordinates in a div, I'm struggling to save that same data to the jSon file.

The code snippet looks like this:

$(document).ready(function(){
  var selected_index = -1;
  var theArray = []; 
  var operation = "A"; 
  if(localStorage.getItem("ID") != null) { 

}
//***********************************************************************

  $("#saveButton").click(function(){
      if(operation == "A" && $("#input1").val() != ""){ 

    //Now attempting to obtain geolocation

    var x = document.getElementById("DivId"); //works when targeted to a div
    alert(x);                                 //This returns [object 
                                                HTMLDivElement]

    function getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
      x = "Geolocation is not supported by this browser.";
      }
    }
    function showPosition(position) {
    x = "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
    }


  getLocation();

       var object = {
              value1 : $("#input1").val(),
              value2 : $("#input2").val(),
              value3 : $("#input3").val(),
              value4 : $("#input4").val(),
              value5 : $("#input5").val(),
              time : Date(),
              place: x          //This is where the location is saved
                                //but returns [object, Object]


          }

          theArray.push(object); 
          localStorage.setItem("ID",JSON.stringify(TheArray));
      }
      console.log(x); //for testing, returns: <div id="DivID" 
                        style="display: none;"></div>

      $("#input1").val("");
      $("#input2").val("");
      $("#input3").val("");
      $("#input4").val("");
      $("#input5").val("");

      $("#input1").focus();

  });

It's clear that I'm storing the location data incorrectly. What would be the correct approach? Thank you in advance for any assistance!

Answer №1

The issue lies in the asynchronous nature of your requests.

When you utilize getPosition(), it triggers getCurrentPosition(showPosition). The problem arises here as this function operates asynchronously. Once called, it runs in the background while your code continues to execute without pausing. Therefore, when you define the object variable, showPosition has not been invoked yet, resulting in x holding its initial value, which is a HTMLDivElement.

To rectify this, consider defining the object variable within the showPosition callback and saving it from there. This precaution is necessary since the method's invocation time is uncertain. Initially, the user must grant permission for the page to access their current location. If permission is denied or overlooked, the callback may never be triggered. While errors can be handled (via the error callback of getCurrentPosition), there is a possibility that no response will ever be received.

Furthermore, other issues exist in the code where x is assigned to a DIV element and later reassigned as a string. Presumably, you intend to append that string as a child node of the DIV, which can be achieved as follows:

x.appendChild(document.createTextNode('Geolocation is not supported in this browser'));

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

Is there a way to display a secondary header once the page is scrolled down 60 pixels?

.nav-header2{ background: purple; display: flex; justify-content: center; align-items: center; } .header2-container{ width: 68vw; height: 60px; padding: 0 2vh; border: 1px solid red; ...

What is the correct way to display or hide a button based on my specific situation?

Creating a 'show more' button for my app has presented me with a challenge. I am using a directive to handle actions when the user clicks on the read more button: (function(window, angular) { var app = angular.module('myApp'); ...

Obtain the existing text from the <select runat="server"> element

Similar Question: Retrieve Text Selection with Runat=“Server” 1: HTML <div id="dialog"> <select id="Select1"> <option>1</option> <option>2</option> <option>3 ...

Serve JSON Data Instead of Rendering a View in C# (MVC)

My goal is to utilize AJAX to receive a JSON array from the controller. In php, you can simply return a string rather than a view, allowing for code like this: $array = array( "Hello" => "hi", "Whatsup" => sup ); return json_encode($array); Howeve ...

Extracting Referring Page URLs Using jQuery

Is there a way to extract URLs from an referring page using jQuery? The URLs are embedded inside <a> elements, similar to this HTML structure: <a href="http://localhost/sr19repairables/vehicles/repairables/2011-chrysler-town-country-touring-miniv ...

The split function in JavaScript is exhibiting some unusual behavior

There is something wrong with my code challenge1 = () => { var data = fs.readFileSync('santa21.txt', 'utf8'); data = data.toString(); dataSplit = data.split(' ') console.log(dataSplit); }; challenge1(); The result of the ...

Difference between JSON field being set to null and the field not being present in the

Is there a way to distinguish between a JSON field being set to null versus the field not being present when unmarshalled into a struct using golang? Both scenarios result in the value in the struct being nil, but I need to determine if the field originall ...

Upon initial execution, a Nextjs error occurs: Unable to locate the module 'caniuse-lite/data/features/css-unicode-bidi'

Encountered an error while starting my nextjs project, here's the issue Error - ./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[2].oneOf[8].use[1]!./node_modules/next/dist/build/webpack/loaders/postcss-loader/s ...

React is unable to retrieve information from an array

Greetings! I am currently in the process of developing a chess game and I am encountering an issue with obtaining information about each square in the console. Specifically, when trying to access squares.ver within a switch case scenario, the console out ...

Fundamental R: Iterating through a 3D array to multiply its elements

I'm dealing with two 3-D arrays, labeled as A and B, each having dimensions of 2 x 3 x 3. Below are examples to illustrate the structure of these arrays, which will aid in understanding how I intend to perform multiplication. A1 A2 A3 ...

Patience is key as we await the arrival of the loaded data before making a return in AngularFire 0

I am working on a form that should only be submitted if the user provides a valid access key ($scope.access_key) - and each key can only be used once. Within my controller, I have the following method: $scope.verifyAccess = function() { var ref = new ...

Refine your search by focusing on select characteristics of an item

Is there a way to filter tasks in a table using only specific attributes provided in the table? Currently, when I enter a search term in the search bar, tasks are displayed even if they have attributes that match the input but are not displayed in the na ...

What could be causing the hidden div to disappear after a button click in asp.net?

I am having an issue where a hidden div is not staying visible after clicking the login button. I want the div to remain visible on the page until another action is taken, but it disappears right after the login click event. Here is my button code: <a ...

What is the best way to display only li elements that possess a specific class utilizing javascript / jquery?

I have a bunch of li's: <ul> <li class="one"></li> <li class="one"></li> <li class="two"></li> </ul> and I want to display only the ones with the class "one" I attempted something like thi ...

How to use JSON.NET to serialize an object containing nested dictionaries

I'm struggling to serialize a JSON object, specifically the Item class into JSON class Item { public Dictionary<string, object> components = new Dictionary<string, object> { }; public string mixins { get; set; } public string ...

When attempting to instantiate a list from JSON in Angular, the type '{}' is lacking the following properties compared to type 'Datos[]'

I'm encountering issues when trying to incorporate JSON data into my Angular application. My Process: Importing the JSON file into a variable: import _data from '../../../assets/data.json'; Following the advice from responses in this t ...

Input field for change detection

I've been struggling to find a solution to capture the input from Html.TextAreaFor. After trying several options, I found that using a change function only works upon exiting, and employing a keypress event has its drawbacks: it triggers before text ...

Explaining the way jQuery data() eliminates circular references

After reading an explanation about the benefits and implementation process, I still have a question - how exactly does it eliminate the circular reference?. Can you explain how the circular reference is broken? $(div1).data('item', div2); $(div ...

Troubleshooting problems with jQuery Chosen plugin post-AJAX request

I'm encountering an issue with the plugin called jquery-chosen not applying to a control that is reconstructed by an ajax call. Despite exploring other suggestions, I have yet to find a solution that works. The versions of jquery and jquery-chosen be ...

Revamp your handles using the power of jQuery rotatable!

Greetings! I am currently utilizing a minified plugin created by godswearhats in my project. To activate the plugin, I simply call the following function: $('#em_1').rotatable(); Here is an excerpt of my HTML code: <div class="draggable par ...