一、注册高德开放平台账号,获取天气接口Key
1、构建自己的应用
网址:https://lbs.amap.com/api/webservice/guide/api/weatherinfo
最终调用api的地址形式:
https://restapi.amap.com/v3/weather/weatherInfo?city=110101&key=<用户key>
二、Unity中写算法进行调用
具体代码:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class GetWeather : MonoBehaviour
{
public string url;
public Button getweather;
public Text weatherInfo;
[Serializable]
public class LivesData
{
public string status;
public string count;
public string info;
public string infocode;
public lives[] lives;
}
// Start is called before the first frame update
void Start()
{
getweather.onClick.AddListener(GetWeatherInfo);
}
void GetWeatherInfo()
{
LoadNetJson<LivesData>(url,
(data) =>
{
weatherInfo.text = data.lives[0].province;
weatherInfo.text += data.lives[0].weather;
weatherInfo.text += data.lives[0].temperature + "°C";
weatherInfo.text += data.lives[0].winddirection + "风";
},
(error) =>
{
Debug.Log(error);
}
);
}
//读取网络Json
public void LoadNetJson<T>(string url, Action<T> onSuccess, Action<string> onError)
{
StartCoroutine(FetchDate(url, onSuccess, onError));
}
//等待网络返回携程
private IEnumerator FetchDate<T>(string url, Action<T> onSuccess, Action<string> onError)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
{
yield return webRequest.SendWebRequest();
if (webRequest.result != UnityWebRequest.Result.Success)
{
onError?.Invoke(webRequest.error);
}
else
{
string json = webRequest.downloadHandler.text;
T data = JsonUtility.FromJson<T>(json);
onSuccess?.Invoke(data);
}
}
}
}