最近有在研究Unity接入地图的功能,碰巧领导有让做获取当前IP的城市信息以及经纬度,于是在查询了百度地图的相关接口后研究出功能,照例 代码贴出 作为自学笔记 记录一下
访问百度地图接口的代码:
public class Test : MonoBehaviour
{string url = "http://api.map.baidu.com/location/ip?ak=bretF4dm6W5gqjQAXuvP0NXW6FeesRXb&coor=bd09ll";
string text;
void Start()
{
StartCoroutine(Request());
}
// Update is called once per frame
void Update()
{
}
IEnumerator Request()
{
WWW www = new WWW(url);
yield return www;
if (string.IsNullOrEmpty(www.error))
{
Debug.Log(www.text);
ResponseBody req = JsonConvert.DeserializeObject<ResponseBody>(www.text);
Debug.Log(req.content.address_detail.city);
}
}
}
www.text是一串Json数据,下面贴上反序列化需要用的代码:
public class ResponseBody
{
public string address;
public Content content;
public int status;
}
public class Content
{
public string address;
public Address_Detail address_detail;
public Point point;
}
public class Address_Detail
{
public string city;
public int city_code;
public string district;
public string province;
public string street;
public string street_number;
public Address_Detail(string city, int city_code, string district, string province, string street, string street_number)
{
this.city = city;
this.city_code = city_code;
this.district = district;
this.province = province;
this.street = street;
this.street_number = street_number;
}
}
public class Point
{
public string x;
public string y;
public Point(string x, string y)
{
this.x = x;
this.y = y;
}
}