What is the method for extracting latitude and longitude values individually from JSON data?

Upon receiving the JSON response from the Google Maps API stored in a variable named 'obj', I noticed that alerting obj.name returns "Pancakes on the Rocks". To access the icon, I can use obj.icon. However, I am struggling to retrieve separate values for latitude (lat) and longitude (lng). When I alert obj.geometry.location, it displays as (-33.87054,151.198815) together. What is the best way to extract these values individually? Your suggestions are greatly appreciated. Thank you.

{
"html_attributions" : [],
"results" : [
  {
     "geometry" : {
        "location" : {
           "lat" : -33.87054,
           "lng" : 151.198815
        }
     },
     "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
     "id" : "c71365287e7606bd21a3311d21fda087830b7813",
     "name" : "Pancakes on the Rocks",
     "opening_hours" : {
        "open_now" : true
     },
     "photos" : [
      ...


function createMarkers(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {

    for (var i = 0; i < results.length; i++) {
    createResultMarker(results[i]);
    }
  } 
}



function createResultMarker(obj) {

  alert('title: ' + obj.name);  // Displays correct name.
  alert(obj.geometry.location);
  alert(obj.geometry.location.lat);

  distance = getDistanceFromLatLonInKm(init_lat, init_lng, obj.geometry.location.lat, obj.geometry.location.lng);

}

Answer №1

To retrieve the latitude of an object, utilize obj.geometry.location.lat(), and for longitude, use obj.geometry.lng(); both of which are functions.

The JSON data you posted is not being directly utilized; instead, you are working with the google.maps.places service, which yields google.maps.LatLng objects.

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

Accessing Google Feed API to retrieve media thumbnails

I am currently utilizing the Google Feed API to extract a thumbnail from an RSS feed ("media:thumbnail") The media:thumbnail element in the RSS feed is structured as follows: <media:thumbnail url="http://anyurl.com/thumbnailname.jpg" width="150" heigh ...

Opening a modal in React Material UI from an autocomplete component results in losing focus

My current challenge involves utilizing the material-ui library to create an autocomplete feature where each item is clickable and opens a modal window. The basic structure looks like this: const ModalBtn = () => { ... return ( <> ...

Tips for implementing a waiting period during an ajax request using jQuery

My current task involves calling a URL to generate a token and then opening another page on the same site once the token is generated. The issue I'm facing is that the window generating the token closes quickly, making it difficult for me to authentic ...

The Jquery flot plugin is failing to plot the graph accurately based on the specified date

I am currently working on plotting a graph using the jquery flot plugin with JSON data. Here is what I need to do: Upon page load, make an AJAX call to receive JSON data from the server. From the received JSON, add 'x' and & ...

A helpful C# tool for verifying JSON strings containing anonymous types

Looking to determine the presence and value of an anonymous object within a JSON string. If the object exists, return its value; if not, return a default value. Need to repeat this process for multiple instances of anonymous objects. The current code is f ...

Decoding intricate JSON structures in Kotlin

I need help with deserializing the JSON below into a specific structure: { "participants": { "0": { "layout": "layout1" } }, "layouts": { "layout1": { ...

jQuery selector unable to locate the specified class in the table row

After receiving an array of strings as a response from an SQL query, I am using JavaScript to dynamically add this data as rows to an HTML table: loadUsers: function() { . . . function displayUsersOnTable(response) { for(var i = ...

Troubles Encountered in Converting Date and Time to JSON Format

I am currently facing an issue where I need to convert a list<T> into JSON data and then bind it to Jqgrid. However, the problem I am encountering is that the list collection includes one column with DateTime values. Upon inspecting the resultant J ...

Utilize the onClick Event to Trigger Function with an Array in ReactJS

Every time I attempt to pass an array as a value to a function by clicking on a div, I encounter the error below: Uncaught Invariant Violation: Expected onClick listener to be a function, instead got a value of object type. If passing an array to a fun ...

What is the method for determining if an NSNumber is null?

NSDictionary *regionDict = (NSDictionary *) region; NSNumber *lat = [regionDict objectForKey:@"lat"]; //[latitude addObject:lat]; NSNumber *lng = [regionDict objectForKey:@"lng"]; //[longitude addObject:lng]; ...

Retrieving live information from an API in order to populate a specific route

Utilizing the contents of two crucial files to extract data from separate APIs, here is my simplified example: poloniex.js const Poloniex = require('poloniex-api-node') const poloniex = new Poloniex() async function obtainExchangeData() { po ...

NextJs manages the logic for processing requests both before and after they are handled

NextJs stands out from other frameworks due to its lack of support for filter chains, request pre-processing, and post-processing. Many node project developers or library creators may find these features essential for executing logic before and after API c ...

The link button appears unselected without a border displayed

I am facing an issue with a link button in my code. Here is the snippet: <div class="col-2"> <a type="button" routerLink="auto-generate-schedules/generate" class="btn btn-primary mb-2">Generate Sche ...

Understanding the response from an AJAX call

VB code Dim temp3 As String = dt.ToString() cmd.Connection = con con.Open() i = cmd.ExecuteNonQuery() con.Close() If i = 1 Then msg = "Record successfully inserted" ...

Struggling to integrate the c3 chart library with Angular, encountering loading issues

I've been attempting to utilize the c3 angular charts, but unfortunately nothing is displaying on my page. Despite checking for console errors and following a tutorial, I still can't seem to get anything to show up. I have cloned the git repo an ...

Functionality that can be utilized repeatedly

I've been struggling to implement a feature for repeatable blocks in my web form. The issue I'm facing is that when I click the buttons, nothing happens even though they work fine when tested in the console. I've been stuck on this problem f ...

ES6 Angular-Meteor ng-table's getData function is not being invoked

I've been working on updating my code to ES6. Specifically, I'm using angular-meteor and ng-table. Everything was displaying correctly in the table before the refactor, but now after converting to ES6 syntax, the data no longer appears. Here is a ...

Customized webpage content using AJAX for interactive map selections

I have integrated JQVMaps into a WordPress website to display a dynamic world map. The goal is to update the content of the page based on the region that the user clicks. Below is a snippet of the code I have implemented as a proof of concept: <div ...

Sending files using AJAX without FormData in Internet Explorer 9

Unfortunately, IE9 does not support FormData, making file uploads via XMLHttpRequest a more challenging task. Is there a workaround for this issue? I've come across mentions of using iFrames, but the process seems complex and unclear on how to transf ...

Click to shift the div downwards

Currently, I have a piece of javascript applied to a div that directs the user to a specific link: <div style="cursor:pointer;" onclick="location.href='http://www.test.com';"> I am wondering if there is a way to add an effect where, upon ...