【地图功能开发系列:二】根据地址名称通过百度地图API查询出坐标

根据地址名称通过百度地图API查询出坐标

百度地图ApiUrl

`string url = "http://api.map.baidu.com/geocoder?address={0}&output=json&key=这里用自己申请的key" ` ``` //查询出门店列表 string sql = "select shopid, shopName,shopadress, lat ,lng as lon from Shop"; //单个门店的情况 if (shopid!=0) { sql += " where shopid=" + shopid; }
    DataTable PlaceDt = kis_web.DBHelper.GetTable(sql);
    foreach (DataRow row in PlaceDt.Rows)
    {
      //请求
        var request = (HttpWebRequest)WebRequest.Create(string.Format(url, row["shopadress"]));
        var response = (HttpWebResponse)request.GetResponse();
        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
        //请求结果
        JObject jo = (JObject)JsonConvert.DeserializeObject(responseString);
        //有些地址是查询不出来result的,因此要做个判断
        if (string.Equals(jo["status"].ToString(), "OK") && jo["result"].ToString() != "[]")
        {
            string lat = jo["result"]["location"]["lat"].ToString();
            string lng = jo["result"]["location"]["lng"].ToString();
            //修改数据库中的门店坐标地址
            string updateSql = "UPDATE Shop SET lat = '{0}',lng = '{1}' WHERE shopid ='{2}'";
            int result = kis_web.DBHelper.ExeSQLs(string.Format(updateSql, lat, lng, row["shopid"]));
           
        }
    }
#测试DEMO可以直接赋值使用
    string url = "http://api.map.baidu.com/geocoder?address={0}&output=json&key=key";
    var request = (HttpWebRequest)WebRequest.Create(string.Format(url, "广州"));
    var response = (HttpWebResponse)request.GetResponse();
    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
    JObject jo = (JObject)JsonConvert.DeserializeObject(responseString);
    string lng = jo["result"]["location"]["lng"].ToString();
    string lat = jo["result"]["location"]["lat"].ToString();
    Response.Write(lng + "|" + lat);

---
*相关命名空间*

using Newtonsoft.Json;
using System.Net;
using Newtonsoft.Json.Linq;


*通过上诉的操作,这样就可以将数据库中拥有地址的门店赋值坐标*
posted @ 2019-04-24 17:33  君宁天下  阅读(1039)  评论(0编辑  收藏
野生程序员真的是太难了,一刻也不敢停止学习