Guide on extracting latitude and longitude geocode from a JSON response using the Google Maps API and storing them in variables with JavaScript

RETRIEVING GEO LOCATION VIA JSON https://maps.googleapis.com/maps/api/geocode/json?address=KOLKATA&key=API_KEY

{
       "results" : [
          {
             "address_components" : [
                {
                   "long_name" : "Kolkata",
                   "short_name" : "Kolkata",
                   "types" : [ "locality", "political" ]
                },
                {
                   "long_name" : "Kolkata",
                   "short_name" : "Kolkata",
                   "types" : [ "administrative_area_level_2", "political" ]
                },
                {
                   "long_name" : "West Bengal",
                   "short_name" : "WB",
                   "types" : [ "administrative_area_level_1", "political" ]
                },
                {
                   "long_name" : "India",
                   "short_name" : "IN",
                   "types" : [ "country", "political" ]
                }
             ],
             "formatted_address" : "Kolkata, West Bengal, India",
             "geometry" : {
                "bounds" : {
                   "northeast" : {
                      "lat" : 23.0078201,
                      "lng" : 88.5428696
                   },
                   "southwest" : {
                      "lat" : 22.3436288,
                      "lng" : 88.19430439999999
                   }
                },
                "location" : {
                   "lat" : 22.572646,
                   "lng" : 88.36389500000001
                },
                "location_type" : "APPROXIMATE",
                "viewport" : {
                   "northeast" : {
                      "lat" : 23.0078201,
                      "lng" : 88.5428696
                   },
                   "southwest" : {
                      "lat" : 22.3436288,
                      "lng" : 88.19430439999999
                   }
                }
             },
             "place_id" : "ChIJZ_YISduC-DkRvCxsj-Yw40M",
             "types" : [ "locality", "political" ]
          }
       ],
       "status" : "OK"
    }

JAVASCRIPT FUNCTION FOR RETRIEVING LATITUDE AND LONGITUDE

$(function() {
    $("#home_city_select").change(function() {
        //alert( $('option:selected', this).text() );
        var city = document.getElementById("home_city_select").value;
        var ltd;
        var lng;

        var jsonLtdLng="https://maps.googleapis.com/maps/api/geocode/json?address="+city+"&key=API_KEY";
        //alert(JSON.stringify(jsonLtdLng));
        //alert($.getJSON(jsonLtdLng));
        //alert($.getJSON(jsonLtdLng.lat));
        //alert($.getJSON(jsonLtdLng.results.geometry.location.lat));
        //alert($.getJSON(jsonLtdLng.results[0].geometry.location.lat));
        //alert($.getJSON(jsonLtdLng.results[0].geometry.location.lat()));
        alert(jsonLtdLng.results[0].geometry.location.lat());
    });
});

Attempting to WORKLIGHT Testing.

Unable to extract the latitude and longitude.

alert(JSON.stringify(jsonLtdLng));//shows complete address

alert($.getJSON(jsonLtdLng));//displays object Object

alert($.getJSON(jsonLtdLng.lat));//no output

alert($.getJSON(jsonLtdLng.results.geometry.location.lat));//no output

alert($.getJSON(jsonLtdLng.results[0].geometry.location.lat));//no output

alert($.getJSON(jsonLtdLng.results[0].geometry.location.lat()));//no output

alert(jsonLtdLng.results[0].geometry.location.lat());//no output

Answer №1

Your attempt to use $.getJSON did not produce the expected results

Consider trying this code instead:

$.getJSON(jsonLtdLng, function (data) {
  console.log(data.results[0].geometry.location.lat);
});

Answer №2

When working with JSON data in JavaScript, you have a few options for deserializing the information. One common method is using JSON.parse() to convert the JSON data into an object that JavaScript can work with. In the past, eval() was used for this purpose, but deserializing using JSON.parse() is now more widely accepted.

To see the JSON data in a readable format, you can use document.write(), but keep in mind that you will need to deserialize it first using JSON.parse(). On the other hand, JSON.stringify() is used for serializing data before transmitting it. The recipient would then need to deserialize it using JSON.parse() to work with it in JavaScript.

While write.document() can be useful for viewing information, using console.log() allows for easier inspection of object contents. Here's an example of how to work with JSON data:

// Assume apiData contains the JSON data from an API
var externalData = JSON.parse(apiData);

// Output will be [object object]
document.write(externalData);

// Output will be blank
document.write('      ');

// Output will display latitude value
document.write(externalData.results[0].geometry.location.lat);

// Use console.log() to view data in the console
console.log(externalData);

Hopefully, this explanation clarifies the process of deserializing JSON data and working with it in JavaScript.

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

The value of an AngularJS service is not being reflected in the view

I have implemented the stateProvider in my code, and I am facing an issue with updating the breadcrumbs in the header when the state changes. Instead of creating embedded views for each state, I have a service that shares an array of breadcrumbs containing ...

Creating a new URL using a JSON response in Node.js: A step-by-step guide

I am facing a query regarding the following code: The issue at hand is: How can I pass each line from response promiseGetCitiesData to promiseGetInformationDataPerCity. Is it possible to achieve this in a single async.each function? Currently, I have ...

