public void Has_Correct_Type() { var name = "EPSG:31370"; var crs = new NamedCRS(name); Assert.AreEqual(CRSType.Name, crs.Type); }
public void Equals_GetHashCode_Contract() { var name = "EPSG:31370"; var left = new NamedCRS(name); var right = new NamedCRS(name); Assert.AreEqual(left, right); Assert.IsTrue(left == right); Assert.IsTrue(right == left); Assert.IsTrue(left.Equals(right)); Assert.IsTrue(right.Equals(left)); Assert.IsTrue(left.Equals(left)); Assert.IsTrue(right.Equals(right)); Assert.AreEqual(left.GetHashCode(), right.GetHashCode()); name = "EPSG:25832"; right = new NamedCRS(name); Assert.AreNotEqual(left, right); Assert.IsFalse(left == right); Assert.IsFalse(right == left); Assert.IsFalse(left.Equals(right)); Assert.IsFalse(right.Equals(left)); Assert.AreNotEqual(left.GetHashCode(), right.GetHashCode()); }
NamedCRS GetCrs(int srid) { var crsType = CrsType; if (crsType == GeoJSONOptions.None) { return(null); } if (_lastSrid == srid && _lastCrs != null) { return(_lastCrs); } var authority = _crsMap.GetAuthority(srid); if (authority == null) { throw new NpgsqlSafeReadException(new InvalidOperationException($"SRID {srid} unknown in spatial_ref_sys table")); } _lastCrs = new NamedCRS(crsType == GeoJSONOptions.LongCRS ? "urn:ogc:def:crs:" + authority + "::" + srid : authority + ":" + srid); _lastSrid = srid; return(_lastCrs); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var jsonObject = JObject.Load(reader); var typeName = jsonObject["type"].ToString().ToLower(); switch (typeName) { case "name": JObject propName = null; JToken jt; if (jsonObject.TryGetValue("properties", out jt)) { propName = JObject.Parse(jt.ToString()); } if (propName != null) { var target = new NamedCRS(propName["name"].ToString()); serializer.Populate(jsonObject.CreateReader(), target); return(target); } break; case "link": var linked = new LinkedCRS(""); serializer.Populate(jsonObject.CreateReader(), linked); return(linked); } return(new NotSupportedException(string.Format("Type {0} unexpected.", typeName))); }
public void NamedCRSConstructorTest() { const string name = "testName"; NamedCRS target = new NamedCRS(name); Assert.AreEqual(name, target.Properties["name"]); Assert.AreEqual(CRSTypes.Name, target.Type); }
/// <summary> /// Converts Iposition to Vector3 World Space coordinates takling account of zoom, scale and mapscale /// </summary> /// <param name="position">IPosition</param> /// <returns>Vector3</returns> public static Vector3 Vector3(this IPosition position, ICRSObject crs = null) { if (crs == null) { crs = new NamedCRS("EPSG:4326"); } return(position.ToGeometry(crs).TransformWorld()[0]); }
public void Has_Name_Property_With_Name() { var name = "EPSG:31370"; var crs = new NamedCRS(name); Assert.IsTrue(crs.Properties.ContainsKey("name")); Assert.AreEqual(name, crs.Properties["name"]); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType != JsonToken.StartObject) { throw new ArgumentException("Expected token '{' not found."); } reader.Read(); if (!(reader.TokenType == JsonToken.PropertyName && (string)reader.Value == "type")) { throw new ArgumentException("Expected token 'type' not found."); } reader.Read(); if (reader.TokenType != JsonToken.String) { throw new ArgumentException("Expected string value not found."); } string crsType = (string)reader.Value; reader.Read(); if (!(reader.TokenType == JsonToken.PropertyName && (string)reader.Value == "properties")) { throw new ArgumentException("Expected token 'properties' not found."); } reader.Read(); if (reader.TokenType != JsonToken.StartObject) { throw new ArgumentException("Expected token '{' not found."); } Dictionary <string, object> dictionary = serializer.Deserialize <Dictionary <string, object> >(reader); CRSBase result = null; switch (crsType) { case "link": object href = dictionary["href"]; object type = dictionary["type"]; result = new LinkedCRS((string)href, type != null ? (string)type : ""); break; case "name": object name = dictionary["name"]; result = new NamedCRS((string)name); break; } if (reader.TokenType != JsonToken.EndObject) { throw new ArgumentException("Expected token '}' not found."); } reader.Read(); if (reader.TokenType != JsonToken.EndObject) { throw new ArgumentException("Expected token '}' not found."); } reader.Read(); return(result); }
/// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader" /> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns> /// The object value. /// </returns> /// <exception cref="Newtonsoft.Json.JsonReaderException"> /// CRS must be null or a json object /// or /// CRS must have a "type" property /// </exception> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return(new UnspecifiedCRS()); } if (reader.TokenType != JsonToken.StartObject) { throw new JsonReaderException("CRS must be null or a json object"); } var jObject = JObject.Load(reader); JToken token; if (!jObject.TryGetValue("type", StringComparison.OrdinalIgnoreCase, out token)) { throw new JsonReaderException("CRS must have a \"type\" property"); } var crsType = token.Value <string>(); if (string.Equals("name", crsType, StringComparison.OrdinalIgnoreCase)) { JObject properties = null; if (jObject.TryGetValue("properties", out token)) { properties = token as JObject; } if (properties != null) { var target = new NamedCRS(properties["name"].ToString()); serializer.Populate(jObject.CreateReader(), target); return(target); } } else if (string.Equals("link", crsType, StringComparison.OrdinalIgnoreCase)) { JObject properties = null; if (jObject.TryGetValue("properties", out token)) { properties = token as JObject; } if (properties != null) { var linked = new LinkedCRS(properties["href"].ToString()); serializer.Populate(jObject.CreateReader(), linked); return(linked); } } return(new NotSupportedException(string.Format("Type {0} unexpected.", crsType))); }
public void Parse_PointStringWithNameCrsExtraParameter_SuccessfulParse() { string strGeometry = "{\"type\": \"Point\",\"coordinates\": [-105.01621,39.57422], \"crs\": {\"type\": \"name\", \"properties\": {\"name\": \"urn:ogc:def:crs:OGC:1.3:CRS84\", \"extra\": [1, 0]}}}"; IGeoJSONObject geoJsonObject = (IGeoJSONObject)JsonConvert.DeserializeObject <IGeometryObject>(strGeometry, new GeometryConverter()); // Assert CRS is parsed Assert.AreEqual(CRSType.Name, geoJsonObject.CRS.Type); NamedCRS namedCrs = (NamedCRS)geoJsonObject.CRS; Assert.AreEqual("urn:ogc:def:crs:OGC:1.3:CRS84", namedCrs.Name); Assert.IsTrue(namedCrs.Properties.ContainsKey("extra")); Assert.IsNotNull(namedCrs.Properties["extra"]); }
/// <summary> /// Parses the CRS information. /// </summary> /// <param name="jsonObject">The json object.</param> /// <returns>A NamedCRS, LinkedCRS or Null.</returns> public static ICRSObject ParseCrs(JObject jsonObject) { if (jsonObject == null || !jsonObject.HasValues) { return(null); } JProperty typeProperty = jsonObject.Property("type"); if (typeProperty != null) { string type = typeProperty.Value.ToObjectOrDefault <string>().ToLower().Trim(); CRSBase crs = null; if (type == "name") { crs = new NamedCRS(); } else if (type == "link") { crs = new LinkedCRS(); } else if (type == "epsg") { crs = new EPSGCRS(); } else { return(null); } if (jsonObject.Property("properties") != null) { foreach (JToken jToken in jsonObject.Property("properties").Value) { var item = (JProperty)jToken; string key = item.Name; object val = item.Value.ToObjectOrDefault <object>(); crs.Properties.Add(key, val); } } if (crs.Properties.Count == 0) { return(null); } return(crs); } return(null); }
public void GeoJsonReaderReadFeatureCollectionTest() { const string json = "{\"features\":[{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[23.0,56.0]},\"properties\":{\"test1\":\"value1\"}}],\"type\":\"FeatureCollection\",\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"name1\"}}}"; GeoJsonReader reader = new GeoJsonReader(); FeatureCollection result = reader.Read <FeatureCollection>(json); Assert.IsNotNull(result); Assert.AreEqual(1, result.Count); Assert.IsNotNull(result.CRS); Assert.IsInstanceOf(typeof(NamedCRS), result.CRS); Assert.AreEqual(CRSTypes.Name, result.CRS.Type); NamedCRS crs = (NamedCRS)result.CRS; Assert.AreEqual("name1", crs.Properties["name"]); }
static public Geometry ToGeometry(this LineString line) { Geometry geom = new Geometry(wkbGeometryType.wkbLineString); SpatialReference sr = new SpatialReference(null); ICRSObject crs = line.CRS; if (crs == null) { crs = new NamedCRS("EPSG:4326"); } switch (crs.Type) { case CRSType.Name: string name = (crs as NamedCRS).Properties["name"] as string; if (name.Contains("urn")) { sr.ImportFromUrl(name); } else if (name.Contains("EPSG")) { string[] args = name.Split(':'); sr.ImportFromEPSG(int.Parse(args[1])); } else { sr.SetWellKnownGeogCS(name); } break; case CRSType.Link: string url = (crs as LinkedCRS).Properties["href"] as string; sr.ImportFromUrl(url); break; case CRSType.Unspecified: sr.SetWellKnownGeogCS("EPSG:4326"); break; } geom.AssignSpatialReference(sr); Position[] vertexes = line.Points(); foreach (Position vertex in vertexes) { Nullable <double> alt = vertex.Altitude; geom.AddPoint(vertex.Latitude, vertex.Longitude, alt ?? 0.0); } return(geom); }
public void Save(string key, VectorQuadTile tile) { var ro = new FeatureCollection(); var crs = new NamedCRS("EPSG:" + Config.Settings.Map.SpatialReferenceSystemIdentifier); ro.CRS = crs; foreach (var omg in tile.Områder) { var område = omg.Område; IGeometryObject geometry = GeoJsonGeometry.FromDotSpatial(omg.Geometry); var props = new Dictionary <string, object> { { "category", område.Category }, { "name", område.Name }, { "number", område.Number }, { "value", område.Value }, { "type", område.Type.ToString() }, { "kind", område.kind } }; var feature = new Feature(geometry, props) { Id = område.AreaId.ToString() }; var fp = new FeatureProperties { nin = område.kind }; if (område.Number == 0) { throw new Exception("Område mangler nummer."); } ro.Features.Add(feature); } var fullPath = GetFullPath(key); var fullPathSingleDir = GetFullPath(key.Replace("/", "_")); var settings = GetJsonSerializerSettings(); File.WriteAllText(fullPath, JsonConvert.SerializeObject(ro, settings)); //File.WriteAllText(fullPathSingleDir, JsonConvert.SerializeObject(ro, settings)); //var serializer = new DataContractJsonSerializer(typeof(VectorQuadTile), CreateDataContractJsonSerializerSettings()); //using (Stream stream = File.Create(fullPath + ".adf")) // serializer.WriteObject(stream, tile); }
/// <summary> /// Tries to finds the coordinate system crs property used. /// </summary> /// <param name="namedCrs">The crs object.</param> /// <returns>The coordinate system id used. If no crs was found, None is returned.</returns> public CoordinateSystemId FindCoordinateSystemId(NamedCRS namedCrs) { if (namedCrs == null || string.IsNullOrEmpty(namedCrs.Name)) { return(CoordinateSystemId.None); } // todo - should check that the found search string has no trailing numbers. string name = namedCrs.Name.ToLower(); if (name.Contains("4326") || name.Contains(":crs84") || name.Contains(":84")) { // Here are some examples of WGS84 definitions that are approved: // epsg:4326, EPSG:4326, urn:ogc:def:crs:EPSG::4326, urn:ogc:def:crs:OGC:1.3:CRS84 // urn:ogc:def:crs:OGC:2:84, urn:ogc:def:crs:EPSG::4326 return(CoordinateSystemId.WGS84); } if (name.Contains("3006")) { return(CoordinateSystemId.SWEREF99_TM); } if (name.Contains("4619")) { return(CoordinateSystemId.SWEREF99); } if (name.Contains("3021") || name.Contains("2400")) { return(CoordinateSystemId.Rt90_25_gon_v); } if (name.Contains("900913") || name.Contains("3857")) { return(CoordinateSystemId.GoogleMercator); } return(CoordinateSystemId.None); }
public void Parse_PointStringWithNameCrs_SuccessfulParse() { string strGeometry = "{\"type\": \"Point\",\"coordinates\": [-105.01621,39.57422], \"crs\": {\"type\": \"name\", \"properties\": {\"name\": \"urn:ogc:def:crs:OGC:1.3:CRS84\"}}}"; IGeometryObject geometryObject = JsonConvert.DeserializeObject <IGeometryObject>(strGeometry, new GeometryConverter()); IGeoJSONObject geoJsonObject = (IGeoJSONObject)geometryObject; // Assert CRS is parsed Assert.AreEqual(CRSType.Name, geoJsonObject.CRS.Type); NamedCRS namedCrs = (NamedCRS)geoJsonObject.CRS; Assert.AreEqual("urn:ogc:def:crs:OGC:1.3:CRS84", namedCrs.Name); // Deserialization without specifying Converter Point point = JsonConvert.DeserializeObject <Point>(strGeometry); // Assert CRS is parsed Assert.AreEqual(CRSType.Name, point.CRS.Type); namedCrs = (NamedCRS)point.CRS; Assert.AreEqual("urn:ogc:def:crs:OGC:1.3:CRS84", namedCrs.Name); }
public static bool GetProjectionFromGeoJson(string fileName, out string projectionName, out string projection) { string geoJson = File.ReadAllText(fileName); ProtoGeoJSON obj = JsonConvert.DeserializeObject <ProtoGeoJSON>(geoJson); projectionName = string.Empty; projection = string.Empty; ICRSObject crs = null; switch (obj.Type) { case "FeatureCollection": GFeatureCollection features = JsonConvert.DeserializeObject <GFeatureCollection>(geoJson); crs = features.CRS; break; case "Feature": GFeature feature = JsonConvert.DeserializeObject <GFeature>(geoJson); crs = feature.CRS; break; case "MultiPolygon": GMultiPolygon multiPoly = JsonConvert.DeserializeObject <GMultiPolygon>(geoJson); crs = multiPoly.CRS; break; case "Polygon": GPolygon poly = JsonConvert.DeserializeObject <GPolygon>(geoJson); crs = poly.CRS; break; default: break; } if (crs is NamedCRS) { NamedCRS nCrs = crs as NamedCRS; object value; if (nCrs.Properties.TryGetValue("name", out value)) { string name = value as string; if (name != null) { name = name.ToLower(); if (name.EndsWith("3857")) { projectionName = "EPSG:3857 Pseudo-Mercator"; projection = CoordinateConverter.WebMercator.WKT; return(true); } else { int index = name.IndexOf("epsg::"); string epsgStr = name.Substring(index); string authNumber = epsgStr.Substring(epsgStr.IndexOf("::") + 2); projection = AutoProjection.GetProjection(authNumber); if (projection != string.Empty) { projectionName = string.Format("EPSG:{0}", authNumber); return(true); } } } } } projectionName = "EPSG:4326 Lat-Long"; projection = CoordinateConverter.WGS84.WKT; return(true); }
async ValueTask <GeoJSONObject> ReadGeometryCore(NpgsqlReadBuffer buf, bool async, BoundingBoxBuilder boundingBox) { await buf.Ensure(SizeOfHeader, async); var littleEndian = buf.ReadByte() > 0; var type = (EwkbGeometryType)buf.ReadUInt32(littleEndian); GeoJSONObject geometry; NamedCRS crs = null; if (HasSrid(type)) { await buf.Ensure(4, async); crs = GetCrs(buf.ReadInt32(littleEndian)); } switch (type & EwkbGeometryType.BaseType) { case EwkbGeometryType.Point: { await buf.Ensure(SizeOfPoint(type), async); var position = ReadPosition(buf, type, littleEndian); boundingBox?.Accumulate(position); geometry = new Point(position); break; } case EwkbGeometryType.LineString: { await buf.Ensure(SizeOfLength, async); var coordinates = new Position[buf.ReadInt32(littleEndian)]; for (var i = 0; i < coordinates.Length; ++i) { await buf.Ensure(SizeOfPoint(type), async); var position = ReadPosition(buf, type, littleEndian); boundingBox?.Accumulate(position); coordinates[i] = position; } geometry = new LineString(coordinates); break; } case EwkbGeometryType.Polygon: { await buf.Ensure(SizeOfLength, async); var lines = new LineString[buf.ReadInt32(littleEndian)]; for (var i = 0; i < lines.Length; ++i) { var coordinates = new Position[buf.ReadInt32(littleEndian)]; for (var j = 0; j < coordinates.Length; ++j) { await buf.Ensure(SizeOfPoint(type), async); var position = ReadPosition(buf, type, littleEndian); boundingBox?.Accumulate(position); coordinates[j] = position; } lines[i] = new LineString(coordinates); } geometry = new Polygon(lines); break; } case EwkbGeometryType.MultiPoint: { await buf.Ensure(SizeOfLength, async); var points = new Point[buf.ReadInt32(littleEndian)]; for (var i = 0; i < points.Length; ++i) { await buf.Ensure(SizeOfHeader + SizeOfPoint(type), async); await buf.Skip(SizeOfHeader, async); var position = ReadPosition(buf, type, littleEndian); boundingBox?.Accumulate(position); points[i] = new Point(position); } geometry = new MultiPoint(points); break; } case EwkbGeometryType.MultiLineString: { await buf.Ensure(SizeOfLength, async); var lines = new LineString[buf.ReadInt32(littleEndian)]; for (var i = 0; i < lines.Length; ++i) { await buf.Ensure(SizeOfHeaderWithLength, async); await buf.Skip(SizeOfHeader, async); var coordinates = new Position[buf.ReadInt32(littleEndian)]; for (var j = 0; j < coordinates.Length; ++j) { await buf.Ensure(SizeOfPoint(type), async); var position = ReadPosition(buf, type, littleEndian); boundingBox?.Accumulate(position); coordinates[j] = position; } lines[i] = new LineString(coordinates); } geometry = new MultiLineString(lines); break; } case EwkbGeometryType.MultiPolygon: { await buf.Ensure(SizeOfLength, async); var polygons = new Polygon[buf.ReadInt32(littleEndian)]; for (var i = 0; i < polygons.Length; ++i) { await buf.Ensure(SizeOfHeaderWithLength, async); await buf.Skip(SizeOfHeader, async); var lines = new LineString[buf.ReadInt32(littleEndian)]; for (var j = 0; j < lines.Length; ++j) { var coordinates = new Position[buf.ReadInt32(littleEndian)]; for (var k = 0; k < coordinates.Length; ++k) { await buf.Ensure(SizeOfPoint(type), async); var position = ReadPosition(buf, type, littleEndian); boundingBox?.Accumulate(position); coordinates[k] = position; } lines[j] = new LineString(coordinates); } polygons[i] = new Polygon(lines); } geometry = new MultiPolygon(polygons); break; } case EwkbGeometryType.GeometryCollection: { await buf.Ensure(SizeOfLength, async); var elements = new IGeometryObject[buf.ReadInt32(littleEndian)]; for (var i = 0; i < elements.Length; ++i) { elements[i] = (IGeometryObject) await ReadGeometryCore(buf, async, boundingBox); } geometry = new GeometryCollection(elements); break; } default: throw new NpgsqlSafeReadException(UnknownPostGisType()); } geometry.CRS = crs; return(geometry); }