About the Geocoding API
Google's Geocoding API provides a way to convert physical addresses into geographic coordinates. We can leverage this service to obtain the latitude and longitude coordinates for a list of cities or street addresses.
To use the Geocoding API, you must first obtain an API key. When you first sign up, Google will give you a $300 credit to use within a year, and then a $200 credit each month. These will allow you to use the API for free. Check out their pay-as-you-go pricing model here.
Once you sign up and obtain an API key you may begin making requests!
Example Request
<maps.googleapis.com/.../json
Sending that Request with PowerShell
$url = "<">maps.googleapis.com/.../json
$params = @{ address = "405 Brushy Creek Rd, Cedar Park, TX"; key = $APIKEY }
Invoke-WebRequest $url -Method Get -Body $params -UseBasicParsing | ConvertFrom-Json
Complete PowerShell Script
Of course, it would be better if we had a list of locations and were able to convert them all at once. For that, we can write a PowerShell script that reads a CSV of locations, iterates through each entry, and writes the response to a CSV.
Check out the full repo at Loop1's GitHub: https://github.com/loop1systems/geocoder
param (
[Parameter(Mandatory = $true)][string]$inputFile
)
$APIKEY = "thisIsMyAPIKEY"
# Verify that the API key is not empty
if ($APIKEY -eq $null -or $APIKEY -eq "") {
Write-Output "Please provide an API key."
Exit
}
# Read input csv
$locations = Import-Csv -Path $inputFile -Header "location"
# Geocoding endpoint
$url = "<">maps.googleapis.com/.../json
# arraylist for storing response
$locData = New-Object System.Collections.ArrayList
foreach ($loc in $locations) {
# build the query parameters
$params = @{ address = $loc ; key = $APIKEY }
# send API request
$response = Invoke-WebRequest $url -Method Get -Body $params -UseBasicParsing | ConvertFrom-Json
if ($response.status -ne "OK") {
$response.error_message
Exit
}
$detailsObject = [PSCustomObject]@{
location = $loc.location
lat = $response.results.geometry.location.lat
lng = $response.results.geometry.location.lng
}
$locData.Add($detailsObject) | Out-Null
}
$locData | Export-Csv -Path "lat-long.csv" -NoTypeInformation
P.S. Stay tuned for a post about how to use this data to create World Map Points!
----------------------
Ana Cruz
Loop1 Systems