Get City, State, Country from Latitude and Longitude in Google Sheets
Asked Answered
L

2

5

In Google Sheets, I have a column with latitude and longitude coordinates. The list goes from A2:A1000. I also have columns for City, State, and Country in B1, C1, and D1, respectively. Is there a formula or script I can run that reads the coordinates and provides the city, state, and country in their respective column? I do not know how to use JavaScript, XML, JSON, serialized PHP, etc. so if your suggestion includes one of those, please provide some instructions. Thanks in advance.

Linalinacre answered 22/12, 2014 at 17:0 Comment(0)
L
15

Well, I have a psuedo-solution. Go into Google Spreadsheets > Tools > Script Editor and paste the following code into a blank project:

function reverse_geocode(lat,lng) {
  Utilities.sleep(1500);

 var response = Maps.newGeocoder().reverseGeocode(lat,lng);
 for (var i = 0; i < response.results.length; i++) {
   var result = response.results[i];
   Logger.log('%s: %s, %s', result.formatted_address, result.geometry.location.lat,
       result.geometry.location.lng);
   return result.formatted_address;
 }
}

Then in the spreadsheet, use this formula:

=reverse_geocode(latitude_goes_here,longitude_goes_here)

For example, if I have the latitude in A2 and longitude in B2:

=reverse_geocode(A2,B2)

This will provide the full address. I'm now trying to figure out how to parse the country from the address.

Linalinacre answered 23/12, 2014 at 17:34 Comment(2)
@Gabriel.Rotman It is working but giving error. "Service invoked too many time for one day: geocode. (line 25) "Blackwell
I know I am really late for the reply as I got into this today. I fetched country value by splitting the string. "function reverse_geocode(lat,long) { Utilities.sleep(1500); var response = Maps.newGeocoder().reverseGeocode(lat,long); for (var i = 0; i < response.results.length; i++) { var result = response.results[i]; var result = result.formatted_address; var result = result.split(","); return result[(result.length)-1]; } }"Maidamaidan
B
2

Based on @gabriel-rotman solution.

Go into Google Spreadsheets > Tools > Script Editor and paste the following code into a blank project:

/**
 * Return the closest, human-readable address type based on the the latitude and longitude values specified.
 *
 * @param   {"locality"}  addressType Address type. Examples of address types include
 *                                    a street address, a country, or a political entity.
 *                                    For more info check: https://developers.google.com/maps/documentation/geocoding/intro#Types
 * @param   {"52.379219"} lat         Latitude
 * @param   {"4.900174"}  lng         Longitude
 * @customfunction
 */
function reverseGeocode(addressType, lat, lng) {
    Utilities.sleep(1500);

    if (typeof addressType != 'string') {
        throw new Error("addressType should be a string.");
    }

    if (typeof lat != 'number') {
        throw new Error("lat should be a number");
    }

    if (typeof lng != 'number') {
        throw new Error("lng should be a number");
    }
    var response = Maps.newGeocoder().reverseGeocode(lat, lng),
        key      = '';
    response.results.some(function (result) {
        result.address_components.some(function (address_component) {
            return address_component.types.some(function (type) {
                if (type == addressType) {
                    key = address_component.long_name;
                    return true;
                }
            });
        });
    });
    return key;
}

Then in the spreadsheet, use this formula:

=reverseGeocode(address_type; latitude_goes_here; longitude_goes_here)

For example, if I have the latitude in A2 and longitude in B2 and that I want to get the city then I can use:

=reverseGeocode("locality"; A2; B2)

If you want the country you can use:

=reverseGeocode("country"; A2; B2)

Bonus function to extract part of an address:

/**
 * Return the closest, human-readable address type based on the the address passed.
 *
 * @param   {"locality"}  addressType Address type. Examples of address types include
 *                                    a street address, a country, or a political entity.
 *                                    For more info check: https://developers.google.com/maps/documentation/geocoding/intro#Types
 * @param   {"Amsterdam"} address     The street address that you want to geocode,
 *                                    in the format used by the national postal service
 *                                    of the country concerned. Additional address elements
 *                                    such as business names and unit, suite or floor
 *                                    numbers should be avoided.
 * @customfunction
 */
function geocode(addressType, address) {
    if (typeof addressType != 'string') {
        throw new Error("addressType should be a string.");
    }

    if (typeof address != 'string') {
        throw new Error("address should be a string.");
    }
    var response = Maps.newGeocoder().geocode(address),
        key      = "";
    response.results.some(function (result) {
        return result.address_components.some(function (address_component) {
            return address_component.types.some(function (type) {
                if (type === addressType) {
                    key = address_component.long_name;
                }
            });
        });
    });
    return key;
}
Behan answered 16/12, 2015 at 20:3 Comment(1)
Thank you for the effort. It is working but giving error. "Service invoked too many time for one day: geocode. (line 25)". I was trying to get administrative areas and addresses of 1000 lat/lonBlackwell

© 2022 - 2024 — McMap. All rights reserved.