Get city name and country name in Mapbox Geocoder

I'm switching the geocoder for Routeshuffle for the third time. First I was using OpenStreetMaps' free, provided geocoder Nominatim. But it didn't work well, plus I was relying on a free service that could go down at any moment. Then I switched to Algolia Places. It was better because it used IP tracking to show you the closest, more relevant locations first. But this was problematic because the street address estimation was horrible. If I put in “20 High St” or “2927923 High St”, the same location would be given. It would just give the center of the street. This could be miles away from the intended point. Basically useless.

Now, I'm using Mapbox's JS geocoder. It has the benefits of Algolia Places in that it has a live autocomplete dropdown, but it is way more accurate in street address estimation. Plus, I'm already using Mapbox for everything else.

Here's a code snippet I thought I would share for getting the “City name, country name” of the geocoded address, because Mapbox doesn't give a straight-forward response as-is:

geocoder.on('result', function(ev) { cityname = "undefined"; countryname = "undefined"; geocoderesults = ev.result.geometry.coordinates; for (i=0; i < ev.result.context.length; i++) { if (ev.result.context[i].id.startsWith("place")) { cityname = ev.result.context[i].text; } else if (ev.result.context[i].id.startsWith("country")) { countryname = ev.result.context[i].text; } } if (cityname == "undefined") { cityname = ev.result.text; } citymapbox = cityname + ", " + countryname; });

This was tested and gave the right city and country in many locations. Hope this helps! PS: check out Routeshuffle, a site for generating random running routes.