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.