Retrieve coordinates, specifically latitude and longitude, by utilizing AJAX and JSONP

Trying to obtain latitude and longitude using AJAX JSONP.
Here is the code snippet:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
$(document).ready(function(){
var region = "Rajkot,Jamnagar";
            var cn ="IN";
            var lat;
            var lng;
            var array = region.split(',');
            var lat = new Array(), lng = new Array();

var totalLength = array.length;
var count = 0;
            for(var item in array)
            {
            $.ajax({

                url: "http://services.gisgraphy.com//geocoding/geocode?address="+array[item]+"&country="+cn+"&format=json",
                              async: false,
                              dataType:'jsonp',
                              success: function(data){  
                                count++;
                    lat.push(data.result[0].lat);
                    lng.push(data.result[0].lng);
                    if (count == totalLength) {
                var commaSeperatedLat = lat.toString();
                localStorage.setItem("newlat",commaSeperatedLat); 
                var commaSeperatedLong = lng.toString();
                console.log(commaSeperatedLat);
                }
                }
                });
                }

            // Function to retrieve latitude and longitude when button is clicked
                function getAllData()
                {
                var moodle_groups_id = (localStorage.getItem("newlat"));
                    alert(moodle_groups_id);
                }
                });
</script>
<body>
<input type="button" value="Retrieve Data" onclick="getAllData()"></input>
</body>

Successfully fetching all latitude and longitude data.
Now, looking to access these variables on button click event using Local Storage methods.
Please assist me in resolving this issue.
Thank you.

Answer №1

