mirror of https://github.com/Squidex/squidex.git
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
80 lines
2.5 KiB
80 lines
2.5 KiB
// ==========================================================================
|
|
// Squidex Headless CMS
|
|
// ==========================================================================
|
|
// Copyright (c) Squidex UG (haftungsbeschraenkt)
|
|
// All rights reserved. Licensed under the MIT license.
|
|
// ==========================================================================
|
|
|
|
using GeoJSON.Net;
|
|
using GeoJSON.Net.Geometry;
|
|
using Squidex.Infrastructure;
|
|
using Squidex.Infrastructure.Json;
|
|
using Squidex.Infrastructure.Json.Objects;
|
|
using Squidex.Infrastructure.ObjectPool;
|
|
using Squidex.Infrastructure.Validation;
|
|
|
|
namespace Squidex.Domain.Apps.Core.Contents
|
|
{
|
|
public static class GeoJsonValue
|
|
{
|
|
public static GeoJsonParseResult TryParse(IJsonValue value, IJsonSerializer serializer, out GeoJSONObject? geoJSON)
|
|
{
|
|
Guard.NotNull(serializer, nameof(serializer));
|
|
Guard.NotNull(value, nameof(value));
|
|
|
|
geoJSON = null;
|
|
|
|
if (value is JsonObject obj)
|
|
{
|
|
if (TryParseGeoJson(obj, serializer, out geoJSON))
|
|
{
|
|
return GeoJsonParseResult.Success;
|
|
}
|
|
|
|
if (!obj.TryGetValue<JsonNumber>("latitude", out var lat) || !lat.Value.IsBetween(-90, 90))
|
|
{
|
|
return GeoJsonParseResult.InvalidLatitude;
|
|
}
|
|
|
|
if (!obj.TryGetValue<JsonNumber>("longitude", out var lon) || !lon.Value.IsBetween(-180, 180))
|
|
{
|
|
return GeoJsonParseResult.InvalidLongitude;
|
|
}
|
|
|
|
geoJSON = new Point(new Position(lat.Value, lon.Value));
|
|
|
|
return GeoJsonParseResult.Success;
|
|
}
|
|
|
|
return GeoJsonParseResult.InvalidValue;
|
|
}
|
|
|
|
private static bool TryParseGeoJson(JsonObject obj, IJsonSerializer serializer, out GeoJSONObject? geoJSON)
|
|
{
|
|
geoJSON = null;
|
|
|
|
if (!obj.TryGetValue("type", out var type) || type is not JsonString)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
try
|
|
{
|
|
using (var stream = DefaultPools.MemoryStream.GetStream())
|
|
{
|
|
serializer.Serialize(obj, stream, true);
|
|
|
|
stream.Position = 0;
|
|
|
|
geoJSON = serializer.Deserialize<GeoJSONObject>(stream, null, true);
|
|
|
|
return true;
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|