【发布时间】:2019-08-15 14:02:18
【问题描述】:
我正在尝试通过获取给定位置(纬度、经度)的当前速度来使用 TomTomApi。对于每个位置,我需要生成一个 url 来执行获取请求。但是找不到一个好的方法来做到这一点。所以最后我想生成 5 个 url 并获得 5 个不同的数据(所以我的函数应该为每个位置返回 5 个当前速度)!
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);
}}
【问题讨论】:
-
一头雾水,把新的 url 发给你的请求例程
-
^^ 我已经尝试并找到了解决方案
标签: c# api unity3d get-request