If you want to successfully call the function all(), make sure it is defined outside of the $(document).ready(function() block.

<script>
$(document).ready(function(){
var region = "Rajkot,Jamnagar";
            var cn ="IN";
            var lat;
            var lng;
            var array = region.split(',');
            var lat = new Array(), lng = new Array();

var totalLength = array.length;
var count = 0;
            for(var item in array)
            {
            $.ajax({

                url: "http://services.gisgraphy.com//geocoding/geocode?address="+array[item]+"&country="+cn+"&format=json",
                              async: false,
                              dataType:'jsonp',
                              success: function(data){  
                                count++;
                    lat.push(data.result[0].lat);
                    lng.push(data.result[0].lng);
                    if (count == totalLength) {
                var commaSeperatedLat = lat.toString();
                localStorage.setItem("newlat",commaSeperatedLat);
                var commaSeperatedLong = lng.toString();
                console.log(commaSeperatedLat);
                }
                }
                });
                }

                });
function all()
{
var moodle_groups_id = (localStorage.getItem("newlat"));

    alert(moodle_groups_id);
}
</script>

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

Can I send JavaScript variables to a different .PHP file by using Ajax?

I need to transfer javascript variables from one file where calculations are performed to another file containing a mySQL query. The second file is loaded using a .load() function without refreshing or redirecting to it. Is it possible to achieve this wit ...

Choose the appropriate data type for the class variable (for example, fArr = Uint32Array)

const functionArray: Function = Uint32Array; new fArr(5); The code snippet above is functioning properly. However, TypeScript is throwing a TS2351 error: "This expression is not constructable. Type 'Function' has no construct signatures". I wo ...

Delete Entries in MongoDB Collection According to Unique User Pairs

I have a collection of messages stored in MongoDB and I need to keep only the latest 500 records for each pair of users. Users are identified by their sentBy and sentTo attributes. /* 1 */ { "_id" : ObjectId("5f1c1b00c62e9b9aafbe1d6c&quo ...

I want to display events from my database table on their corresponding dates using JavaScript and jQuery. How can I achieve this?

Using the FullCalendar plugin, I attempted to achieve a specific functionality, but unfortunately fell short of my goal. Below is the snippet of my scripting code: $('#calendar').fullCalendar({ //theme: true, header: { ...

Display a single unique value in the dropdown menu when there are duplicate options

Hey there, I'm currently working on retrieving printer information based on their location. If I have multiple printers at the same location, I would like to only display that location once in the dropdown menu. I am aware that this can be resolved at ...

Tips on transferring information from localstorage to a backend server using jquery

Need help sending a jsonwebtoken from localstorage using jQuery to a node server. I've attempted it this way, but it's not working. Here is the client-side code for handling requests: $(function () { // Code snippet here }); After authentic ...

Conceal a column within a nested HTML table

I am facing a challenge with a nested table column structure: My goal is to hide specific columns based on their index within the table. Can someone explain the concept behind achieving this? I am unsure of how to get started on this task. <table clas ...

Angular: The application has encountered an error due to an undefined property reading issue, resulting in a type error

Here is the code for the company.ts file: company.ts file - List item export class Company{ gstNo:number; contactNumber:number; contactName:string; phoneNo:number; address:string; companyName:string; } import { Injectable } ...

Delete JavaScript data array

I've been working on a project involving data manipulation in a JSON file. Although I can successfully add new names to the file, I'm facing an issue when trying to delete them. Instead of deleting, the inputted name gets added to the file again ...

Gathering user information through Javascript to dynamically populate an HTML document

Looking to utilize JavaScript to extract the value entered in a search bar and then display it in HTML. function pullValue() { var search = document.getElementById("search-bar") } How can the extracted data be inserted into the following: <h3 class ...

Javascript and Codeigniter interaction: Using conditionals with Ajax

I am having trouble understanding this code snippet. I am currently studying Ajax and came across this piece of code that automatically inserts data. However, I am unsure about the line if(result=='12') then trigger ajax. What does the number 12 ...

Unclear when notifying div content

After creating a PHP page, I encountered an issue while trying to select the inner text of a div and alert it with jQuery. Instead of getting the expected result, it keeps alerting "undefined." What could possibly be causing this? Here is the code snippet ...

Is the Wrapper created by the combination of React, JavaScript Arrow functions, and Classes

I stumbled upon a website at: After implementing the solution successfully, I found myself puzzled by the javascript code. There was a snippet in the AnimatedWrapper.js class that caught my attention: const AnimatedWrapper = WrappedComponent => class ...

Grabbing the mouse in Firefox

Are there any alternatives to the .setCapture(); and .releaseCapture() functions in Firefox that do not involve using jQuery? (The client prefers not to use it) ...

Tips on preventing the occurrence of double encoding in raw JSON output from a view

I am encountering a JavaScript error while attempting to parse JSON data obtained from my controller: Uncaught SyntaxError: Unexpected token & in JSON at position 1 at JSON.parse () at stores:76 This is the code I use to serialize my list of elem ...

Enable clickable elements positioned behind an iframe

I am currently working on integrating a third-party chatbot into my web application using an iframe in ASP.NET MVC. Like with any chatbot, a button is provided to start a chat (located on the right-hand side below the screen). When this button is clicked, ...

Execute a function within a different function once the ajax call has been completed

There's an issue with the timing of my function that runs inside another function. It seems like sometimes the ajax call to the server isn't completed before the function is called. function obtainPlans(row, user, id, type) { $.get( "/ ...

Restricting the Vue for-loop results to display only the current item in use

Currently, I am utilizing a for-loop to retrieve all of my posts, followed by employing a partial to obtain a list of all the usersThatUpvoted on that post. <div v-for="p in posts" style="padding: 16px"> <div> &l ...

Understanding the relationship between csv and json array formats, along with the process of converting them into a json array using Node.js

Greetings! I have been searching for quite some time and have not been able to find the desired result. I am unsure of what a CSV file would look like with the following JSON array: [ { email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email_ ...

When the page initially loads, the block appears on top of the upper block and remains in place after the page is refreshed

Upon initial loading, the block appears on top of another block but remains fixed upon page refresh. The same issue occurs in the mobile version of the site and occasionally displays correctly. The website is built on WordPress and optimized using Page Spe ...