/// <summary> /// Date and time message (ZDA). This should not normally need the last time as argument, because it defines it. /// </summary> public Waypoint(TalkerId talkerId, IEnumerable <string> fields, DateTimeOffset time) : base(talkerId, Id, time) { IEnumerator <string> field = fields.GetEnumerator(); Position = new GeographicPosition(); Name = string.Empty; double? wayPointLatitude = ReadValue(field); CardinalDirection?wayPointHemisphere = (CardinalDirection?)ReadChar(field); double? wayPointLongitude = ReadValue(field); CardinalDirection?wayPointDirection = (CardinalDirection?)ReadChar(field); string waypointName = ReadString(field); if (wayPointLatitude.HasValue && wayPointLongitude.HasValue) { double?latitude = RecommendedMinimumNavigationInformation.Nmea0183ToDegrees(wayPointLatitude, wayPointHemisphere); double?longitude = RecommendedMinimumNavigationInformation.Nmea0183ToDegrees(wayPointLongitude, wayPointDirection); if (latitude.HasValue && longitude.HasValue) { Position = new GeographicPosition(latitude.Value, longitude.Value, 0); Valid = true; } Name = waypointName; } }
public static void CoordinateAreEqual(double expectedLongitudeX, double expectedLatitudeY, GeographicPosition position) { GeographicPosition coordinate = (GeographicPosition)position; Assert.AreEqual(expectedLongitudeX, coordinate.Longitude); Assert.AreEqual(expectedLatitudeY, coordinate.Latitude); }
private static void Internal_FillGeographyBuilder(SqlGeographyBuilder gb, MultiLineString multiLineString) { gb.BeginGeography(OpenGisGeographyType.MultiLineString); foreach (var lineString in multiLineString.Coordinates) { gb.BeginGeography(OpenGisGeographyType.LineString); bool beginFigureCalled = false; foreach (var ipos in lineString.Coordinates) { GeographicPosition pos = ipos as GeographicPosition; if (!beginFigureCalled) { gb.BeginFigure(pos.Latitude, pos.Longitude); beginFigureCalled = true; } else { gb.AddLine(pos.Latitude, pos.Longitude); } } gb.EndFigure(); gb.EndGeography(); } gb.EndGeography(); }
static void Pointold(BinaryWriter p_bw, GeographicPosition p_Location) { p_bw.Write(s_WKBNDR); p_bw.Write((Int32)WkbGeometryType.WkbPoint); p_bw.Write(p_Location.Longitude); p_bw.Write(p_Location.Latitude); }
/// <summary> /// Constructs a new WPT sentence /// </summary> public Waypoint(GeographicPosition position, string name) : base(OwnTalkerId, Id, DateTimeOffset.UtcNow) { Position = position ?? throw new ArgumentNullException(nameof(position)); Name = name; Valid = true; }
static Polygon ParsePolygon(byte[] p_wkb, ref int p_pos) { var v_type = GetType(p_wkb, ref p_pos); if (v_type != (uint)WkbGeometryType.WkbPolygon) { throw new Exception("Invalid object type"); } var v_numLineStrings = GetUInt32(p_wkb, ref p_pos); var v_LineStrings = new List <LineString>(); for (var v_ls = 0; v_ls < v_numLineStrings; ++v_ls) { var v_numPoints = GetUInt32(p_wkb, ref p_pos); var v_Points = new GeographicPosition[v_numPoints]; for (var i = 0; i < v_numPoints; ++i) { v_Points[i] = GetGeographicPosition(p_wkb, ref p_pos); } v_LineStrings.Add(new LineString(v_Points)); } return(new Polygon(v_LineStrings)); }
/// <summary> /// Creates an ObservationsGISResult from a list of species observations. /// </summary> /// <param name="speciesObservationList">The observations list.</param> /// <returns></returns> public static SpeciesObservationsGeoJsonModel CreateResult(SpeciesObservationList speciesObservationList, FeatureCollection spatialFilter) { var features = new List <Feature>(); foreach (ISpeciesObservation observation in speciesObservationList) { // if x or y-coordinate doesn't exist, continue if (!observation.Location.CoordinateX.HasValue || !observation.Location.CoordinateY.HasValue) { continue; } var pos = new GeographicPosition(observation.Location.CoordinateX.Value, observation.Location.CoordinateY.Value); var point = new ArtDatabanken.GIS.GeoJSON.Net.Geometry.Point(pos); var dicProperties = new Dictionary <string, object>(); dicProperties.Add("observationId", observation.Id); dicProperties.Add("siteType", 2); dicProperties.Add("accuracy", observation.Location.CoordinateUncertaintyInMeters); var feature = new Feature(point, dicProperties); feature.Id = observation.DatasetID; features.Add(feature); } var featureCollection = new FeatureCollection(features); var result = new SpeciesObservationsGeoJsonModel(featureCollection, spatialFilter); return(result); }
public static IPosition ToGeometry(this DirectPositionType pos) { IPosition position; int dim; string[] coord = pos.Text.Trim().Replace(" ", " ").Split(' '); if (string.IsNullOrEmpty(pos.srsDimension)) { dim = 2; /* We assume that we are in 2D */ } else { dim = int.Parse(pos.srsDimension); if (dim < 2 || dim > 3) { throw new InvalidFormatException("invalid GML representation: gml:pos dimension equals " + dim); } } if (dim == 2) { position = new GeographicPosition(coord[0], coord[1]); } else { position = new GeographicPosition(coord[0], coord[1], coord[2]); } return(position); }
public bool IsPointInPolygon(GeographicPosition p, GeographicPosition[] polygon) { double minLongitude = polygon[0].Longitude; double maxLongitude = polygon[0].Longitude; double minLatitude = polygon[0].Latitude; double maxLatitude = polygon[0].Latitude; for (int i = 1; i < polygon.Length; i++) { GeographicPosition q = polygon[i]; minLongitude = Math.Min(q.Longitude, minLongitude); maxLongitude = Math.Max(q.Longitude, maxLongitude); minLatitude = Math.Min(q.Latitude, minLatitude); maxLatitude = Math.Max(q.Latitude, maxLatitude); } if (p.Longitude < minLongitude || p.Longitude > maxLongitude || p.Latitude < minLatitude || p.Latitude > maxLatitude) { return(false); } // http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html bool inside = false; for (int i = 0, j = polygon.Length - 1; i < polygon.Length; j = i++) { if ((polygon[i].Latitude > p.Latitude) != (polygon[j].Latitude > p.Latitude) && p.Longitude < (polygon[j].Longitude - polygon[i].Longitude) * (p.Latitude - polygon[i].Latitude) / (polygon[j].Latitude - polygon[i].Latitude) + polygon[i].Longitude) { inside = !inside; } } return(inside); }
public void Feature_Equals_GetHashCode_Contract_Dictionary() { var leftDictionary = GetPropertiesInRandomOrder(); var rightDictionary = GetPropertiesInRandomOrder(); var geometry_10 = new GeographicPosition(10, 10); var geometry_20 = new GeographicPosition(20, 20); var left = new Net.Feature.Feature(new Point( geometry_10), leftDictionary, "abc"); var right = new Net.Feature.Feature(new Point( geometry_20), rightDictionary, "abc"); Assert_Are_Not_Equal(left, right); // different geometries left = new Net.Feature.Feature(new Point( geometry_10), leftDictionary, "abc"); right = new Net.Feature.Feature(new Point( geometry_10), rightDictionary, "abc"); // identical geometries, different ids and or properties or not compared Assert_Are_Equal(left, right); }
private MultiPolygon GetShiftedMultpolygon(MultiPolygon multipolygon, ShiftingFactorForCoordinates shiftingOption) { List <LineString> lineStrings = multipolygon.Coordinates.SelectMany(polygon => polygon.Coordinates).ToList(); List <LineString> transformedLineStrings = new List <LineString>(); foreach (LineString line in lineStrings) { var updatedCoords = new List <IPosition>(); foreach (IPosition coords in line.Coordinates) { GeographicPosition geographicPosition = (GeographicPosition)coords; var latitudeFactor = (shiftingOption.ShiftingFactorForY / _earthsRadiusInMeters) * 180 / Math.PI; var longitudeFactor = (shiftingOption.ShiftingFactorForX / _earthsRadiusInMeters) * (180 / Math.PI) / Math.Cos(geographicPosition.Latitude * Math.PI / 180); updatedCoords.Add( new GeographicPosition( geographicPosition.Latitude + latitudeFactor, geographicPosition.Longitude + longitudeFactor)); } transformedLineStrings.Add(new LineString(updatedCoords)); } var result = new MultiPolygon(new List <Polygon> { new Polygon(transformedLineStrings) }); return(result); }
private static void Internal_FillGeographyBuilder(SqlGeographyBuilder gb, Point point) { gb.BeginGeography(OpenGisGeographyType.Point); GeographicPosition pos = point.Coordinates as GeographicPosition; gb.BeginFigure(pos.Latitude, pos.Longitude); gb.EndFigure(); gb.EndGeography(); }
/// <summary> /// Prints GEOJson dump of Sites /// </summary> /// <param name="requiredProperties">list of properties to include (if not found in siteproperties an empty string will be inserted)</param> /// <param name="propertyFilter">two part filter in property table i.e. 'program:agrimet'</param> public void Execute(string[] requiredProperties, string propertyFilter = "") { Console.Write("Content-Type: application/json\n\n"); var features = new List <Feature>(); FeatureCollection fc = new FeatureCollection(features); var sites = db.GetSiteCatalog(propertyFilter: propertyFilter); var siteProp = new TimeSeriesDatabaseDataSet.sitepropertiesDataTable(db); int id = 0; foreach (var s in sites) { var pos = new GeographicPosition(s.latitude, s.longitude); var pt = new GeoJSON.Net.Geometry.Point(pos); var props = siteProp.GetDictionary(s.siteid); for (int i = 0; i < requiredProperties.Length; i++) { if (requiredProperties[i].Trim() == "") { continue; } if (!props.ContainsKey(requiredProperties[i])) { props.Add(requiredProperties[i], ""); } } props.Add("siteid", s.siteid); props.Add("title", s.description); props.Add("state", s.state); props.Add("type", s.type); if (!props.ContainsKey("region")) { props.Add("region", s.agency_region); } props.Add("install", s.install); id++; var feature = new Feature(pt, props, id.ToString()); fc.Features.Add(feature); } var settings = new JsonSerializerSettings(); settings.NullValueHandling = NullValueHandling.Ignore; var json = Newtonsoft.Json.JsonConvert.SerializeObject(fc, Newtonsoft.Json.Formatting.Indented, settings); Console.WriteLine(json); //File.WriteAllText(@"c:\temp\test.json", json); }
public void Instantiation() { GeographicPosition geoPos = new GeographicPosition(); Assert.True(geoPos.ContainsValidPosition() == false); geoPos = new GeographicPosition(0.1, 0.0, 200); Assert.True(geoPos.ContainsValidPosition()); Assert.Equal(0.1, geoPos.Latitude, 10); Assert.Equal(0, geoPos.Longitude, 10); }
public void CrossTrackError1() { GeographicPosition start = new GeographicPosition(0, 0, 0); GeographicPosition end = new GeographicPosition(1, 0, 0); GreatCircle.CrossTrackError(start, end, start, out var crossTrackError, out Length distance); Assert.Equal(59.7053933897411, distance.NauticalMiles, 2); // 1 degree latitude = ~60 nautical miles Assert.Equal(0, crossTrackError.Meters); // start on track -> deviation is 0 }
public void Equality() { var p1 = new GeographicPosition(10, 20, 30); var p2 = new GeographicPosition(p1); Assert.Equal(p1, p2); Assert.True(p1.EqualPosition(p2)); Assert.False(p1.Equals(null)); }
/// <summary> /// Internal ctor /// </summary> public BearingAndDistanceToWayPoint(TalkerId talkerId, IEnumerable <string> fields, DateTimeOffset time) : base(talkerId, Id, time) { IEnumerator <string> field = fields.GetEnumerator(); string timeString = ReadString(field); DateTimeOffset now = ParseDateTime(time, timeString); DateTime = now; NextWayPointName = string.Empty; NextWayPoint = new GeographicPosition(); double? nextWayPointLatitude = ReadValue(field); CardinalDirection?nextWayPointHemisphere = (CardinalDirection?)ReadChar(field); double? nextWayPointLongitude = ReadValue(field); CardinalDirection?nextWayPointDirection = (CardinalDirection?)ReadChar(field); double? bearingTrue = ReadValue(field); string bearingTrueIdentifier = ReadString(field); double? bearingMagnetic = ReadValue(field); string bearingMagneticIdentifier = ReadString(field); double? distance = ReadValue(field); string nm = ReadString(field); string wayPointName = ReadString(field); if (nextWayPointLongitude.HasValue && nextWayPointLatitude.HasValue) { Valid = true; double?latitude = RecommendedMinimumNavigationInformation.Nmea0183ToDegrees(nextWayPointLatitude, nextWayPointHemisphere); double?longitude = RecommendedMinimumNavigationInformation.Nmea0183ToDegrees(nextWayPointLongitude, nextWayPointDirection); if (latitude.HasValue && longitude.HasValue) { NextWayPoint = new GeographicPosition(latitude.Value, longitude.Value, 0); } NextWayPointName = wayPointName; if (bearingTrue.HasValue && bearingTrueIdentifier == "T") { BearingTrueToWayPoint = Angle.FromDegrees(bearingTrue.Value); } if (bearingMagnetic.HasValue && bearingMagneticIdentifier == "M") { BearingMagneticToWayPoint = Angle.FromDegrees(bearingMagnetic.Value); } if (distance.HasValue && nm == "N") { DistanceToWayPoint = Length.FromNauticalMiles(distance.Value); } } }
public double Distance(GeographicPosition pos1, GeographicPosition pos2) { var d1 = pos1.Latitude * (Math.PI / 180.0); var num1 = pos1.Longitude * (Math.PI / 180.0); var d2 = pos2.Latitude * (Math.PI / 180.0); var num2 = pos2.Longitude * (Math.PI / 180.0) - num1; var d3 = Math.Pow(Math.Sin((d2 - d1) / 2.0), 2.0) + Math.Cos(d1) * Math.Cos(d2) * Math.Pow(Math.Sin(num2 / 2.0), 2.0); return(6376500.0 * (2.0 * Math.Atan2(Math.Sqrt(d3), Math.Sqrt(1.0 - d3)))); }
/// <summary> /// Creates a new route point. /// </summary> /// <param name="routeName">Name of the route</param> /// <param name="indexInRoute">The index of this point</param> /// <param name="totalPointsInRoute">The total number of points on this route</param> /// <param name="waypointName">The name of this waypoint</param> /// <param name="position">The position of the waypoint</param> /// <param name="bearingToNextWaypoint">The direction to the next waypoint (optional, will be calculated when the route is constructed)</param> /// <param name="distanceToNextWaypoint">The distance to the next waypoint (optional, will be calculated when the route is constructed)</param> /// <remarks> /// Route and point names should use ASCII characters only. Some devices may understand the extended ASCII code page (values > 127), /// but this is rare. Most devices will silently truncate any names longer than 10 chars. /// </remarks> public RoutePoint(string routeName, int indexInRoute, int totalPointsInRoute, string waypointName, GeographicPosition position, Angle?bearingToNextWaypoint, Length?distanceToNextWaypoint) { RouteName = routeName; IndexInRoute = indexInRoute; TotalPointsInRoute = totalPointsInRoute; WaypointName = waypointName; Position = position; BearingToNextWaypoint = bearingToNextWaypoint; DistanceToNextWaypoint = distanceToNextWaypoint; }
public void CrossTrackError2() { GeographicPosition start = new GeographicPosition(1, 0, 0); GeographicPosition end = new GeographicPosition(2, 0, 0); GeographicPosition current = new GeographicPosition(1.75, 0, 0); GreatCircle.CrossTrackError(start, end, current, out var crossTrackError, out Length distance); Assert.Equal(14.9264938243846, distance.NauticalMiles, 4); // 1 degree latitude = 60 nautical miles. A quarter of it is remaining Assert.Equal(0, crossTrackError.Meters); // On track -> deviation is 0 }
public void CrossTrackError4() { GeographicPosition start = new GeographicPosition(1, 0, 0); GeographicPosition end = new GeographicPosition(2, 0, 0); GeographicPosition current = new GeographicPosition(1.75, -1.0 / 60.0, 0); GreatCircle.CrossTrackError(start, end, current, out var crossTrackError, out Length distance); Assert.Equal(14.9264938243846, distance.NauticalMiles, 4); // 1 degree latitude = 60 nautical miles. A third of it is remaining Assert.Equal(-1.00, crossTrackError.NauticalMiles, 2); // One nautical mile off, to the left }
public void EqualityGeographicPosition() { var geoPos = new GeographicPosition(0.1, 0.0, 200); var geoPos2 = new GeographicPosition(0.100000001, -0.000000002, 200); var geoPos3 = new GeographicPosition(1, 2, 500); Assert.True(geoPos.EqualPosition(geoPos2)); Assert.True(geoPos.Equals(geoPos2)); // Hmm... Equals is now implemented as AlmostEquals(). Is this wise? Assert.True(!geoPos.EqualPosition(geoPos3)); }
private static void InternalDistDir(GeographicPosition startPosition, GeographicPosition endPosition, ref double distance, ref double direction) { double deltaLat = endPosition.Latitude - startPosition.Latitude; double deltaLon = endPosition.Longitude - startPosition.Longitude; double deltaX = deltaLon * GreatCircle.MetersPerDegreeLongitude * Math.Abs(Math.Cos(startPosition.Latitude * Math.PI / 180.0)); double deltaY = deltaLat * GreatCircle.MetersPerDegreeeLatitude; distance = Math.Sqrt(deltaX * deltaX + deltaY * deltaY); direction = GreatCircle.RadiansToAviatic(Math.Atan2(deltaY, deltaX)); }
public Task <bool?> GetRuleStatusAsync() { if (_vehicleStatus != null) { var point = new GeographicPosition(_vehicleStatus.Latitude, _vehicleStatus.Longitude); return(Task.FromResult <bool?>(IsPointInPolygon(point, _points))); } else { return(Task.FromResult((bool?)null)); } }
public static IPosition ToGeometry(this CoordType coord) { /* Check dimension consistancy */ if (coord.X == null || coord.Y == null) { throw new InvalidFormatException("invalid GML representation: gml:coord missing X or Y"); } GeographicPosition geopos = new GeographicPosition(System.Convert.ToDouble(coord.X), System.Convert.ToDouble(coord.Y), System.Convert.ToDouble(coord.Z)); return(geopos); }
public GeographicPosition ConvertPosition(GeographicPosition position, ICoordinateSystem fromCoordinateSystem, ICoordinateSystem toCoordinateSystem) { if (position == null) { return(null); } var transformator = GetTransformator(fromCoordinateSystem, toCoordinateSystem); return(ConvertGeographicPosition(transformator, position)); }
/// <summary> /// Sets the next point on the route (i.e. to skip a missed waypoint) /// </summary> /// <param name="position">Position of next waypoint</param> /// <returns>True on success, false otherwise. This returns false if the given position is not part of the route.</returns> public bool SetNextPoint(GeographicPosition position) { var pt = _routePoints.FirstOrDefault(x => x.Position.EqualPosition(position)); if (pt != null) { _nextPoint = pt; return(true); } return(false); }
private async Task SaveNewPoint() { await StateManager.SetStateAsync("vehicleStatus", _vehicleStatus); var point = new GeographicPosition(_vehicleStatus.Latitude, _vehicleStatus.Longitude); bool newInside = IsPointInPolygon(point, _points); if (_inside.HasValue && _inside.Value != newInside) { await SendNotification(_vehicleStatus.VehicleId, newInside? "Now we are inside the safe block" : "DANGER: We are outside the safe block!"); } _inside = newInside; }
public static Point PointFromDbGeometry(DbGeometry inp) { if (inp.SpatialTypeName != "Point") { throw new ArgumentException(); } var coordinates = new GeographicPosition(inp.YCoordinate.GetValueOrDefault(), // due to the throw above, this will never default inp.XCoordinate.GetValueOrDefault(), null); var point = new Point(coordinates); return(point); }
private static Polygon ReadPolygonText(WktStreamTokenizer tokenizer) { //var pol = new Polygon(new List<LineString> //{ // new LineString(new List<GeographicPosition>() // { // new GeographicPosition(0,0), // new GeographicPosition(1,1), // new GeographicPosition(0,0) // }) //}); var nextToken = GetNextEmptyOrOpener(tokenizer); if (nextToken == "EMPTY") { return(null); } var aneis = new List <LineString>(); do { var ring = GetCoordinates(tokenizer); var max = ring.Count; var vertices = new List <GeographicPosition>(); for (var i = 0; i < max; i++) { var lng = ring[i]; var lat = ring[i + 1]; var coord = new GeographicPosition(lat, lng); i++; vertices.Add(coord); } aneis.Add(new LineString(vertices)); nextToken = GetNextCloserOrComma(tokenizer); } while (nextToken == ","); var pol = new Polygon( new List <LineString>(aneis) ); return(pol); }
/// <summary> /// LineString from WKT. /// </summary> /// <returns>The LineString</returns> /// <param name="wkt">WKT.</param> public static LineString LineStringFromWKT(string wkt) { string[] terms = wkt.TrimStart('(').TrimEnd(')').Split(','); string[] values; List<IPosition> positions = new List<IPosition>(terms.Length); GeographicPosition prevgeopos = null; for (int i = 0; i < terms.Length; i++) { values = terms[i].Trim(' ').Split(' '); string z = (values.Length > 2 ? values[2] : null); GeographicPosition geopos = new GeographicPosition(values[1], values[0], z); try { if (prevgeopos != null && Enumerable.SequenceEqual(geopos.Coordinates, prevgeopos.Coordinates)) continue; } catch { } positions.Add(geopos); prevgeopos = geopos; } LineString test = new LineString(positions); return test; }
private static IPosition FromGMLPos(XmlElement gml) { IPosition position; int dim; string gmlpos; if (!IsGMLNamespace(gml, true)) return null; if (gml.LocalName != "pos") return null; string dimension = gml.GetAttribute("srsDimension"); if (dimension == "") /* in GML 3.0.0 it was dimension */ dimension = gml.GetAttribute("dimension"); if (dimension == "") dim = 2; /* We assume that we are in 2D */ else { dim = int.Parse(dimension); if (dim < 2 || dim > 3) throw new InvalidFormatException("invalid GML representation: gml:pos dimension equals " + dim); } /* We retrieve gml:pos string */ gmlpos = gml.InnerText.Trim(); /* gml:pos pattern: * x1 y1 * x1 y1 z1 */ string[] pos = gmlpos.Split(' '); position = new GeographicPosition(pos[0], pos[1], pos[2]); return position; }
/// <summary> /// LineString from WK. /// </summary> /// <returns>The LineString</returns> /// <param name="wkt">WKT.</param> public static LineString LineStringFromWKT(string wkt) { string[] terms = wkt.TrimStart('(').TrimEnd(')').Split(','); string[] values; List<IPosition> positions = new List<IPosition>(terms.Length); for (int i = 0; i < terms.Length; i++) { values = terms[i].Trim(' ').Split(' '); string z = (values.Length > 2 ? values[2] : null); GeographicPosition geopos = new GeographicPosition(values[1], values[0], z); positions.Add(geopos); } LineString test = new LineString(positions); return test; }
/// <summary> /// MultiPoint from WK. /// </summary> /// <returns>The MultiPoint</returns> /// <param name="wkt">WKT.</param> public static MultiPoint MultiPointFromWKT(string wkt) { string[] terms = wkt.TrimStart('(').TrimEnd(')').Trim(' ').Split(','); string[] values; List<IPosition> points = new List<IPosition>(terms.Length); for (int i = 0; i < terms.Length; i++) { values = terms[i].Split(' '); string z = (values.Length > 2 ? values[2] : null); GeographicPosition geopos = new GeographicPosition(values[1], values[0], z); points.Add(geopos); } return new MultiPoint(points); }
/// <summary> /// Point from WK. /// </summary> /// <returns>The Point</returns> /// <param name="wkt">WKT.</param> public static Point PointFromWKT(string wkt) { string[] values; values = wkt.Trim(' ').Split(' '); string z = (values.Length > 2 ? values[2] : null); GeographicPosition geopos = new GeographicPosition(values[1], values[0], z); return new Point(geopos); }
public static IPosition ToGeometry(this CoordType coord) { /* Check dimension consistancy */ if (coord.X == null || coord.Y == null) throw new InvalidFormatException("invalid GML representation: gml:coord missing X or Y"); GeographicPosition geopos = new GeographicPosition(System.Convert.ToDouble(coord.X), System.Convert.ToDouble(coord.Y), System.Convert.ToDouble(coord.Z)); return geopos; }
public static IPosition ToGeometry(this DirectPositionType pos) { IPosition position; int dim; string[] coord = pos.Text.Trim().Split(' '); if (string.IsNullOrEmpty(pos.srsDimension)) dim = 2; /* We assume that we are in 2D */ else { dim = int.Parse(pos.srsDimension); if (dim < 2 || dim > 3) throw new InvalidFormatException("invalid GML representation: gml:pos dimension equals " + dim); } if (dim == 2) position = new GeographicPosition(coord[0], coord[1]); else position = new GeographicPosition(coord[0], coord[1], coord[2]); return position; }
private static IPosition FromGMLCoord(XmlElement element) { double? x = null, y = null, z = null; foreach (XmlElement el in element.ChildNodes) { if (!IsGMLNamespace(el, false)) continue; if (el.LocalName == "X") x = double.Parse(el.InnerText); if (el.LocalName == "Y") y = double.Parse(el.InnerText); if (el.LocalName == "Z") z = double.Parse(el.InnerText); } /* Check dimension consistancy */ if (x == null || y == null) throw new InvalidFormatException("invalid GML representation: gml:coord missing X or Y"); GeographicPosition geopos = new GeographicPosition(y.Value, x.Value, z.Value); return geopos; }
public static List<LineString> SplitWorldExtent(LineString lineString) { List<LineString> newLineStrings = new List<LineString>(); LineString currentLineString = new LineString(); newLineStrings.Add(currentLineString); GeographicPosition previous_position = (GeographicPosition)lineString.Positions[0]; currentLineString.Positions.Add(previous_position); int currentPosition = 0; int dayline = 0; for (int i = 1; i < lineString.Positions.Count; i++) { GeographicPosition current_position = (GeographicPosition)lineString.Positions[i]; if ((current_position.Longitude != 180 && previous_position.Longitude != 180) || (current_position.Longitude != -180 && previous_position.Longitude != -180)) { if ((current_position.Longitude - previous_position.Longitude < -90) || (current_position.Longitude - previous_position.Longitude > 90)) { LineString newLineString = currentLineString; if (current_position.Longitude - previous_position.Longitude > 90) { dayline--; if (currentPosition == 0) { newLineString = new LineString(); newLineStrings.Insert(0, newLineString); } else { newLineString = newLineStrings[--currentPosition]; } } if (current_position.Longitude - previous_position.Longitude < -90) { dayline++; if (newLineStrings.Count <= currentPosition + 1) { newLineString = new LineString(); newLineStrings.Add(newLineString); } else { newLineString = newLineStrings[currentPosition + 1]; } currentPosition++; } double new_longitude; double new_latitude; double? new_altitude; double new_longitude2; double new_latitude2; double? new_altitude2; if (previous_position.Longitude > 0) { new_longitude = 180; new_longitude2 = -180; } else { new_longitude = -180; new_longitude2 = 180; } // Calaculate the latitude to be linear with the next point if ((current_position.Longitude - previous_position.Longitude + 2 * new_longitude) == 0) { new_latitude = (current_position.Latitude - previous_position.Latitude) * (-1 * new_longitude - previous_position.Longitude + 2 * new_longitude) + previous_position.Latitude; } else { new_latitude = (current_position.Latitude - previous_position.Latitude) * (-1 * new_longitude - previous_position.Longitude + 2 * new_longitude) / (current_position.Longitude - previous_position.Longitude + 2 * new_longitude) + previous_position.Latitude; } new_latitude2 = new_latitude; new_altitude = new_altitude2 = current_position.Altitude; GeographicPosition new_position1 = new GeographicPosition(new_latitude, new_longitude, new_altitude); GeographicPosition new_position2 = new GeographicPosition(new_latitude2, new_longitude2, new_altitude2); newLineString.Positions.Add(new_position2); currentLineString.Positions.Add(new_position1); if (dayline == 0) currentLineString.Positions.Add(currentLineString.Positions[0]); currentLineString = newLineString; } } currentLineString.Positions.Add(current_position); previous_position = current_position; } return newLineStrings; }