Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
function Get-GeoLocation {
Get current location.
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.
Will try to get address information about your current location.
Get-GeoLocation -LatLon
Will return the Latitude and Longitude of your current location.
Author: Øyvind Kallstad
Version: 1.0
Date: 09.08.2016
param (
# Number of times the function tries to get the coordinates. Default value is 4.
[int] $NumTries = 4,
# Number of milliseconds to sleep between each try. Default value is 1000.
[int] $SleepBetweenTries = 1000,
# Use this switch to indicate that you want the Latitude and Longitude returned.
# Address lookup will not be performed.
[switch] $LatLon
try {
Add-Type -AssemblyName 'System.Device'
catch {
Write-Warning 'Unable to load the needed assembly (System.Device).'
$watcher = New-Object -TypeName System.Device.Location.GeoCoordinateWatcher -ArgumentList 'High'
[void]$watcher.TryStart($true, [TimeSpan]::FromMilliseconds(1000))
$count = 0
do {
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 = "$($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
Copy link

Chirishman commented Dec 24, 2017

Can loop infinitely. Evaluation on line 61 should be an AND statement and the numerical comparison should be less than or equal or you should switch those variables.
} while (($watcher.Position.Location.IsUnknown) -and ($count -le $numTries))
} while (($watcher.Position.Location.IsUnknown) -and ($numTries -ge $count))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment