4

How can I parse through the response from a reverse geocode 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);
                    }
                } 

This displays the formatted address fine in the popup, but I'm trying to take other bits out of the response, ideally the street name or route (if no street name found). But when using obj = JSON.parse(json); I keep getting this error in the console.

SyntaxError: JSON.parse: unexpected character

if it were PHP I would do a bunch of for each loops. Is it possible to do something similar in JavaScript ?

heres a sample

{
   "results" : [
  {
     "address_components" : [
        {
           "long_name" : "131",
           "short_name" : "131",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Stubbington Avenue",
           "short_name" : "Stubbington Ave",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Portsmouth",
           "short_name" : "Portsmouth",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Portsmouth",
           "short_name" : "Portsmouth",
           "types" : [ "administrative_area_level_3", "political" ]
        },
        {
           "long_name" : "Portsmouth",
           "short_name" : "Portsmouth",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "England",
           "short_name" : "England",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United Kingdom",
           "short_name" : "GB",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "PO2",
           "short_name" : "PO2",
           "types" : [ "postal_code_prefix", "postal_code" ]
        },
        {
           "long_name" : "Portsmouth",
           "short_name" : "Portsmouth",
           "types" : [ "postal_town" ]
        }
     ],
     "formatted_address" : "131 Stubbington Avenue, Portsmouth PO2, UK",
     "geometry" : {
        "location" : {
           "lat" : 50.8170795,
           "lng" : -1.0709701
        },
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 50.81842848029149,
              "lng" : -1.069621119708498
           },
           "southwest" : {
              "lat" : 50.8157305197085,
              "lng" : -1.072319080291502
           }
        }
     },
     "types" : [ "street_address" ]
  }
   ],
"status" : "OK"
}

also heres a link to my dev page with my current code in full

In summary, how do I get "Stubbington Avenue" from that mess up there ?

2
  • that "mess" is valid object syntax.. not sure why the json.parse would fail.. if you can turn it into an object then you can for for-each loops as demonstrated here stackoverflow.com/questions/8312459/… Commented Mar 4, 2014 at 23:58
  • console.log(json) keeps saying its not defined. But if I add alert(json) to the page a pop up of [object][object] etcdoes come up, am I just not passing it on correctly ? obj = JSON.parse(results); Commented Mar 5, 2014 at 0:13

2 Answers 2

10

you don't need to JSON.parse those results, it's already json.

to get "stubbington avenue" out of that valid json, you would use results[0].address_components[1].short_name

if you wanted to build the actual address out of those address components, you can loop through and see the values printed out to the console like this:

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

instead of logging them out, append them to a string, or append them to an element, whatever you wish to do with them.

Sign up to request clarification or add additional context in comments.

Comments

0

I am using Meteor and for Meteor.js it worked a bit differently in my case

Below is the Meteor Client Side and Server Side Code that worked for me:

      // 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){
          // do checks
          var apiurl = 'http://maps.googleapis.com/maps/api/geocode/json?address='+zip_code+'&sensor=true';
          var result = HTTP.get( apiurl );
          return result;
      }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.