Is it possible to extract JSON data from a reverse geocoding request to Google

Looking to extract specific information from a reverse geocode response using Google Maps JavaScript API v3.

geocoder.geocode({'latLng': latlng}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[0]) {
                        infowindow.setContent(results[0].formatted_address);
                        infowindow.open(map, marker);
                    }
                } 

The formatted address is displayed in the popup as expected, but I'm interested in retrieving other details like the street name or route. Despite attempts with JSON.parse(json);, an error keeps popping up in the console:

SyntaxError: JSON.parse: unexpected character

In a PHP environment, I would utilize several for each loops. Can a similar approach be taken in JavaScript?

Here's a snippet of sample data:

{
   "results" : [
  {
     "address_components" : [
        {
           "long_name" : "131",
           "short_name" : "131",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Stubbington Avenue",
           "short_name" : "Stubbington Ave",
           "types" : [ "route" ]
        },
        ...
     ],
     "formatted_address" : "131 Stubbington Avenue, Portsmouth PO2, UK",
     ...
  }
   ],
"status" : "OK"
}

Addtionally, here's a link to my developer page showcasing the full code.

To simplify, how can I isolate "Stubbington Avenue" from the provided dataset?

Answer №1

There is no need to parse those results using JSON.parse; it is already in JSON format.

To extract "stubbington avenue" from the valid json, you can access it by using

results[0].address_components[1].short_name

If you want to construct the complete address using those address components, you can iterate through them and display the values in the console like this:

for(var i in results[0].address_components){
    console.log(results[0].address_components[i].short_name);
}

Instead of just logging them out, you can append them to a string or add them to an element, depending on what you wish to do with them.

Answer №2

In my experience with Meteor, I found that it worked a little differently for Meteor.js compared to other platforms.

Here is the code that successfully ran on both the Client Side and Server Side:

      // Client Side

      var zipcode = $('[name=zipcode]').val();

      Meteor.call('getLocationbyZipGoogleAPI', zipcode, function(error, result){
          if(error){
              console.log('error',error.reason);
          } else {
            var apidata = JSON.parse(result.content);
            var longname = apidata.results[0].address_components[3].long_name;
            var longaddress = apidata.results[0].formatted_address;
            var finaladdress = longaddress+', '+longname;
          }
      });

      // Server Method to Call API

      'getLocationbyZipGoogleAPI': function(zip_code){
          // perform validation checks
          var apiurl = 'http://maps.googleapis.com/maps/api/geocode/json?address='+zip_code+'&sensor=true';
          var result = HTTP.get( apiurl );
          return result;
      }

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

How can I simulate the response of a VueX action using Vue-test-utils?

I am currently developing a test for a Vue component that interacts with a module store to execute an action and utilize the result from it. Since the action involves making requests to our API, I prefer not to run the test using the actual action. Instea ...

Retrieve the child nodes from the array and organize them into a

Given an array of regions, where the highest region has key: 10 and parent_id: null, the goal is to restructure this array in order to return a tree representation. The desired regions tree structure for input [10] should be: Egypt Zone 1 Tagamo3 Giza H ...

Locate Checkbox by its Attribute Name and Value

On my webpage, there are multiple groups of checkboxes. In one particular group, I have added a custom "documentcategory" attribute to each checkbox. My goal is to identify all the checkboxes on the page that have the "documentcategory" attribute with a va ...

The Onchange event failed to display or conceal the Div

