How to Get User’s Country and State (a.k.a Reverse Geocoding) in Unity
For one of the games I’m currently working on, I needed to know what country the players were from. There are multiple ways to get user’s location as I discussed in another post. I decided to use GPS which gives us the most accurate data. You can checkout this post for technical details and sample code to access GPS location in Unity. On the down side, we get only (latitude, longitude) coordinates from the API. Basically we know the coordinates on earth where the player is, but we don’t what country they are in. We would be in a different boat if we had gone with IP geocoding or directly asking the user.
Reverse Geocoding is the process of converting the (longitude, latitude) coordinates to a place. The place could be a country, a state, a park or a restaurant.
There are online services that provide reverse geocoding APIs, most notably Google Maps. In general reverse geocoding, the online services would be the way to go. For us however since we only need the country, it seemed like a bit of an overkill. First it would mean that in case of offline activity, we wouldn’t be able to perform the queries. Secondly it would cost us a bit. I was hopeful I’d be able to find a good library to use on the users’ devices.
Luckily I came across Wibci.CountryReverseGeocode library on github. It does exactly what I wanted! It allows offline, (fairly-)performant queries for country and US states.
There were a few minor issues for using the library in Unity. First the ll2cpp optimizer would get stuck on large initializer code. Second was the use of 3rd party JSON libraries which were incompatible with Unity. I got around those and created a port of the library for Unity. You can checkout the library on github from the link below.
Reverse Geocoder for Unity allows you to look up world coordinates (latitude, longitude) and get the country / US state…
Using the Reverse Geocoder library linked above and device’s location, you can get the user’s country and state offline. A powerful tool for making location-based games in Unity.