zoukankan      html  css  js  c++  java
  • 百度api:根据经纬度获取地理位置信息

    调用百度api,根据经度和纬度获取地理位置信息,返回Json。

    C#代码:

    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System;
    using System.Net.Http;
    
        public class LocationService
        {
            //百度api
            private static string url = @"http://api.map.baidu.com/geocoder/v2/?location={0}&output=json&ak=WEc8RlPXzSifaq9RHxE1WW7lRKgbid6Y";
    
            /// <summary>
            /// 根据经纬度获取地理位置
            /// </summary>
            /// <param name="lat">纬度</param>
            /// <param name="lng">经度</param>
            /// <returns>具体的地埋位置</returns>
            public static string GetLocation(string lat, string lng)
            {
                HttpClient client = new HttpClient();
                string location = string.Format("{0},{1}", lat, lng);
                string bdUrl = string.Format(url, location);
                string result = client.GetStringAsync(bdUrl).Result;
                var locationResult = (JObject)JsonConvert.DeserializeObject(result);
    
                if (locationResult == null || locationResult["result"] == null || locationResult["result"]["formatted_address"] == null)
                    return string.Empty;
    
                var address = Convert.ToString(locationResult["result"]["formatted_address"]);
                if (locationResult["result"]["sematic_description"] != null)
                    address += " " + Convert.ToString(locationResult["result"]["sematic_description"]);
                return address;
            }
        }

    调用示例1:

    LocationService.GetLocation("0","0")

    返回Json:

    {{  "country": "",  "country_code": -1,  "province": "",  "city": "",  "district": "",  "adcode": "0",  "street": "",  "street_number": "",  "direction": "",  "distance": ""}}

    调用示例2:

    LocationService.GetLocation("36.2585", "120.27")

    返回Json:

     {{  "status": 0,  "result": {    "location": {      "lng": 120.26999999999993,      "lat": 36.25849989472075    },    "formatted_address": "山东省青岛市城阳区和融路",    "business": "上马",    "addressComponent": {      "country": "中国",      "country_code": 0,      "province": "山东省",      "city": "青岛市",      "district": "城阳区",      "adcode": "370214",      "street": "和融路",      "street_number": "",      "direction": "",      "distance": ""    },    "pois": [],    "roads": [],    "poiRegions": [],    "sematic_description": "青岛宝佳自动化设备有限公司北575米",    "cityCode": 236  }}}

    =================================================================

    以下内容转自他人博客,返回xml格式的例子

    博客地址:http://www.cnblogs.com/_zjl/p/3431525.html

    代码:

     private string GetAddress(string lng, string lat)
            {
                try
                {
                    string url = @"http://api.map.baidu.com/geocoder/v2/?ak=E4805d16520de693a3fe707cdc962045&callback=renderReverse&location=" + lat + "," + lng + @"&output=xml&pois=1";
                    WebRequest request = WebRequest.Create(url);
                    request.Method = "POST";
                    XmlDocument xmlDoc = new XmlDocument();
                    string sendData = xmlDoc.InnerXml;
                    byte[] byteArray = Encoding.Default.GetBytes(sendData);
    
                    Stream dataStream = request.GetRequestStream();
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    dataStream.Close();
    
                    WebResponse response = request.GetResponse();
                    dataStream = response.GetResponseStream();
                    StreamReader reader = new StreamReader(dataStream, System.Text.Encoding.GetEncoding("utf-8"));
                    string responseXml = reader.ReadToEnd();
    
                    XmlDocument xml = new XmlDocument();
                    xml.LoadXml(responseXml);
                    string status = xml.DocumentElement.SelectSingleNode("status").InnerText;
                    if (status == "0")
                    {
    
                        XmlNodeList nodes = xml.DocumentElement.GetElementsByTagName("formatted_address");
                        if (nodes.Count > 0)
                        {
                            return nodes[0].InnerText;
                        }
                        else
                            return "未获取到位置信息,错误码3";
                    }
                    else
                    {
                        return "未获取到位置信息,错误码1";
                    }
                }
                catch (System.Exception ex)
                {
                    return "未获取到位置信息,错误码2";
                }
            }
    

     

    url中的参数:

    参数是否必须默认值格式举例含义
    coordtype bd09ll bd09ll 百度经纬度坐标 坐标的类型,目前支持的坐标类型包括:bd09ll(百度经纬度坐标)、gcj02ll(国测局经纬度坐标)、wgs84ll( GPS经纬度)
    location 38.76623,116.43213 lat<纬度>,lng<经度> 根据经纬度坐标获取地址
    pois 0 0 是否显示指定位置周边的poi,0为不显示,1为显示。当值为1时,显示周边100米内的poi。

    运行方法返回的结果:

    北京市海淀区中关村大街27号1101-08室

    从百度api返回的结果:

      <?xml version="1.0" encoding="utf-8" ?> 
    - <GeocoderSearchResponse>
      <status>0</status> 
    - <result>
    - <location>
      <lat>39.983424051248</lat> 
      <lng>116.32298703399</lng> 
      </location>
      <formatted_address>北京市海淀区中关村大街27号1101-08室</formatted_address> 
      <business>中关村,人民大学,苏州街</business> 
    - <addressComponent>
      <streetNumber /> 
      <street>中关村大街</street> 
      <district>海淀区</district> 
      <city>北京市</city> 
      <province>北京市</province> 
      </addressComponent>
      <cityCode>131</cityCode> 
    - <pois>
    - <poi>
      <addr>中关村西区南侧(中关村科技园区内)</addr> 
      <distance>0.050000</distance> 
      <name>中关村大厦</name> 
      <poiType>办公大厦,商务大厦</poiType> 
      <tel>(010)82856666</tel> 
      <zip>100000</zip> 
    - <point>
      <x>116.32298658484</x> 
      <y>39.983423843929</y> 
      </point>
      </poi>
    - <poi>
      <addr>中关村大街27号</addr> 
      <distance>0.050000</distance> 
      <name>眉州东坡酒楼中关村店</name> 
      <poiType>中餐馆,餐饮</poiType> 
      <tel>(010)82856948</tel> 
      <zip /> 
    - <point>
      <x>116.32298658484</x> 
      <y>39.983423843929</y> 
      </point>
      </poi>
    - <poi>
      <addr>中关村大街27号</addr> 
      <distance>0.050000</distance> 
      <name>中国人民财产保险中关村营业部</name> 
      <poiType>中国人民财产保险,保险公司,金融</poiType> 
      <tel>(010)82856779</tel> 
      <zip>100000</zip> 
    - <point>
      <x>116.32298658484</x> 
      <y>39.983423843929</y> 
      </point>
      </poi>
    - <poi>
      <addr>北京市海淀区</addr> 
      <distance>94.432081</distance> 
      <name>光合作用书房</name> 
      <poiType>图书音像,购物</poiType> 
      <tel /> 
      <zip /> 
    - <point>
      <x>116.32239334388</x> 
      <y>39.983890240676</y> 
      </point>
      </poi>
    - <poi>
      <addr>中关村大街27号</addr> 
      <distance>42.195731</distance> 
      <name>建行中关村支行</name> 
      <poiType>中国建设银行,银行,金融</poiType> 
      <tel /> 
      <zip>100000</zip> 
    - <point>
      <x>116.32292037972</x> 
      <y>39.983711118168</y> 
      </point>
      </poi>
    - <poi>
      <addr>北京市海淀区</addr> 
      <distance>62.342644</distance> 
      <name>海淀医院-激光整形美容部</name> 
      <poiType>美容美发,生活服务</poiType> 
      <tel /> 
      <zip /> 
    - <point>
      <x>116.32317954086</x> 
      <y>39.98301950182</y> 
      </point>
      </poi>
    - <poi>
      <addr>中关村大街19号新中关购物中心1楼</addr> 
      <distance>112.983688</distance> 
      <name>星巴克新中关店</name> 
      <poiType>星巴克,咖啡厅,休闲餐饮,餐饮</poiType> 
      <tel>(010)82486056</tel> 
      <zip /> 
    - <point>
      <x>116.32218215226</x> 
      <y>39.983899777278</y> 
      </point>
      </poi>
      </pois>
      </result>
      </GeocoderSearchResponse>

    xml说明:

    名称类型说明
    status constant 返回结果状态值, 成功返回0,其他值请查看附录
    location lat 纬度坐标
    lng 经度坐标
    formatted_address 结构化地址信息
    business 所在商圈信息,如 "人民大学,中关村,苏州街"
    addressComponent city 城市名
    district 区县名
    province 省名
    street 街道名
    street_number 街道门牌号
    pois(周边poi数组) addr 地址信息
    cp 数据来源
    distance 离坐标点距离
    name poi名称
    poiType poi类型,如’ 办公大厦,商务大厦’
    point poi坐标{x,y}
    tel 电话
    uid poi唯一标识
    zip 邮编

    附录:

    返回码定义
    0 正常
    1 服务器内部错误
    2 请求参数非法
    3 权限校验失败
    4 配额校验失败
    5 ak不存在或者非法
    101 服务禁用
    102 不通过白名单或者安全码不对
    2xx 无权限
    3xx 配额错误

     

  • 相关阅读:
    WPF概述(硬件加速及分辨率无关性)
    创建自己的Code Snippet(代码模板)
    [LeetCode]46. Restore IP Addresses复原IP地址
    [LeetCode]45. Reverse Words in a String按单词翻转字符串
    [LeetCode]44. Implement strStr()实现strStr()函数
    [LeetCode]43. Integer to Roman整数转罗马数字
    [LeetCode]42. Roman to Integer罗马数字转整数
    [LeetCode]41. String to Integer(atoi)字符串转整数
    [LeetCode]40. Valid Palinadrome有效回文串
    [LeetCode]39. Longest Valid Parentheses最长有效括号对
  • 原文地址:https://www.cnblogs.com/xianhan/p/7171134.html
Copyright © 2011-2022 走看看