Can someone help me with an issue in my script? Here is my Javascript code: <script type="text/javascript"> $(document).ready(function() { $("#datetimepicker_mask2").change(function() { var date = $("#datetimepicker_mask2").val(); ...

Sending blank data using ExpressJS ajax feature

I am encountering an issue while trying to send JSON data to my server as the POST requests are coming through with empty bodies. Below is the TypeScript code I am using on the front end: function sendData() : void { console.log("Sending data..."); var na ...

Is the displayed Cyrillic string in the incorrect character set?

I am facing an issue with extracting a value from a decoded JSON response obtained from a Russian API. The value within the JSON = Object268 Initially, it appeared as: Объект 268 After including <meta charset="utf-8"> in my html ...

The CSS navigation bar is not properly aligned in the center

This menu was constructed by me: JSBIN EDIT ; JSBIN DEMO Upon closer inspection, it appears that the menu is not centered in the middle of the bar; rather, it is centered higher up. My goal is to have it positioned lower, right in the middle. I ...

Splitting Array into various objects using JavaScript techniques

How can I split the Array into individual objects? I need to transform the array below: arr = [ { name: 'abc', age: 15, roll_no: 25 }, { name: 'def', age: 10, roll_no: 20 }, { name: 'xyz', age: 16, roll_no: 18 }, ...

Managing JSON data with tab fragments on android devices

I am a beginner in the world of Android development and I am currently working on accessing JSON data for my project. The app consists of two tabs within a viewpager - the first tab displays information about events while the second tab contains a custom l ...

Deliver files statically from Node.js while handling POST data

Currently, I am running a node.js server and utilizing node-static to serve static HTML files. var nodeStatic = require('node-static'); var file = new nodeStatic.Server('./public'); .. file.serveFile('/file.html', 500, {}, re ...

It seems that React JS with Redux may not be triggering a re-render

I am currently delving into the world of React JS with Redux and have what I believe is a straightforward query. Here's the code snippet I'm working with: import React from 'react'; import ReactDOM from 'react-dom'; import { ...

Unable to locate index.html file in Docker container while dockerizing React application

I'm a newcomer to Docker and I'm looking to containerize my react app. The index.html file is located in the public folder within my react project. However, when I try to run the docker image, it fails with an error indicating that the index.html ...

Guide to refreshing extensive dataset using MySQL migration scripts

We are in the process of developing a Nodejs application for a client who has requested that we use migration scripts to streamline updating the production database. As someone new to MySQL, I am struggling with how to update table contents using only MySQ ...

Is there a way to retrieve values from TextFields and Select elements by simply clicking on a button?

I am currently working on a project using react, redux, and material ui. I need to retrieve data from a TextField in order to make an order. The code snippet below showcases my current implementation: <Select value={product.color_set[0].title}> { ...

Come hang out in the user voice channel by reacting with your favorite emojis!

I am currently developing a Discord bot, and I want to implement a feature where the bot joins a voice channel if a user reacts to its message. I am using the awaitReactions function which only returns reaction and user data. Is there a way to retrieve th ...

Error: react-testing-library throwing validateDOMNesting warning

Warning: validateDOMNesting(...): <tbody> cannot appear as a child of <div>. in tbody (created by TableBody) in TableBody (created by TableBody) in TableBody Inquiry: Is there a way to render the TableBody component within a table ...

What is the best way to implement a custom toast delay in a React application using setTimeout

The concept is straightforward: When the function showToast is called, I aim to change my toast's className to show, and then remove it by replacing with an empty string after displaying it for 3 seconds. HTML: <div id="toast">New col ...

Attempting to retrieve XML/JSON

I am struggling with extracting the first 15 words from a file using the API. I have attempted to do it with both XML and JSON, but keep encountering this error: XMLHttpRequest cannot load No 'Access-Control-Allow-Origin' header is present on th ...

Innovative application transforms rigid input with dynamic hyphens

I am currently working on an input field specifically designed for Social Security Numbers (SSNs). My aim is to have an input with pre-placed hyphens, allowing the user to simply enter their 9-digit SSN while the numbers automatically space themselves arou ...

Formik Fields with unique key properties

When mapping text fields, I follow this structure: { AddVehicleFields.map(({formikRef, ...input}) => ( <> <TextField key={formikRef} helperText={ getIn(formik.touched, formikRef) ? getIn(formik. ...