I'm trying to consume the TomTomApi by getting the currrentSpeed given for a location (lat,lon). For each location i need to generate an url to do a get request. But can't find a good way to do it. So in the end i would like to generate 5 urls and get 5 differents data (so my function should return 5 current speed one for each location )!
public class TomTomApiTrafficFlow: MonoBehaviour{
// parameter to set lat & lon + type of response (json) or the key providing by the api
[SerializeField]
const string lat = "50.843829";
[SerializeField]
const string lon = "4.369384";
[SerializeField]
const string typeFile = "json";// xml ou json
[SerializeField]
const string API_KEY = "API_KEY";
// Where to send our request
const string DEFAULT_URL = "https://api.tomtom.com/traffic/services/4/flowSegmentData/relative-delay/10/json/";
string targetUrl = DEFAULT_URL + "?key=" + API_KEY + "&point=" + lat + "," + lon;
// Keep track of what we got back
string recentData = "";
void Awake()
{
this.StartCoroutine(this.RequestRoutine(this.targetUrl,this.ResponseCallback ));
}
// Web requests are typically done asynchronously, so Unity's web request system
// returns a yield instruction while it waits for the response.
//
private IEnumerator RequestRoutine(string url, Action<string> callback = null)
{
//const string URL = "https://api.tomtom.com/traffic/services/4/flowSegmentData/relative-delay/10/json/" + "?key=" + API_KEY + "&point=" + lat + "," + lon;
// Using the static constructor
var request = UnityWebRequest.Get(url);
// Wait for the response and then get our data
yield return request.SendWebRequest();
var data = request.downloadHandler.text;
// This isn't required, but I prefer to pass in a callback so that I can
// act on the response data outside of this function
if (callback == null)
Debug.Log(callback);
callback(data);
}
// Callback to act on our response data
private void ResponseCallback(string data)
{
//List<string> LcurSpeed = new List<string>();
Debug.Log(data);
recentData = data;
JObject o = JObject.Parse(recentData.ToString());
JToken token = o.SelectToken("flowSegmentData.currentSpeed");
recentData = token.ToString();
}
// Old fashioned GUI system to show the example
void OnGUI()
{
this.targetUrl = GUI.TextArea(new Rect(0, 0, 500, 50), this.targetUrl);
GUI.TextArea(new Rect(0, 60, 50, 50), recentData);
}}