Get-GeoLocation

If you ever find yourself in a situation where you don’t really know where you are, I got you covered!

This small function will try to get the longitude/latitude coordinates and use the OpenStreetMap API to perform a reverse lookup to get address information for your current location.


function Get-GeoLocation {
<#
.SYNOPSIS
Get current location.
.DESCRIPTION
This function tries to get the latitude and longitude coordinates of the current location,
and will look up those coordinates on OpenStreetMap to get address information.
.EXAMPLE
Get-GeoLocation
Will try to get address information about your current location.
.EXAMPLE
Get-GeoLocation -LatLon
Will return the Latitude and Longitude of your current location.
.NOTES
Author: Øyvind Kallstad
Version: 1.0
Date: 09.08.2016
.LINK
https://communary.net/
#>
[CmdletBinding()]
param (
# Number of times the function tries to get the coordinates. Default value is 4.
[Parameter()]
[int] $NumTries = 4,
# Number of milliseconds to sleep between each try. Default value is 1000.
[Parameter()]
[int] $SleepBetweenTries = 1000,
# Use this switch to indicate that you want the Latitude and Longitude returned.
# Address lookup will not be performed.
[Parameter()]
[Alias('ll')]
[switch] $LatLon
)
try {
Add-Type AssemblyName 'System.Device'
}
catch {
Write-Warning 'Unable to load the needed assembly (System.Device).'
break
}
$watcher = New-Object TypeName System.Device.Location.GeoCoordinateWatcher ArgumentList 'High'
[void]$watcher.TryStart($true, [TimeSpan]::FromMilliseconds(1000))
$count = 0
do {
$count++
Start-Sleep Milliseconds $SleepBetweenTries
} while (($watcher.Position.Location.IsUnknown) -or ($count -ge $numTries))
if ($watcher.Position.Location.IsUnknown) {
Write-Warning 'Couldn''t get coordinates.'
}
else {
$coord = $watcher.Position.Location
if (-not ($LatLon)) {
$url = "http://nominatim.openstreetmap.org/reverse?format=json&lat=$($coord.Latitude.ToString().Replace(',','.'))&lon=$($coord.Longitude.ToString().Replace(',','.'))&zoom=18&addressdetails=1"
try {
$result = Invoke-RestMethod Uri $url
Write-Output ($result.address)
}
catch {
Write-Warning $_.Exception.Message
}
}
else {
Write-Output ([PSCustomObject][Ordered] @{
Latitude = $coord.Latitude
Longitude = $coord.Longitude
})
}
}
}
New-Alias Name whereami Value Get-GeoLocation Force

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s