0

I need to obtain the zip code from a given address using the Google Maps Geocoder API. I have been able to get other data, such as longitude and latitude, but obtaining the zip code is just a little bit different. The Json I am trying to parse the zip code from is:

    {
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "1600",
               "short_name" : "1600",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "Amphitheatre Parkway",
               "short_name" : "Amphitheatre Pkwy",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Mountain View",
               "short_name" : "Mountain View",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Santa Clara County",
               "short_name" : "Santa Clara County",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "California",
               "short_name" : "CA",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "94043",
               "short_name" : "94043",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
         "geometry" : {
            "location" : {
               "lat" : 37.4267861,
               "lng" : -122.0806032
            },

The javascript function I have written is:


        async function getZipCode() {
        const searchedAddress = @Html.Raw(Json.Serialize(ViewData["searchString"]));
        const response = await axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
            params: {
                address: searchedAddress,
                key: [key],
                sensor: 'true_or_false'
            }
        })
            let addressComponents = response.data.results[0].address_components;
            for (var i = 0; i < addressComponents.count; i++) {
                if (addressComponents[i].types == 'postal_code') {
                    let zip = response.data.results[0].address_components[i].short_name;
                    return zip;
                    console.log(zip);
                }
            }

         }

I know, for the data provided in this json example, I can obtain the postal_code with

response.data.results[0].address_components[6].short_name;

but this is not always the case. Sometimes the postal code is contained in a different iteration of address_components, so I need to come up with a way to check for the type and then get the short_name.

The function I have is not returning anything to the console. I realize that the console.log statement is within the "if" statement, but am drawing a blank on how to actually get this data.

BenTen
  • 333
  • 1
  • 5
  • 17
  • 1
    Duplicate of [Latitude and longitude can find zip code?](https://stackoverflow.com/questions/6764917/latitude-and-longitude-can-find-zip-code) – MrUpsidown Mar 10 '21 at 08:53

1 Answers1

1

You're pretty close in your attempt. Where it seems you've gone awry is here:

if (addressComponents[i].types == 'postal_code') { // ...

What you're asking the interpreter to figure out is if addressComponents[i].types is equal to the string postal_code, when we know that types seems to always be an Array. In most all setups, Arrays can't be coerced directly to strings.

What you're actually trying to figure out is if the string postal_code exists within the Array. As such, you can use Array.prototype.includes():

if (addressComponents[i].types.includes('postal_code')) { // process the postal code data

Aside: anything after a return won't get executed, so you wouldn't see the output from console.log(zip) using your code in any event, success or not. Using an IDE with solid syntax highlighting may have alerted you to this by showing the code that wouldn't get executed in a lighter opacity - I would recommend beginning to use one straight away if you aren't already.

esqew
  • 42,425
  • 27
  • 92
  • 132
  • Thanks a lot. This, along with changing addressComponents.count to addressComponents.length did the trick. – BenTen Mar 10 '21 at 05:23