公司要做一个根据经纬度得到距离的功能,开始时用的百度地图API,很方便。后来根据要求,不使用百度地图API。在网上也找了很多资料,搜索结果一页一页的翻了10来页,终于找到一个,这个的精度和百度地图API的精度最接近。在此做了一个JS版的和C#版 的,供大家按需摘取
JS版
C#版<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>测距</title> <script src="Scripts/jquery-1.4.4.min.js" type="text/javascript"></script> </head> <body> <div id="allmap"></div> <div id = "dv"> <table id = "tb"> <tr> <td></td> <td>经度</td> <td>纬度</td> </tr> <tr> <td>起点坐标</td> <td><input type = "text" id = "aLon" value ="106.583815" /></td> <td><input type = "text" id = "aLat" value="29.426896" /></td> </tr> <tr> <td>终点坐标</td> <td><input type = "text" id = "bLon" value="106.546445"/></td> <td><input type = "text" id = "bLat" value = "29.502367"/></td> </tr> <tr> <td><input type = "button" id = "btnCal" value = "计算距离" /></td> <td colspan = "2"><center><input type = "text" id = "lbResult" size = "46"/></center></td> </tr> </table> </div> </body> </html> <script type="text/javascript"> $(function () { $("#btnCal").click(function () { //起点经纬 var a1 = $("#aLon").val(); var a2 = $("#aLat").val(); //终点经纬 var b1 = $("#bLon").val(); var b2 = $("#bLat").val(); //测距 var distance = GetDistance(a1, a2, b1, b2); $("#lbResult").val(distance + "米"); }); function rad(d) { return d * Math.PI / 180.0; } function GetDistance(lng1, lat1, lng2, lat2) { var radLat1 = rad(lat1); var radLat2 = rad(lat2); var a = radLat1 - radLat2; var b = rad(lng1) - rad(lng2); var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2))); s = s * 6378137; s = Math.round(s * 10000) / 10000; return s; } }); </script>
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { double distance = GetDistance(106.583815, 29.426896, 106.546445, 29.502367); Console.WriteLine(distance + "米"); Console.ReadKey(); } private static double EARTH_RADIUS = 6378137; private static double rad(double d) { return d * Math.PI / 180.0; } public static double GetDistance(double lng1, double lat1, double lng2, double lat2) { double radLat1 = rad(lat1); double radLat2 = rad(lat2); double a = radLat1 - radLat2; double b = rad(lng1) - rad(lng2); double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) + Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2))); s = s * EARTH_RADIUS; s = Math.Round(s * 10000) / 10000; return s; } } }