我正在使用 Openlayers 并嘗試將幾何資訊保存在我的資料庫中。
當我在 openlayers 地圖上繪制多邊形時,生成的物件(特征)采用這種格式
{
"type": "Polygon",
"coordinates": [
[
[
54.86572265625,
74.0013854318592
],
[
53.59130859375,
73.62159408606237
],
[
53.96484375,
73.16953636227885
],
[
55.986328125,
73.59679245247814
]
]
]
}
上面的物件有 2 個屬性。 {type: string, coordinates: someNestedArray}
我將此物件傳遞給我的 API 以將其保存在資料庫中。但是我面臨著定義坐標屬性型別的問題。
基本上它是 float[][][] 型別,所以我創建了我的 EF 模型類,如下所示
public class Geometry
{
public string Type { get; set; }
public float[][][] Coordinates { get; set; }
}
當我嘗試獲取/更新時,EF 拋出以下錯誤
{"The property 'Geometry.Coordinates' could not be mapped, because it is of type 'float[][][]'
which is not a supported primitive type or a valid entity type. Either explicitly map this property,
or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'."}
錯誤很明顯。EF 無法自行映射這些不受支持的型別。如何顯式定義映射?或者有什么辦法可以讓它發揮作用?float[][][] 型別是否正確?
提前致謝。
uj5u.com熱心網友回復:
您始終可以將坐標保存為字串,其中坐標以逗號分隔。
例如在 FE 部分,您可以這樣處理:
const someLine = feature.getGeometry().transform("EPSG:4326",
"EPSG:3857");
const geometryLine = someLine
.clone()
.getGeometry()
.transform("EPSG:3857", "EPSG:4326");
const geometryCoords = geometryLine.getCoordinates().join(";");
然后你會得到這樣的東西:“43.520548594674132,26.565803087473146;....”它可以作為字串保存到資料庫中。(它可以用更少的小數點額外調整,等等。)
之后,如果您想通過 API 處理/獲取資料并通過 automapper(或某些自定義實作)將其映射到坐標串列(例如這樣的東西)
public class Coordinates
{
public double Longitude { get; set; }
public double Latitude { get; set; }
}
要將以前保存的資料映射到 DTO,您可以使用這樣的方法
public class GeneralProfile : Profile
{
public GeneralProfile()
{
CreateMap<Route, GetSavedRouteDTO>()
.ForMember(x => x.TripLength, options => options.MapFrom(x => x.Length))
.ForMember(x => x.RouteCoordinates, options => options.MapFrom(MapFromStringCoordinates));
CreateMap<Route, RouteCreateDTO>().ReverseMap();
}
private List<Coordinates> MapFromStringCoordinates(Route route, GetSavedRouteDTO getSavedRouteDTO)
{
var currentCulture = System.Globalization.CultureInfo.InstalledUICulture;
var numberFormat = (System.Globalization.NumberFormatInfo)currentCulture.NumberFormat.Clone();
numberFormat.NumberDecimalSeparator = ".";
var coordinates = new List<Coordinates>();
var coordinatesSplit = route.Coordinates.Split(";");
foreach (var coord in coordinatesSplit)
{
var currentCoord = coord.Split(",");
if (currentCoord.Length > 1)
{
var latitude = double.Parse(currentCoord[0], numberFormat);
var longitude = double.Parse(currentCoord[1], numberFormat);
var coords= new Coordinates { Latitude = latitude, Longitude = longitude };
coordinates.Add(coords);
}
}
return coordinates;
}
}
有了它,您將獲得包含緯度和經度的坐標串列,并從中創建幾何物體。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/372607.html
