Golang语言社区--使用百度API获取经纬度

时间:2022-05-05
本文章向大家介绍Golang语言社区--使用百度API获取经纬度,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "time"
)

func init() {
    fmt.Println("Entry init!")
    return
}

func main() {
    fmt.Println("Entry main!")
    fJingDu, fWeiDu := Get_JWData_By_Ctiy("上海")
    fmt.Println("fJingDu:!", fJingDu)
    fmt.Println("fWeiDu:!", fWeiDu)
    time.Sleep(10 * time.Second)
    return
}

//百度赌徒API申请
//http://www.funboxpower.com/498.html

// 经纬度对照网址
//http://www.docin.com/p-655216087.html

// key
//pckg0S4gcS65cSZbRdlxyb4kTq3DIAsQ

// url
//http://api.map.baidu.com/geocoder?address=地址&output=输出格式类型&key=用户密钥&city=城市名

//http://api.map.baidu.com/geocoder?address=%E6%88%90%E9%83%BD&output=json&key=pckg0S4gcS65cSZbRdlxyb4kTq3DIAsQ&city=%E6%88%90%E9%83%BD

// {
//    "status":"OK",
//    "result":{
//        "location":{
//            "lng":104.047017,
//            "lat":30.645663
//        },
//        "precise":0,
//        "confidence":40,
//        "level":"u57ceu5e02"
//    }
//}

type JWData struct {
    Lng float64 // 经纬度
    Lat float64
}

type CtiyJWData struct {
    Location   JWData
    Precise    int
    Confidence int
    Level      string
}

type BodyData struct {
    Status string
    Result CtiyJWData
}

func Get_JWData_By_Ctiy(strCtiy string) (float64, float64) {
    fmt.Println("Entry Get_JWData_By_Ctiy!")
    resp, err := http.Get("http://api.map.baidu.com/geocoder?address=" + strCtiy + "&output=json&key=pckg0S4gcS65cSZbRdlxyb4kTq3DIAsQ&city=" + strCtiy)
    if err != nil {
        fmt.Println("http.Get err:", err.Error())
        return 0.0, 0.0
    }
    body, errbody := ioutil.ReadAll(resp.Body)
    if errbody != nil {
        fmt.Println("ioutil.ReadAll errbody:", errbody.Error())
        return 0.0, 0.0
    }
    fmt.Println("body:", string(body))
    // 解析数据
    st := &BodyData{}
    json.Unmarshal(body, &st)
    fmt.Println("st:", st.Status)
    fmt.Println("st:", st.Result.Precise)
    fmt.Println("st:", st.Result.Confidence)
    fmt.Println("st:", st.Result.Level)
    fmt.Println("st:", st.Result.Location.Lat)
    fmt.Println("st:", st.Result.Location.Lng)

    return st.Result.Location.Lat, st.Result.Location.Lng
}