using RestSharp;
using System.Text;
using System;
using System.Threading.Tasks;
using Adrenak.Unex;
using UnityEngine;
namespace Adrenak.UniMap {
///
/// Used to get the coordinates of an address
///
public class GeocodingRequest {
const string k_BaseURL = "https://maps.googleapis.com/maps/api/geocode/json?";
///
/// The Google Maps API key
///
public string Key { get; private set; }
///
/// The address to request
///
public string Address { get; private set; }
///
/// Language of the request
///
public string Language { get; set; }
///
/// ISO code of the region
///
public string Region { get; set; }
///
/// Creates an instance for geocoding request
///
/// The Google Maps API key to be used
public GeocodingRequest(string key) {
Key = key;
}
///
/// Gets the request URL for the set parameters
///
public string GetURL() {
if (Key.IsNullOrEmpty())
throw new Exception("No key provided");
if (Address.IsNullOrEmpty())
throw new Exception("No address provided");
var builder = new StringBuilder(k_BaseURL);
builder.Append("key=").Append(Key);
builder.Append("&address=").Append(Address);
if (!Language.IsNullOrEmpty())
builder.Append("&language=").Append(Language);
if (!Region.IsNullOrEmpty())
builder.Append("®ion=").Append(Region);
return builder.ToString();
}
///
/// Sends the request for a given address
///
/// The address that needs to be geocoded
/// Callback on successful request
/// Callback on unsuccessul request
public void Send(string address, Action onSuccess, Action onFailure) {
Address = address;
var client = new RestClient();
var request = new RestRequest(GetURL(), Method.GET);
client.ExecuteAsync(request, response => {
Dispatcher.Enqueue(() => {
if (response.IsSuccessful()) {
var model = JsonUtility.FromJson(response.Content);
if (model != null)
onSuccess?.Invoke(model);
else {
var exception = new Exception("Could not deserialize", response.GetException());
onFailure?.Invoke(exception);
}
}
else {
var exception = new Exception("Unsuccessful response for Geocoding", response.GetException());
onFailure?.Invoke(exception);
}
});
});
}
///
/// Sends the request for a given address and returns a task for the response
///
/// The address that needs to be goecoded
/// The promise for the response
public Task Send(string address) {
var source = new TaskCompletionSource();
Send(
address,
response => source.SetResult(response),
exception => source.SetException(exception)
);
return source.Task;
}
}
}