How many Capitals are closer to me than my own?

Using GeoNearest:

capitals = Map[CountryData[#, "CapitalCity"] &, CountryData["UN"]];
nearest = GeoNearest[capitals, Here, 10]

Mathematica graphics

And then use LengthWhile like this to answer the question in the title (the capital in my country is Stockholm):

Mathematica graphics

I only printed the ten closest capitals for display purposes, you can use this:

nearest = GeoNearest[capitals, Here, All]

You can also use free-form input in place of CountryData:

Mathematica graphics

There is also TakeWhile if you want to make a visualization. Here is a suggestion. I apologize for using images for code, but I like how entities look in notebooks:

Mathematica graphics

Mathematica graphics

Note that my answer to the question "how many capitals are closer to me than my own?" is short enough to be a one-liner, if using free-form input:

Mathematica graphics


For efficiently retrieving nearby cities, use Nearest[] with a custom DistanceFunction:

capitals = Map[CountryData[#, "CapitalCity"] &, CountryData["UN"]];
locs = CityData[#, "Coordinates"] & /@ capitals;

nf = Nearest[locs -> capitals, DistanceFunction -> (QuantityMagnitude @* GeoDistance)];

Then:

CommonName /@ nf[CityData[{"Aachen", "NorthRhineWestphalia", "Germany"}, "Coordinates"], 7]
   {"Brussels", "Luxemburg", "Amsterdam", "Paris", "Bern", "London", "Vaduz"}

From that, just increase the value of the second argument until the last city returned is in the same country as the original city:

nearestCapitals[city_, opts___] := Module[{k = 0, res},
       While[res = nf[CityData[city, "Coordinates"], ++k]; 
             CityData[Last[res], "Country"] =!= CityData[city, "Country"]];
       GeoGraphics[{Tooltip[GeoMarker[city, "Color" -> Blue], CommonName[city]], 
                    MapAt[{Directive[Red, Thick], #} &, 
                          GeoPath[{city, #}, "Geodesic"] & /@ res, {-1}], 
                    Tooltip[GeoMarker[#], CommonName[#]] & /@ res}, opts, 
                   PlotLabel -> StringForm["`` UN capital cities are closer",
                                           Length[res] - 1]]]

nearestCapitals[Entity["City", {"Unalaska", "Alaska", "UnitedStates"}], 
                GeoBackground -> GeoStyling["CountryBorders"]]

nearest capitals to Unalaska

Tags:

Geographics