using Adrenak.Unex; using System; using System.Text; using System.Threading.Tasks; using UnityEngine; using RestSharp; namespace Adrenak.UniMap { public class PlacePhotoDownloader { const string k_BaseURL = "https://maps.googleapis.com/maps/api/place/photo?"; /// /// The Google Maps API key /// public string Key { get; set; } /// /// Reference ID of the image that has to be downloaded /// public string Reference { get; private set; } /// /// Maximum width of the image to be downloaded. Default: 512 /// public int MaxWidth { get; set; } = 512; /// /// Maximum height of the image to be downloaded. Default: 512 /// public int MaxHeight { get; set; } = 512; /// /// The TextureFormat of the texture that is downladed by the instance. Default: RGB565 /// public TextureFormat Format { get; set; } = TextureFormat.RGB565; /// /// Whether mip maps of the download texture are generated /// public bool IsMipMapped { get; set; } /// /// Creates an instance to download the images /// /// The Google API key public PlacePhotoDownloader(string key) { Key = key; } /// /// Gets the URL of the request given the current parameter values /// /// public string GetURL() { var builder = new StringBuilder(k_BaseURL); builder.Append("&key=").Append(Key) .Append("&photoreference=").Append(Reference) .Append("&maxheight=").Append(MaxHeight) .Append("&maxwidth=").Append(MaxWidth); return builder.ToString(); } /// /// Send the API request and returns the response or exception /// /// Action that returns the response as a c# object /// Action that returns the exception encountered in case of an error public void Download(string reference, Action onResult, Action onException) { Reference = reference; string url = string.Empty; try { url = GetURL(); } catch (Exception e) { onException(e); } var client = new RestClient(); var request = new RestRequest(url, Method.GET); client.ExecuteAsync(request, response => { Dispatcher.Enqueue(() => { if (response.IsSuccessful()) { var tex = new Texture2D(1, 1, Format, IsMipMapped); tex.LoadImage(response.RawBytes); onResult?.Invoke(tex); } else onException?.Invoke(response.GetException()); }); }); } /// /// Send the API request and return a task for the response /// public Task Download(string reference) { var source = new TaskCompletionSource(); Download( reference, result => source.SetResult(result), exception => source.SetException(exception) ); return source.Task; } } }