using GPSBusiness.Model; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace GPSBusiness.Helper { public static class MapHelper { private const string key = "89981abaf32ae94b09a639c54845e089"; //高德 private const string ak = "gxoEbH7Fj52wc1LVwRsGGOC5"; //百度 private const string txkey = "WANBZ-6C56D-6P34Y-HWNMG-YHAH7-BJFP5"; //腾讯 /// /// 传入经度纬度 /// /// 经度 /// 纬度 public static string GetLonLatUrl(string lat, string lon) { string LonLat = ""; string url = "http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x=" + lon + "&y=" + lat + ""; System.Net.HttpWebRequest requst = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);//http传输协议 System.Net.HttpWebResponse respone = (System.Net.HttpWebResponse)requst.GetResponse();//活的http的网络资源 System.IO.Stream stream = respone.GetResponseStream();//转换成字节流 System.IO.StreamReader sr = new System.IO.StreamReader(stream, Encoding.GetEncoding("utf-8"));//已utf-8模式读取数据 string responestr = sr.ReadToEnd(); sr.Close(); sr.Dispose();//释放资源 string[] responeArr = responestr.Split('\"'); if (responeArr.Length >= 11) { LonLat = GetbyBase64("utf-8", responeArr[5]) + "," + GetbyBase64("utf-8", responeArr[9]); } return LonLat; } /// /// 解析base64信息数据 /// /// 解析编码格式 /// 传入的base64位值 /// public static string GetbyBase64(string code_type, string code) { string decode = ""; byte[] bytes = Convert.FromBase64String(code); try { decode = Encoding.GetEncoding(code_type).GetString(bytes); } catch { decode = code; } return decode; } /// /// 根据经纬度获取地图信息(高德) /// /// 超时时间默认10秒 /// 经纬度字符串 /// 失败返回"" public static MapLocation GetMapLocation(string strLatLng, int timeout = 10000) { try { string url = string.Format("http://restapi.amap.com/v3/geocode/regeo?key={0}&batch=true&location={1}", key, strLatLng); string apiText = HttpGet(url, timeout); return JObject.Parse(apiText).ToObject(); } catch (Exception) { return new MapLocation(); } } /// /// 根据经纬度获取地图信息(腾讯) /// /// 超时时间默认10秒 /// 经纬度字符串 /// 失败返回"" public static TXMapLocation GetTXMapLocation(string strLatLng, int timeout = 10000) { try { string url = string.Format("https://apis.map.qq.com/ws/place/v1/search?boundary=nearby({0},1000)&key={1}",strLatLng, txkey); //string.Format("https://apis.map.qq.com/ws/geocoder/v1/?location={0}&key={1}&get_poi=0", // strLatLng, txkey); string apiText = HttpGet(url, timeout); return JObject.Parse(apiText).ToObject(); } catch (Exception) { return new TXMapLocation(); } } /// /// 根据经纬度获取地址,多个 /// /// 超时时间默认10秒 /// 经纬度数组 /// 1、获取详细地址2、获取市跟区 /// 失败返回"" public static List GetLocationByLngLat(List lngLatList, int timeout = 10000, int type = 1) { int idx = 0; List lstAddress = new List(); List listLatLng = new List(); try { for (int i = 0; i < lngLatList.Count; i++) { LocationModel item = lngLatList[i]; if (idx < 20 && i < lngLatList.Count - 1) { listLatLng.Add(item.LngLatStr); idx++; } else { if (i == lngLatList.Count - 1) { listLatLng.Add(item.LngLatStr); } if (i < lngLatList.Count - 1) { i--; //请求地址时,i递增的话会导致每次请求遗漏1个地址 } idx = 0; string strLatLng = string.Join("|", listLatLng); MapLocation mapLocation = GetMapLocation(strLatLng); if (Convert.ToInt32(mapLocation.Status) == 1) { switch (type) { case 2: lstAddress.AddRange( mapLocation.Regeocodes.Select( x => x.AddressComponent.City.ToString().Replace("[]", "").Replace("市", "") + ( !string.IsNullOrWhiteSpace( x.AddressComponent.District.ToString().Replace("[]", "")) ? x.AddressComponent.District.ToString().Replace("[]", "") : x.AddressComponent.Township.ToString().Replace("[]", "")) + "|" + x.AddressComponent.Adcode)); break; default: lstAddress.AddRange( mapLocation.Regeocodes.Select( x => x.FormattedAddress.ToString().Replace("[]", ""))); break; } } else { //TODO 当第一个经纬度错误的时候会失败,之后有空回来解决这个问题 for (int j = 0; j < listLatLng.Count - 1; j++) { lstAddress.Add(""); } } listLatLng = new List(); } } } catch (Exception) { lstAddress = new List { "未知" }; } return lstAddress; } /// /// 根据经纬度获取地址,一个 /// /// /// /// 超时时间默认10秒 /// /// 失败返回"" public static string GetLocationByLngLat(decimal longitude = 0, decimal latitude = 0, int type = 1, int timeout = 10000) { string address = ""; try { string strLatLng = longitude + "," + latitude; MapLocation mapLocation = GetMapLocation(strLatLng); if (Convert.ToInt32(mapLocation.Status) == 1) { Regeocode map = mapLocation.Regeocodes.First(); switch (type) { case 2: address = map.AddressComponent.City.ToString().Replace("[]", "").Replace("市", "") + (!string.IsNullOrWhiteSpace(map.AddressComponent.District.ToString() .Replace("[]", "")) ? map.AddressComponent.District.ToString().Replace("[]", "") : map.AddressComponent.Township.ToString().Replace("[]", "")) + "|" + map.AddressComponent.Adcode; break; default: address = map.FormattedAddress.ToString().Replace("[]", ""); break; } } if (Convert.ToInt32(mapLocation.Status) == 0) { } } catch (Exception) { address = ""; } return address; } /// /// 根据经纬度获取地址,一个(腾讯) /// /// /// /// 超时时间默认10秒 /// /// 失败返回"" public static string GetTXLocationByLngLat(decimal longitude = 0, decimal latitude = 0, int type = 1, int timeout = 10000) { string address = ""; try { string strLatLng = latitude + "," + longitude; TXMapLocation mapLocation = GetTXMapLocation(strLatLng); if (Convert.ToInt32(mapLocation.Status) == 0) { address = mapLocation.Data[0].Address.ToString(); } if (Convert.ToInt32(mapLocation.Status) == 1) { } } catch (Exception) { address = ""; } return address; } /// /// 根据经纬度获取区域代码 /// /// 纬度 /// 经度 /// 超时秒数 /// public static int GetRegionCodeByLatLng(decimal lat, decimal lng, int timeout = 10000) { try { int regionCode = 0; string strLatLng = lat + "," + lng; string url = string.Format( "http://api.map.baidu.com/geocoder/v2/?location={0}&latest_admin=1&output=json&pois=1&ak={1}", strLatLng, ak); string apiText = HttpGet(url, timeout); JObject jsonObj = JObject.Parse(apiText); if ((int)(jsonObj["status"]) == 0)//成功返回0 { regionCode = Convert.ToInt32(jsonObj["result"]["addressComponent"]["adcode"]); } return regionCode; } catch (Exception) { return 0; } } /// /// 获取路径规划路线 /// /// 起点经度 /// 起点纬度 /// 终点经度 /// 终点纬度 /// 超时时间默认10秒 /// 失败返回"" public static List GetRouteList(decimal startLongitude, decimal startLatitude, decimal endLongitude, decimal endLatitude, int timeout = 10000) { try { string origin = startLongitude + "," + startLatitude; string destination = endLongitude + "," + endLatitude; PathPlanning pathPlanning = GetPathPlanning(origin, destination); List list = new List(); if (Convert.ToInt32(pathPlanning.Status) == 1) { Model.Path path = pathPlanning.Routes.Paths.FirstOrDefault(); if (path != null) { string[] lineList = string.Join(";", path.Steps.Select(x => x.Polyline)).Split(';'); list.AddRange( lineList.Select( x => new PointLatLng (Convert.ToDouble(x.Split(',')[1]), Convert.ToDouble(x.Split(',')[0])))); } return list; } } catch (Exception) { return new List(); } return new List(); } /// /// 根据起点终点经纬度获取路径规划(步行)(高德) /// /// 终点经纬度 /// 超时时间默认10秒 /// 起点经纬度 /// 失败返回"" public static PathPlanning GetPathPlanning(string origin, string destination, int timeout = 10000) { try { string url = string.Format("https://restapi.amap.com/v3/direction/walking?key={0}&origin={1}&destination={2}", key, origin, destination); string apiText = HttpGet(url, timeout); return JObject.Parse(apiText).ToObject(); } catch (Exception) { return new PathPlanning(); } } public static string HttpGet(string url, int timeout) { HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest; req.ContentType = "multipart/form-data"; req.Accept = "*/*"; req.UserAgent = ""; req.Timeout = timeout; req.Method = "GET"; req.KeepAlive = true; HttpWebResponse response = req.GetResponse() as HttpWebResponse; string apiText = ""; using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { apiText = sr.ReadToEnd(); } return apiText; } public static GDPointLatLng Gps84ToGD(double lat,double lng, int timeout = 10000) { try { string url = string.Format("https://restapi.amap.com/v3/assistant/coordinate/convert?key=82c0ac5c67dc9b13a3bb5b8fd4813996&locations={0}&coordsys=gps", lng + "," + lat); string apiText = HttpGet(url,timeout); return JObject.Parse(apiText).ToObject(); } catch (Exception) { return new GDPointLatLng() ; } } public static GpsModels.BaseStationModel GetBaseStation(int mcc, int mnc, long lac, long cellid) { try { string url = string.Format("http://apilocate.amap.com/position?accesstype=0&cdma=0&bts={0},{1},{2},{3},50&output=json&key={4}", mcc, mnc, lac, cellid, key); string apiText = HttpGet(url, 10000); return JObject.Parse(apiText).ToObject(); } catch (Exception) { return new GpsModels.BaseStationModel(); } } } }