Search code examples
jqueryjsongoogle-mapsgeolocation

Google Maps (Reverse) Geocoding API should display only Cityname


Im using the Google Maps GeolocationAPI to retrieve the Cityname of given Coordinates ( this is called reverse geolocation). Documentation is available here

i send a post request with jquery and get a JSON formatted object at my script its this array: locationName[].

for some coordinates i have success displaying the city name using:

locationName[0].address_components[0].long_name;

but for some coordinates the city name is at

locationName[0].address_components[1].long_name;

or even at

locationName[0].address_components[3].long_name;

additionally i want to display the City district (if its available for the given coordinates if not then i only want to display the cityname)

how can i determine which field in the array is the city name and how to determine if a city district is available and if so in which field it is ?


Solution

  • This question is basically about checking objects for a particular value in an array attribute and returning that object if the value is found in the array. Here's one way you can do it -

    var desiredLocationDescription;
    var addressComponentArray = [];
    var typeName = "locality";
    
    
    for (var i = 0; i < locationName[0].address_components.length; i++){
        addressComponentArray.push(locationName[0].address_components[i])
    }
    
    for (var i = 0; i < addressComponentArray.length; i++){
        if (addressComponentArray[i].types.includes(typeName)){
            desiredLocationDescription = addressComponentArray[i];
            break;
        }
    }
    
    console.log(desiredLocationDescription.long_name)
    

    Since the city name is stored in the object with the type: ["locality", "political"], look through the array of objects until you find the one with 'locality' in its types.