· 6 years ago · Apr 24, 2020, 07:46 AM
1Function Get-Address {
2 [CmdletBinding()]
3 Param (
4 # Uri parameters
5 [Parameter(Mandatory)] [String] $Address,
6 # It is the fszymaniak's api key for testing purpose
7 [string]$ApiKey = "AIzaSyAnBN47v2zAT9lPAIKYutL8nVEf94A0_ok",
8 [string]$Uri = "https://maps.googleapis.com/maps/api/geocode/json?",
9 [string]$Url = "$($Uri)address=$($Address)&key=$($ApiKey)"
10 )
11
12 # Refer to https://developers.google.com/maps/documentation/geocoding/start for info about properties returned
13 $Results = Invoke-RestMethod -Uri $Url
14 If ($Results.status -eq 'OK') {
15 $jsonResults = $Results.results # get the results from json data returned from Google API
16
17 # filtering data
18 $line1 = $jsonResults.address_components | Where-Object { $_.types -CMatch 'route' }
19 $line2 = $jsonResults.address_components | Where-Object { $_.types -CMatch 'street_number' }
20 $city = $jsonResults.address_components | Where-Object { $_.types -CMatch 'locality' }
21 $state = $jsonResults.address_components | Where-Object { $_.types -CMatch 'administrative_area_level_1' }
22 $stateCode = $state.short_name
23 $country = $jsonResults.address_components | Where-Object { $_.types -CMatch 'country' }
24 $county = $jsonResults.address_components | Where-Object { $_.types -CMatch 'administrative_area_level_2' }
25 $countryCode = $country.short_name
26 $postCode = $jsonResults.address_components | Where-Object { $_.types -CMatch 'postal_code' }
27
28 $addressDetails = @{
29 UnformattedAddress = $jsonResults.formatted_address
30 Latitude = $jsonResults.geometry.location.lat
31 Longitude = $jsonResults.geometry.location.lng
32 Line1 = $line1.long_name
33 Line2 = $line2.long_name
34 City = $city.long_name
35 State = $state.long_name
36 StateCode = $stateCode
37 Country = $country.long_name
38 County = $county.long_name
39 CountryCode = $countryCode
40 PostCode = $postCode.long_name
41 }
42
43 $Results = $addressDetails
44 $Results
45 }
46 else {
47 Write-Warning "Did not get succcessful return from Google Geocode API endpoint"
48 $Results
49 }
50
51 Write-Host ($Results | ConvertTo-Json)
52}