Unity C# How to get country, city or location of a player
Asked Answered
E

3

6

I've a game where I'm trying to keep my own analytics. No pin point location, is there something similar to SystemInfo class that could give approximate location of the player?

I know I can tap into the GPS but I don't want to make things complicated. Just a simple city or country will do.

Please advise.

Electric answered 13/4, 2020 at 5:53 Comment(0)
U
5

I had this problem too, so I wanted to make as simple of a solution as possible. Unfortunately, it wasn't easy:

[Serializable]
public class IpApiData
{
    public string country_name;

    public static IpApiData CreateFromJSON(string jsonString)
    {
        return JsonUtility.FromJson<IpApiData>(jsonString);
    }
}


public static IEnumerator SetCountry()
{
    string ip = new System.Net.WebClient().DownloadString("https://api.ipify.org");
    string uri = $"https://ipapi.co/{ip}/json/";


    using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
    {
        yield return webRequest.SendWebRequest();

        string[] pages = uri.Split('/');
        int page = pages.Length - 1;

        IpApiData ipApiData = IpApiData.CreateFromJSON(webRequest.downloadHandler.text);

        Debug.Log(ipApiData.country_name);
    }
}

This will get the country, no problem. If you want to change it to city, or anything else, you'll just have to add some fields to IpApiData, as per this link: https://ipapi.co/api/#complete-location

Ulrick answered 18/4, 2021 at 17:43 Comment(1)
If you're making the request from the player's device you won't get rate limitedUlrick
S
1

You can either ask the user for their details or send a request to your web server where that uses something like ipdata.co to track where the IP address came from.

Syphilology answered 13/4, 2020 at 5:56 Comment(0)
E
0

You can first take the IP of the player. I think this might help answers.unity.com/questions/518346/get-ipv4-adress. Then use any site IP-tracker to find the location. (like ipstack)

Evocation answered 13/4, 2020 at 6:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.