百度地图开发工具类,包括计算坐标距离,坐标转换

本文介绍如何将微信坐标转换为百度地图坐标,并计算微信用户与数据库中位置记录之间的距离。通过API调用实现坐标转换,利用数学公式计算两点间距离,并按距离排序返回结果。
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;


namespace BaiDuMapDemo.Models
{
    public class Message
    {
        /// <summary>
        /// 返回最新的排序后的信息
        /// </summary>
        /// <param name="datas">已经计算距离当前位置长度,但是未排序的信息</param>
        /// <returns></returns>
        public string  SortText(string datas)
        {
            datas = datas.Replace("\\", "");
            var ss = JsonConvert.DeserializeObject(datas);
            List<NetModel> list = JsonConvert.DeserializeObject<List<NetModel>>(ss.ToString());
            list = list.OrderBy(p => Convert.ToDouble(p.longs)).ToList();
            string returnText = JsonConvert.SerializeObject(list);
            return returnText;
        }




        /// <summary>
        /// 微信坐标和数据库坐标比较距离,具体的操作方法
        /// </summary>
        /// <param name="lng"></param>
        /// <param name="lat"></param>
        /// <param name="lng1"></param>
        /// <param name="lng2"></param>
        /// <returns>dictionary中key为多少条数据,value为包含id,name,longs 的json数据</returns>
        public Dictionary<int,string> HowLongToMe(double lng, double lat)
        {
            TestBaiduMapEntities Entities = new TestBaiduMapEntities();
            List<Location> list = Entities.Location.Where(p => p.id > 1).ToList(); //数据库中Location表所有的数据
            //将微信坐标转换为百度坐标
            Dictionary<double, double> dic = ConvertToBaidu(lng, lat);
            var retText = "[";
            foreach(var item in list)
            {
                string howLong=CacleLong(dic.First().Key,dic.First().Value,item.Lng,item.Lat).ToString(); //计算出距离
                retText += "{\"id\":\"" + item.id + "\",\"name\":\"" + item.Name + "\",\"longs\":\"" + howLong + "\"},";
            }
            retText += "]";
            retText = retText.Replace(",]", "]");
            var ss = JsonConvert.DeserializeObject(retText);
            List<NetModel> listReturn = JsonConvert.DeserializeObject<List<NetModel>>(ss.ToString());
            listReturn = listReturn.OrderBy(p => Convert.ToDouble(p.longs)).ToList();
            string returnText = JsonConvert.SerializeObject(listReturn); //返回参数 returnText,即是dictionary中的string;
            Dictionary<int, string> returnDic = new Dictionary<int, string>();
            returnDic.Add(list.Count, returnText);
            return returnDic;
        }


        /// <summary>
        /// 将微信坐标转换为百度坐标
        /// </summary>
        /// <param name="lng"></param>
        /// <param name="lat"></param>
        /// <returns>百度坐标,key表示经度,value表示纬度</returns>
        public Dictionary<double, double> ConvertToBaidu(double lng, double lat)
        {
            Dictionary<double, double> dic = new Dictionary<double, double>();
            //转换前的GPS坐标  
            double x = 116.397428;
            double y = 39.90923;
            //google 坐标转百度链接 //http://api.map.baidu.com/ag/coord/convert?from=2&to=4&x=116.32715863448607&y=39.990912172420714&callback=BMap.Convertor.cbk_3694  
            //gps坐标的type=0  
            //google坐标的type=2  
            //baidu坐标的type=4  
            String path = "http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x=" + x + "+&y=" + y + "&callback=BMap.Convertor.cbk_7594";
            string res = SendDataByGET(path);
            if (res.IndexOf("(") > 0 && res.IndexOf(")") > 0)
            {
                int sint = res.IndexOf("(") + 1;
                int eint = res.IndexOf(")");
                int ls = res.Length;
                String str = res.Substring(sint, eint - sint);
                int errint = res.IndexOf("error") + 7;
                int enderr = res.IndexOf("error") + 8;
                String err = res.Substring(errint, 1);
                if ("0".Equals(err))
                {
                    int sx = str.IndexOf(",\"x\":\"") + 6;
                    int sy = str.IndexOf("\",\"y\":\"");
                    int endy = str.IndexOf("\"}");
                    int sl = str.Length;
                    string xp = str.Substring(sx, sy - sx);
                    string yp = str.Substring(sy + 7, endy - sy - 7);
                    byte[] outputb = Convert.FromBase64String(xp);
                    string XStr = Encoding.Default.GetString(outputb);
                    outputb = Convert.FromBase64String(yp);
                    string YStr = Encoding.Default.GetString(outputb);
                    dic.Add(Convert.ToDouble(XStr), Convert.ToDouble(YStr));
                }
            }
            return dic;
        }
      
        /// 通过GET方式发送数据  
        /// url  
        /// GET数据  
        /// GET容器  
        public string SendDataByGET(string Url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);


            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }


        /// <summary>
        /// 计算两个百度坐标的距离
        /// </summary>
        /// <param name="lng_a">当前位置的经度</param>
        /// <param name="lat_a">当前位置的纬度</param>
        /// <param name="lng_b">目标点的经度</param>
        /// <param name="lat_b">目标点的纬度</param>
        /// <returns></returns>
        public double CacleLong(double lng_a, double lat_a, double lng_b, double lat_b)
        {
            double pk = 180 / 3.14169;
            double a1 = lat_a / pk;
            double a2 = lng_a / pk;
            double b1 = lat_b / pk;
            double b2 = lng_b / pk;
            double t1 = Math.Cos(a1) * Math.Cos(a2) * Math.Cos(b1) * Math.Cos(b2);
            double t2 = Math.Cos(a1) * Math.Sin(a2) * Math.Cos(b1) * Math.Sin(b2);
            double t3 = Math.Sin(a1) * Math.Sin(b1);
            double tt = Math.Acos(t1 + t2 + t3);
            return 6366000 * tt;
        }


    }




    public class NetModel
    {
        public int id { get; set; }
        public string name { get; set; }
        public string longs { get; set; }
    }

}


数据库设计


id int Unchecked
Name nvarchar(500) Unchecked
Lng       float                              Unchecked
Lat     float                          Unchecked
SerachText nvarchar(500) Checked


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值