Tips on inserting JS code into React component

I seem to be struggling with integrating my JS code into a React component. I attempted it, but unfortunately made a mess of things. Can anyone provide guidance on how to properly accomplish this? mycomponent.js import React from "react"; import Navbar ...

What is preventing me from accessing my session array in this.state.props from my mapStateToProps in React-Native Redux?

I am currently facing an issue with my Redux store setup. I am attempting to store an array of Session objects, where each Session object contains an array of Hand objects. However, when trying to access my store using `mapStateToProps`, none of the option ...

The ASP.NET MVC3 form collection registers as 0 when performing a jQuery ajax post

I'm currently developing a project on ASP.NET MVC3. My current challenge involves POSTing to a method that should return a set of data using the jQuery.ajax api. However, upon handling the request on the server, I noticed that the form collection&apo ...

Using ThreeJs to create interactive 3D objects with button-controlled movement

Currently, I'm diving into the world of Three.js and I have a fascinating project in mind. I want to create movement buttons that will control the position of a sphere object. Through some research, I found out that I can use the onclick function on b ...

How to integrate a JSON file to customize the style of a Google Map in

I've been attempting to apply a custom style to my Google Map using a JSON file, but I keep encountering an error. I've added the API key in AppDelegate.swift and also included the necessary keys in info.plist, yet the map continues to display th ...

Creating an AJAX URL in an external JavaScript file within a Django project

How can I verify if a student user's email exists in the database using keyup event in a registration form, and prevent form submission if the email is already registered? Below are the relevant files for achieving this: urls.py urlpatterns = [ ...

Utilizing the MVC ASP.NET framework, execute an Ajax form submission to obtain a JSON response

I am experiencing an issue with an Ajax form in MVC asp.net. After submitting the form and attempting to return a json result from the action, my Onsuccess function is not triggering and the view is not being displayed. Instead, only json objects are being ...

When transitioning between steps in Material UI React, the Vertical Stepper component should automatically scroll to the top of

When switching steps in Material UI's vertical stepper, it should automatically scroll to the beginning of the selected step. https://i.sstatic.net/fRX4E.png One potential solution is to utilize a ref to scroll to the stepper titles. More informatio ...

Restricting the drop zone for a jqueryui sortable element

In my HTML code, I have a list of elements inside a ul tag. The last li element is supposed to create new items. I used jqueryui's sortable() function to make the ul sortable, but excluded the last li element from being draggable. However, other items ...

Using JQuery to locate and substitute occurrences of HTML elements throughout my webpage

Looking for assistance with a JQuery search and replace task involving multiple instances of HTML within a specific DIV element on my webpage. Specifically, I need to change certain items in the textbox to a simpler display format. Here is a snippet of th ...

Mapping JSON to Java objects in Spring MVC causes a 400 error (Bad Request)

Whenever I try to submit the form, I encounter a 400 (Bad Request) error. My setup includes Jackson API jackson-core-asl-1.9.10.jar and jackson-mapper-asl-1.9.10.jar. Although I am able to receive JSON data, I am facing issues while submitting it. myjava ...

What is the syntax for implementing the 'slice' function in React?

While working on my React app, I encountered an issue when trying to extract the first 5 characters from a string using slice. The error message displayed was: TypeError: Cannot read property 'slice' of undefined I am utilizing a functional compo ...

How can we refresh the model in Angular.js from a section of the application that has not been 'angularized' yet?

UPDATE: Found a similar question at Call Angular JS from legacy code Working on adding a new feature to an existing application using Angular. Unable to do a complete rewrite, so the challenge is integrating Angular models with the rest of the app that di ...

Verify if there are any errors in the response

I'm working with a web API that responds with JSON, and have a shell script that uses curl to send requests and processes the JSON using jq. The structure of the responses is as follows: Error response: { "error": "error_message" } - a single struc ...

Manipulate paths in JS/JQuery by dynamically adding parameters with an indefinite number of values

My JavaScript script relies on an AJAX call that adds a parameter to an HTML request, but I've encountered two issues. I'm struggling to find a straightforward method to retrieve the pathname with parameters. With pure JavaScript, location.path ...

Please optimize this method to decrease its Cognitive Complexity from 21 to the maximum allowed limit of 15. What are some strategies for refactoring and simplifying the

How can I simplify this code to reduce its complexity? Sonarqube is flagging the error---> Refactor this method to reduce its Cognitive Complexity from 21 to the allowed 15. this.deviceDetails = this.data && {...this.data.deviceInfo} || {}; if (th ...

Does the use of 'window.location.replace' in Chrome cause a session to be destroyed in PHP when redirecting to a specified page?

Apologies if the question seems a bit convoluted, but let me explain the scenario. Here is an example of an Ajax function I am working with: $.ajax({ url:"../controllers/xx_register.php", type:"POST", data:send, success: function(resp ...

Is there a way to transmit a div using Node.js?

Scenario: I am developing a web application that allows users to draw on a canvas, save the drawing as an image, and share it with others using Node.js. Current Progress: Drawing functionality (real-time updates on both clients). Saving the canvas as a ...