Skip to content

Commit

Permalink
增加高德地图和腾讯地图的单元测试
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Mar 20, 2024
1 parent f78aff8 commit 333285f
Show file tree
Hide file tree
Showing 6 changed files with 207 additions and 21 deletions.
25 changes: 18 additions & 7 deletions NewLife.Map/AMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,10 @@ public async Task<GeoAddress> GetGeoAsync(String address, String city = null, St

{
var addr = rs["formatted_address"] + "";
if (!addr.IsNullOrEmpty()) geo.Address = addr;
if (!addr.IsNullOrEmpty() && (geo.Address.IsNullOrEmpty() || geo.Address.Length < addr.Length))
geo.Address = addr;
}

// 替换竖线
TrimAddress(geo);

Expand Down Expand Up @@ -170,18 +172,19 @@ public async Task<GeoAddress> GetReverseGeoAsync(GeoPoint point, String coordtyp

var geo = new GeoAddress
{
Address = rs["formatted_address"] + ""
};
geo.Location = new GeoPoint
{
Longitude = point.Longitude,
Latitude = point.Latitude
Address = rs["formatted_address"] + "",
Location = point
};
if (rs["addressComponent"] is IDictionary<String, Object> component)
{
var reader = new JsonReader();
reader.ToObject(component, null, geo);

if (component.TryGetValue("city", out var obj) && obj is not String)
geo.City = null;
if (component.TryGetValue("streetNumber", out obj) && obj is not String)
geo.StreetNumber = null;

geo.Code = component["adcode"].ToInt();

geo.Township = null;
Expand All @@ -199,6 +202,14 @@ public async Task<GeoAddress> GetReverseGeoAsync(GeoPoint point, String coordtyp
{
geo.Street = sn["street"] + "";
geo.StreetNumber = sn["number"] + "";

if (geo.Title.IsNullOrEmpty())
{
if (!sn.TryGetValue("direction", out var direction)) direction = "";
if (sn.TryGetValue("distance", out var distance)) distance = Math.Round(distance.ToDouble(), 0) + "米";

geo.Title = $"{geo.Province}{geo.City}{geo.District}{geo.Township}{geo.Street}{geo.StreetNumber}{direction}{distance}";
}
}
}

Expand Down
4 changes: 2 additions & 2 deletions NewLife.Map/Map.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public interface IMap
#endregion

#region 地理编码
/// <summary>查询地址获取坐标</summary>
/// <summary>查询地址获取坐标。将地址转换为地理位置坐标</summary>
/// <param name="address">地址</param>
/// <param name="city">城市</param>
/// <param name="coordtype">所需要的坐标系</param>
Expand All @@ -37,7 +37,7 @@ public interface IMap
#endregion

#region 逆地理编码
/// <summary>根据坐标获取地址</summary>
/// <summary>根据坐标获取地址。将地理位置坐标转换为直观易懂的地址的过程</summary>
/// <param name="point">坐标</param>
/// <param name="coordtype">坐标系</param>
/// <returns></returns>
Expand Down
2 changes: 0 additions & 2 deletions NewLife.Map/NewLifeMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ namespace NewLife.Map;
public class NewLifeMap : Map, IMap
{
#region 属性
/// <summary>服务端地址</summary>
public String Server { get; set; }
#endregion

#region 构造
Expand Down
37 changes: 27 additions & 10 deletions NewLife.Map/WeMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ public async Task<GeoAddress> GetGeoAsync(String address, String city = null, St
var gp = new GeoPoint { Longitude = ds["lng"].ToDouble(), Latitude = ds["lat"].ToDouble() };

var geo = new GeoAddress();
geo.Location = gp;
var reader = new JsonReader();
reader.ToObject(rs, null, geo);

Expand All @@ -108,22 +109,26 @@ public async Task<GeoAddress> GetGeoAsync(String address, String city = null, St
}
}
geo.Confidence = rs["reliability"].ToInt() * 10;//可信度

geo.Location = gp;
geo.Level = rs["level"] + "";

if (formatAddress)
{
var geo2 = await GetReverseGeoAsync(gp, coordtype);
if (geo2 != null)
{
geo2.Comprehension = geo.Comprehension;
geo2.Confidence = geo.Confidence;
if (geo2.Level.IsNullOrEmpty()) geo2.Level = geo.Level;

geo = geo2;
if (geo.Level.IsNullOrEmpty()) geo.Level = rs["level"] + "";
}
}

if (geo.Address.IsNullOrEmpty())
{
geo.Address = $"{geo.Province}{geo.City}{geo.District}{geo.Street}{rs["title"]}";
}

// 替换竖线
if (!geo.Address.IsNullOrEmpty()) geo.Address = geo.Address.Replace("|", null);

Expand All @@ -143,7 +148,7 @@ public async Task<IDictionary<String, Object>> GetReverseGeocoderAsync(GeoPoint
{
if (point.Longitude < 0.1 || point.Latitude < 0.1) throw new ArgumentNullException(nameof(point));

var url = $"https://apis.map.qq.com/ws/geocoder/v1/?location={point.Latitude},{point.Longitude}&output=json";//&get_poi=1
var url = $"/ws/geocoder/v1/?location={point.Latitude},{point.Longitude}&output=json";//&get_poi=1

return await InvokeAsync<IDictionary<String, Object>>(url, "result");
}
Expand All @@ -157,11 +162,19 @@ public async Task<GeoAddress> GetReverseGeoAsync(GeoPoint point, String coordtyp
var rs = await GetReverseGeocoderAsync(point, coordtype);
if (rs == null || rs.Count == 0) return null;

var geo = new GeoAddress { Address = $"{rs["address"]}", Location = point };
var geo = new GeoAddress { Address = rs["address"] + "", Location = point };

if (rs["formatted_addresses"] is IDictionary<String, Object> formattedAddresses)
{
geo.Name = $"{formattedAddresses["recommend"]}";//推荐使用的地址描述,描述精确性较高
// 推荐使用的地址描述,描述精确性较高
geo.Name = formattedAddresses["recommend"] + "";

var addr = formattedAddresses["standard_address"] + "";
if (!addr.IsNullOrEmpty())
{
geo.Title = geo.Address;
geo.Address = addr;
}
}

if (rs["address_component"] is IDictionary<String, Object> component)
Expand Down Expand Up @@ -204,15 +217,19 @@ public async Task<Driving> GetDistanceAsync(GeoPoint origin, GeoPoint destinatio

if (type <= 0 || type > 3) type = 1;

var url = $"https://apis.map.qq.com/ws/distance/v1/?model={DrivingType(type)}&from={origin.Latitude},{origin.Longitude}&to={destination.Latitude},{destination.Longitude}&output=json";
var url = $"/ws/direction/v1/{DrivingType(type)}?from={origin.Latitude},{origin.Longitude}&to={destination.Latitude},{destination.Longitude}&output=json";

var list = await InvokeAsync<IDictionary<String, Object>>(url, "result");
if (list == null || list.Count == 0) return null;

if (list["elements"] is not IList<Object> elements) return null;
if (list["routes"] is not IList<Object> elements) return null;
if (elements.FirstOrDefault() is not IDictionary<String, Object> geo) return null;

var rs = new Driving { Distance = geo["distance"].ToInt(), Duration = geo["duration"].ToInt() };
var rs = new Driving
{
Distance = geo["distance"].ToInt(),
Duration = geo["duration"].ToInt() * 60
};
return rs;
}

Expand Down Expand Up @@ -244,7 +261,7 @@ private String DrivingType(Int32 type)
/// <returns></returns>
public async Task<IDictionary<String, Object>> IpLocationAsync(String ip)
{
var url = $"https://apis.map.qq.com/ws/location/v1/ip?ip={ip}";
var url = $"/ws/location/v1/ip?ip={ip}";

var dic = await InvokeAsync<IDictionary<String, Object>>(url, "result");
if (dic == null || dic.Count == 0) return null;
Expand Down
78 changes: 78 additions & 0 deletions XUnitTest/AMapTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using NewLife.Data;
using NewLife.Map;
using Xunit;

namespace XUnitTest;

public class AMapTests
{
private readonly AMap _map;
public AMapTests() => _map = new AMap { AppKey = "2aada76e462af71e1b67ba1df22d0fa4" };

[Fact]
public async void Geocoder()
{
var addr = "上海中心大厦";
var map = _map;
//var rs = await map.GetGeocoderAsync(addr);

//Assert.NotNull(rs);
//Assert.True(rs.ContainsKey("location"));

var ga = await map.GetGeoAsync(addr, null, null, false);

Assert.NotNull(ga);
Assert.Equal(121.505366, ga.Location.Longitude);
Assert.Equal(31.23351, ga.Location.Latitude);
Assert.Equal("上海市浦东新区上海中心大厦", ga.Address);
//Assert.True(ga.Confidence > 0);

ga = await map.GetGeoAsync(addr, null, null, true);

Assert.NotNull(ga);
Assert.Equal(121.505366, ga.Location.Longitude);
Assert.Equal(31.23351, ga.Location.Latitude);
Assert.Equal("上海市浦东新区陆家嘴街道上海中心大厦上海中心·上海之品商场", ga.Address);
Assert.Equal("上海市浦东新区陆家嘴街道银城中路501号东16米", ga.Title);
Assert.Equal(310115, ga.Code);
Assert.Equal(310115005, ga.Towncode);
}

[Fact]
public async void GetDistanceAsync()
{
var points = new List<GeoPoint>
{
new() { Longitude = 121.51199904625513, Latitude = 31.239184419374944 },
new() { Longitude = 114.21892734521, Latitude = 29.575429778924 }
};

var map = _map;
var drv = await map.GetDistanceAsync(points[0], points[1], "wgs84", 0);

Assert.NotNull(drv);
Assert.Equal(851357, drv.Distance);
Assert.True(Math.Abs(32190 - drv.Duration) < 600);
}

//[Fact]
//public async void ConvertAsync()
//{
// var points = new List<GeoPoint>
// {
// new() { Longitude = 121.51199904625513, Latitude = 31.239184419374944 },
// new() { Longitude = 114.21892734521, Latitude = 29.575429778924 }
// };

// var map = _map;
// var points2 = await map.ConvertAsync(points, "wgs84", "gcj02");

// Assert.NotNull(points2);

// Assert.Equal(points.Count, points2.Count);
// Assert.True(points2[0].Longitude > 0);
// Assert.True(points2[0].Latitude > 0);
//}
}
82 changes: 82 additions & 0 deletions XUnitTest/WeMapTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using NewLife;
using NewLife.Data;
using NewLife.Http;
using NewLife.Map;
using Xunit;

namespace XUnitTest;

public class WeMapTests
{
private readonly WeMap _map;
public WeMapTests() => _map = new WeMap { AppKey = "YGEBZ-BDCCX-AJG4X-ZUH6W-MESMV-P2BFF" };

[Fact]
public async void Geocoder()
{
var addr = "上海中心";
var map = _map;
//var rs = await map.GetGeocoderAsync(addr);

//Assert.NotNull(rs);
//Assert.True(rs.ContainsKey("location"));

var ga = await map.GetGeoAsync(addr, null, null, false);

Assert.NotNull(ga);
Assert.Equal(121.505406, ga.Location.Longitude);
Assert.Equal(31.233501, ga.Location.Latitude);
//Assert.Null(ga.Address);
Assert.True(ga.Confidence > 0);

ga = await map.GetGeoAsync(addr, null, null, true);

Assert.NotNull(ga);
Assert.Equal(121.505406, ga.Location.Longitude);
Assert.Equal(31.233501, ga.Location.Latitude);
Assert.Equal("上海市浦东新区陆家嘴银城中路501号", ga.Address);
Assert.Equal("上海市浦东新区花园石桥路", ga.Title);
Assert.Equal(310115, ga.Code);
//Assert.Equal(310115005, ga.Towncode);
}

[Fact]
public async void GetDistanceAsync()
{
var points = new List<GeoPoint>
{
new() { Longitude = 121.51199904625513, Latitude = 31.239184419374944 },
new() { Longitude = 114.21892734521, Latitude = 29.575429778924 }
};

var map = _map;
var drv = await map.GetDistanceAsync(points[0], points[1], "wgs84", 0);

Assert.NotNull(drv);
Assert.Equal(851907, drv.Distance);
Assert.True(Math.Abs(37020 - drv.Duration) < 600);
}

//[Fact]
//public async void ConvertAsync()
//{
// var points = new List<GeoPoint>
// {
// new() { Longitude = 121.51199904625513, Latitude = 31.239184419374944 },
// new() { Longitude = 114.21892734521, Latitude = 29.575429778924 }
// };

// var map = _map;
// var points2 = await map.ConvertAsync(points, "wgs84", "gcj02");

// Assert.NotNull(points2);

// Assert.Equal(points.Count, points2.Count);
// Assert.True(points2[0].Longitude > 0);
// Assert.True(points2[0].Latitude > 0);
//}
}

0 comments on commit 333285f

Please sign in to comment.