How can I get my computer's location to the granularity of city and country using the command-line?

I know I could get the IP of the correct network interface and do an IP lookup but I wonder if the system has a quicker way to access this. The system clock has the location so I am wondering if it's possible to get it that way.


Command line tool

I've made quick modification to an excellent robmathers app WhereAmI. You can find it on my github.

Once You compile it and run, that's the output:

Latitude: 40.714232
Longitude: -73.9612889
Accuracy (m): 65.000000
Timestamp: 30.04.2015, 11:37:45 CEST
Location: 277 Bedford Avenue, Brooklyn, NY 11211, United States

If You want only the city and the country - changes in parsing json should be made (or grep the output). Sample json data can be found here.

Note: This is very quick implementation, but there shouldn't be any errors

Info from preferences

You can get info from preferences by running:

defaults read /Library/Preferences/.GlobalPreferences.plist com.apple.preferences.timezone.selected_city

You'll need to parse the output, because it looks like:

CountryCode = PL;
GeonameID = 3081368;
Latitude = "51.1";
LocalizedNames =     {
    pl = "Wroc\\U0142aw";
Longitude = "17.03333";
Name = "Wroc\\U0142aw";
Population = 634893;
TimeZoneName = "Europe/Warsaw";
Version = 1;
  • Well, this is awesome, but requires the internet. If I use that, I figure I might as well do an old-fashioned IP lookup. This is more accurate, I take it? – SimplGy Apr 30 '15 at 12:10
  • As far as I know, there's no offline database with locations assigned to lat/lon. The only thing I found is: /System/Library/PreferencePanes/DateAndTime.prefPane/Contents/Resources/TimeZone.prefPane/Contents/Resources/all_cities_adj.plist but that's only capital cities (?) list. – Mateusz Szlosek Apr 30 '15 at 14:06
  • My clock does already know it's locale in order to set a time zone. Usually it even has the correct city. It knows this with or without internet connectivity, it just won't update the location without the internet. – SimplGy Apr 30 '15 at 14:07
  • 1
    @SimplGy the info is stored in defaults, updated the answer – Mateusz Szlosek Apr 30 '15 at 15:12
  • That is so awesome! – SimplGy May 4 '15 at 6:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .