百度地图热⼒图--批量地址转换应⽤(基于百度api)需求:把外卖订餐地址做个⽤户分布热⼒图
⾸先从百度API的demo例⼦参考静态页⾯,其中数据格式是
然后我们就想把数据库⾥的地址批量转换但是百度API没有提供批量转换的接⼝。
但是我们到了百度webapi单个地址转换的接⼝
利⽤这个接⼝,在后台读取地址和统计个数,返回⼀个json
⽤HttpWebRequest去发起get请求返回json,在把返回的json转成对象
这⾥套了三层,所以数据结构构造成这样(⼀开始不这么写获取是null)
单个地址转换写好了,下⾯⽤⼀个list<T>装⼀下,foreach遍历依次赋值,⽤个⼀般处理程序得到json
最后把前台界⾯的数组换成ajax请求数据,要把async设置成false同步请求,不然就会跳过这⾥往下执⾏,这⾥⽤匿名函数返回⼀个数组最后结果
代码:
1public static T RequestApi<T>(string address)
2 {
3string apiUrl = "api.map.baidu/geocoder/v2/";
4string apiKey = "6Gra1QZ4gWrsrUgirWZ0Z1NdfFrh0mD3"; //
5string output = "json";
6
7 IDictionary<string, string> param = new Dictionary<string, string>();
8 param.Add("ak", apiKey);
9 param.Add("output", output);
10
11
12 param.Add("address", address);
13
14string result = string.Empty;
15
16//初始化⽅案信息实体类。
17 T info = default(T);
18try
19 {
20//以 Get 形式请求 Api 地址
21 result = HttpUtils.DoGet(apiUrl, param);
22 info = JsonHelper.FromJson<T>(result);
23 }
24catch (Exception)
26 info = default(T);
27throw;
28 }
29
30return info;
31 }
1public class HttpUtils
2 {
3///<summary>
4///执⾏HTTP GET请求。
5///</summary>
6///<param name="url">请求地址</param>
7///<param name="parameters">请求参数</param>
8///<returns>HTTP响应</returns>
9public static string DoGet(string url, IDictionary<string, string> parameters) 10 {
11if (parameters != null && parameters.Count > 0)
12 {
13if (url.Contains("?"))
14 {
15 url = url + "&" + BuildPostData(parameters);
16 }
17else
18 {
19 url = url + "?" + BuildPostData(parameters);
20 }
21 }
22
23 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
24 req.ServicePoint.Expect100Continue = false;
25 req.Method = "GET";
26 req.KeepAlive = true;
27 req.UserAgent = "Test";
28 req.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; 29
30 HttpWebResponse rsp = null;
31try
32 {
33 rsp = (HttpWebResponse)req.GetResponse();
34 }
35catch (WebException webEx)
36 {
37if (webEx.Status == WebExceptionStatus.Timeout)
38 {
39 rsp = null;
40 }
41 }
42
43if (rsp != null)
44 {
45if (rsp.CharacterSet != null)
46 {
47 Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet); 48return GetResponseAsString(rsp, encoding);
49 }
50else
51 {
52return string.Empty;
53 }
54 }
55else
56 {
57return string.Empty;
59 }
60
61///<summary>
62///把响应流转换为⽂本。
63///</summary>
64///<param name="rsp">响应流对象</param>
65///<param name="encoding">编码⽅式</param>
66///<returns>响应⽂本</returns>
67private static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
68 {
69 StringBuilder result = new StringBuilder();
70 Stream stream = null;
71 StreamReader reader = null;
72
73try
74 {
75// 以字符流的⽅式读取HTTP响应
76 stream = rsp.GetResponseStream();
77 reader = new StreamReader(stream, encoding);
78
79// 每次读取不⼤于256个字符,并写⼊字符串
80char[] buffer = new char[256];
81int readBytes = 0;
82while ((readBytes = reader.Read(buffer, 0, buffer.Length)) > 0)
83 {
84 result.Append(buffer, 0, readBytes);
85 }
86 }
87catch (WebException webEx)
88 {
89if (webEx.Status == WebExceptionStatus.Timeout)
90 {
91 result = new StringBuilder();
92 }
93 }
94finally
95 {
96// 释放资源
97if (reader != null) reader.Close();
98if (stream != null) stream.Close();
99if (rsp != null) rsp.Close();
100 }
101
102return result.ToString();
103 }
104
105///<summary>
106///组装普通⽂本请求参数。
107///</summary>
108///<param name="parameters">Key-Value形式请求参数字典。</param>
109///<returns>URL编码后的请求数据。</returns>
110private static string BuildPostData(IDictionary<string, string> parameters)
111 {
112 StringBuilder postData = new StringBuilder();
113bool hasParam = false;
114
115 IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator(); 116while (dem.MoveNext())
117 {
118string name = dem.Current.Key;
119string value = dem.Current.Value;
120// 忽略参数名或参数值为空的参数
121if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
124 {
125 postData.Append("&");
126 }
127
128 postData.Append(name);
129 postData.Append("=");
130 postData.Append(Uri.EscapeDataString(value));
131 hasParam = true;百度api接口
132 }
133 }
134
135return postData.ToString();
136 }
137
138 }
1public static class JsonHelper
2 {
3private static JsonSerializerSettings _jsonSettings;
4
5static JsonHelper()
6 {
7 IsoDateTimeConverter datetimeConverter = new IsoDateTimeConverter();
8 datetimeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
9
10 _jsonSettings = new JsonSerializerSettings();
11 _jsonSettings.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
12 _jsonSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
13 _jsonSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
14 _jsonSettings.Converters.Add(datetimeConverter);
15 }
16
17///<summary>
18///将指定的对象序列化成 JSON 数据。
19///</summary>
20///<param name="obj">要序列化的对象。</param>
21///<returns></returns>
22public static string ToJson(this object obj)
23 {
24try
25 {
26if (null == obj)
27return null;
28
29return JsonConvert.SerializeObject(obj, Formatting.None, _jsonSettings);
30 }
31catch (Exception ex)
32 {
33
34return null;
35 }
36 }
37
38///<summary>
39///将指定的 JSON 数据反序列化成指定对象。
40///</summary>
41///<typeparam name="T">对象类型。</typeparam>
42///<param name="json">JSON 数据。</param>
43///<returns></returns>
44public static T FromJson<T>(this string json)
45 {
46try
47 {
48return JsonConvert.DeserializeObject<T>(json, _jsonSettings);
50catch (Exception ex)
51 {
52
53
54return default(T);
55 }
56 }
57 }
最后结果:
1public static IEnumerable<JWCDTO> GetAllJW()
2 {
3 List<BigDataDTO> p = GetAll().ToList();
4
5 List<JWCDTO> list = new List<JWCDTO>(); ;
6foreach (BigDataDTO pp in p)
7 {
8string address = pp.Address;
9int count = pp.count;
10 BGDTO bg = Re.RequestApi<BGDTO>(address);
11if(bg==null)
12 {
13continue;
14 }
15string lat = bg.result.location.lat;
16string lng = bg.result.location.lng;
17 JWCDTO log = ToProductDTO(lat, lng, count);
18 list.Add(log);//list.Add(ToLog(row));
19
20 }
21
22return list;
23
24 }
JW.ashx:
1public class JW : IHttpHandler
2 {
3
4public void ProcessRequest(HttpContext context)
5 {
6 context.Response.ContentType = "application/json";
7 List<JWCDTO> p;
8 p = ReJson.GetAllJW().ToList();
9 context.Response.Write(new JavaScriptSerializer().Serialize(p));
10 }
11
12public bool IsReusable
13 {
14get
15 {
16return false;
17 }
18 }
19 }
前台页⾯:
1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ReJson.aspx.cs" Inherits="XZ.UI.Web.Admin.ReJson" %>
2
3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4
5 <html xmlns="/1999/xhtml">
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论