2019独角兽企业重金招聘Python工程师标准>>>
string startLonLat = SiteHelper.GetLonLat("大连"); //获取起始地经度纬度
string endLonLat = SiteHelper.GetLonLat("沈阳"); //获取目的地经度纬度
int distance = SiteHelper.GetDistance(startLonLat, endLonLat); //计算2个地址的距离(单位千米)
/// <summary>
/// 获取经度纬度
/// </summary>
/// <param name="address">地址</param>
/// <returns></returns>
public static string GetLonLat(string address)
{
#region 返回数据格式
//{
// "status":"1",
// "info":"OK",
// "infocode":"10000",
// "count":"1",
// "geocodes":[
// {
// "formatted_address":"浙江省杭州市西湖区",
// "province":"浙江省",
// "citycode":"0571",
// "city":"杭州市",
// "district":"西湖区",
// "township":Array[0],
// "neighborhood":Object{...},
// "building":Object{...},
// "adcode":"330106",
// "street":Array[0],
// "number":Array[0],
// "location":"120.130203,30.259324",
// "level":"区县"
// }
// ]
//}
//{
// "status":"0",
// "info":"INVALID_USER_KEY",
// "infocode":"10001"
//}
#endregion
string queryUrl = "http://restapi.amap.com/v3/geocode/geo?key=6119e85de0fa6a97be90a0af41f0613c7&address=" + address; //高德接口
string queryResult = Utils.HttpGet(queryUrl); //请求接口数据
string location = string.Empty; //经度纬度
JsonData jd = JsonMapper.ToObject(queryResult);//字符串转换成json格式
int status = Utils.ObjToInt(jd["status"], 0);//查询结果 1:成功 0:失败
if (status == 1) //成功
{
JsonData list = jd["geocodes"];
if (list.Count > 0)
{
location = Utils.ObjectToStr(list[0]["location"]); //获取经度纬度
}
}
return location;
}
/// <summary>
/// 获取2个地址的距离
/// </summary>
/// <param name="startLonLat">起始地经度纬度</param>
/// <param name="endLonLat">目的地经度纬度</param>
/// <returns></returns>
public static int GetDistance(string startLonLat, string endLonLat)
{
#region 返回数据格式
//{
// "status":"1",
// "info":"OK",
// "infocode":"10000",
// "results":[
// {
// "origin_id":"1",
// "dest_id":"1",
// "distance":"936631",
// "duration":"37140"
// }
// ]
//}
#endregion
int duration = 0; //起始地与目的地之间的距离
string queryUrl = "http://restapi.amap.com/v3/distance?key=6119e85defa6a97be090a0af41f0613c7&origins=" + startLonLat + "&destination=" + endLonLat; //高德接口
string queryResult = Utils.HttpGet(queryUrl); //请求接口数据
JsonData jd = JsonMapper.ToObject(queryResult);//字符串转换成json格式
int status = Utils.ObjToInt(jd["status"], 0);//查询结果 1:成功 0:失败
if (status == 1) //成功
{
JsonData list = jd["results"];
if (list.Count > 0)
{
duration = Convert.ToInt32(Convert.ToInt64(list[0]["distance"].ToString()) / 1000);
}
}
return duration;
}