Unity调用百度接口获取当前IP的所在地以及经纬度

本文介绍如何在Unity中调用百度地图API来获取用户的地理位置信息,包括城市名称及经纬度坐标。通过示例代码展示了从请求地理信息到解析JSON响应数据的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近有在研究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;
    }
}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值