Skip to content

Instantly share code, notes, and snippets.

@natsupy
Forked from sandcastle/GeoData.cs
Created July 16, 2018 00:33
Show Gist options
  • Save natsupy/503bc942b1cbc5a693f74a2e64e1c595 to your computer and use it in GitHub Desktop.
Save natsupy/503bc942b1cbc5a693f74a2e64e1c595 to your computer and use it in GitHub Desktop.
A Unity 3D behaviour for Geo location lookup via IP address
using UnityEngine;
using System.Collections;
using Newtonsoft.Json;
/// <summary>
/// The Geo data for a user.
///
/// http://ip-api.com/docs/api:json
///
/// <code>
/// {
/// "status": "success",
/// "country": "COUNTRY",
/// "countryCode": "COUNTRY CODE",
/// "region": "REGION CODE",
/// "regionName": "REGION NAME",
/// "city": "CITY",
/// "zip": "ZIP CODE",
/// "lat": LATITUDE,
/// "lon": LONGITUDE,
/// "timezone": "TIME ZONE",
/// "isp": "ISP NAME",
/// "org": "ORGANIZATION NAME",
/// "as": "AS NUMBER / NAME",
/// "query": "IP ADDRESS USED FOR QUERY"
/// }
/// </code>
///
/// </summary>
public class GeoData
{
/// <summary>
/// The status that is returned if the response was successful.
/// </summary>
public const string SuccessResult = "success";
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("query")]
public string IpAddress { get; set; }
}
public class GeoCountry : MonoBehaviour {
// Use this for initialization
void Start () {
HTTP.Request someRequest = new HTTP.Request( "get", "http://ip-api.com/json" );
someRequest.Send( ( request ) => {
// Get Geo data
GeoData data = null;
try {
data = request.response.Get<GeoData>();
}
catch (System.Exception ex) {
// TODO: Hook into an auto retry case
Debug.LogError("Could not get geo data: " + ex.ToString());
return;
}
// Ensure successful
if (data.Status != GeoData.SuccessResult) {
// TODO: Hook into an auto retry case
Debug.LogError("Unsuccessful geo data request: " + request.response.Text);
return;
}
Debug.Log ("User's Country: \"" + data.Country + "\"; Query: \"" + data.IpAddress + "\"");
});
}
// Update is called once per frame
void Update () {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment