A Polygon is a planar Surface, defined by 1 exterior boundary and 0 or more interior boundaries. Each interior boundary defines a hole in the Polygon.
Vertices of rings defining holes in polygons are in the opposite direction of the exterior ring.
Inheritance: Geometry
Esempio n. 1
0
        private static SKPath ToSkia(IViewport viewport, Polygon polygon)
        {
            var vertices = polygon.ExteriorRing.Vertices;
            var path = new SKPath();
            {
                // todo: use transform matrix
                var first = viewport.WorldToScreen(vertices[0].X, vertices[0].Y);
                path.MoveTo((float)first.X, (float) first.Y);

                for (var i = 1; i < vertices.Count; i++)
                {
                   var point = viewport.WorldToScreen(vertices[i].X, vertices[i].Y);
                    path.LineTo((float) point.X, (float) point.Y);
                }
                path.Close();
                foreach (var interiorRing in polygon.InteriorRings)
                {
                    // note: For Skia inner rings need to be clockwise and outer rings
                    // need to be counter clockwise (if this is the other way around it also
                    // seems to work)
                    // this is not a requirement of the OGC polygon.
                    var firstInner = viewport.WorldToScreen(interiorRing.Vertices[0].X, interiorRing.Vertices[0].Y);
                    path.MoveTo((float)firstInner.X, (float)firstInner.Y);
                    for (var i = 1; i < interiorRing.Vertices.Count; i++)
                    {
                        var point = viewport.WorldToScreen(interiorRing.Vertices[i].X, interiorRing.Vertices[i].Y);
                        path.LineTo((float)point.X, (float)point.Y);
                    }
                }
                path.Close();
                return path;
            }
        }
Esempio n. 2
0
        public void AddHexagon(Land land)
        {
            var zone = GeoHex.Decode(land.GeohexKey);

            var isOwn = Current.Instance.Earthwatcher.Lands.Any(x => x.GeohexKey == land.GeohexKey);
            var sphericalCoordinates = ConvertHexCoordinates(zone.getHexCoords());
            var polygon = new Polygon { ExteriorRing = new LinearRing(sphericalCoordinates) };
            var feature = new Feature { Geometry = polygon };
            feature["isGreenpeaceUser"] = land.EarthwatcherId.HasValue && land.EarthwatcherId.Value == Configuration.GreenpeaceId ? "True" : "False";
            feature["hexcode"] = zone.code;

            bool ischecked = false;
            if (land.OKs.Split(',').Any(x => x.Equals(Current.Instance.Earthwatcher.Id.ToString())) || land.Alerts.Split(',').Any(x => x.Equals(Current.Instance.Earthwatcher.Id.ToString())))
            {
                ischecked = true;
            }

            bool denouncedByMe = false;
            if(Current.Instance.Scores.Any(x => x.Action.Equals(ActionPoints.Action.DemandAuthorities.ToString()) && (x.LandId == land.Id)))
            {
                denouncedByMe = true;
            }

            bool islockedOnly = land.IsLocked == true && land.DemandAuthorities == false ? true : false;

            feature.Styles.Add(GetVectorStyle(land.LandStatus, isOwn, land.DemandAuthorities, ischecked, land.EarthwatcherId.HasValue && land.EarthwatcherId.Value == Configuration.GreenpeaceId ? true : false, islockedOnly, denouncedByMe));

            source.Features.Add(feature);
        }
Esempio n. 3
0
        public static void DrawPolygon(Graphics graphics, Polygon pol, Brush brush, Pen pen, IViewport viewport)
        {
            if (pol.ExteriorRing == null) return;
            if (pol.ExteriorRing.Vertices.Count <= 2) return;

            //Use a graphics path instead of DrawPolygon. DrawPolygon has a problem with several interior holes
            var gp = new GraphicsPath();

            //Add the exterior polygon
            var points = GeometryRenderer.WorldToScreenGDI(pol.ExteriorRing, viewport);
            if (points.Length > 2)
                gp.AddPolygon(points);
            //Add the interior polygons (holes)
            foreach (LinearRing linearRing in pol.InteriorRings)
            {
                var interiorPoints = GeometryRenderer.WorldToScreenGDI(linearRing, viewport);
                if (interiorPoints.Length > 2)
                    gp.AddPolygon(interiorPoints);
            }

            if (gp.PointCount == 0) return;

            // Only render inside of polygon if the brush isn't null or isn't transparent
            if (brush != null && brush != Brushes.Transparent)
                graphics.FillPath(brush, gp);
            // Create an outline if a pen style is available
            if (pen != null)
                graphics.DrawPath(pen, gp);
        }
Esempio n. 4
0
        void layerRequest_LayerRecived(object sender, EventArgs e)
        {

            Polygon poligono;
            Earthwatchers.Models.KmlModels.Layer layer = sender as Earthwatchers.Models.KmlModels.Layer;

            if (layer != null)
            {
                isFirstTime = false;
                layersTest = layer;     
                foreach (Earthwatchers.Models.KmlModels.Zone zon in layer.Zones)
                {
                    foreach (var p in zon.Polygons)
                    {
                        poligono = new Polygon { ExteriorRing = new LinearRing(ConvertHexCoordinates(p.Locations.Select(l => new Location(l.Longitude.Value, l.Latitude.Value)).ToList())) };
                        var feature = new Feature { Geometry = poligono };
                        var vStyle = new VectorStyle
                        {
                            Fill = new Brush { Color = Color.FromArgb(48, 255, 255, 255) },
                            Outline = new Pen { Color = Color.FromArgb(100, 241, 251, 187), Width = 2 }, //#F1FBBB
                        };
                        feature.Styles.Add(vStyle);
                        _source.Features.Add(feature);
                    }
                }
                Current.Instance.MapControl.OnViewChanged(true);
            }
            Current.Instance.MapControl.OnViewChanged(true);
        }
Esempio n. 5
0
 private static Polygon CreatePolygon()
 {
     var polygon = new Polygon();
     polygon.ExteriorRing.Vertices.Add(new Point(0, 0));
     polygon.ExteriorRing.Vertices.Add(new Point(0, 1000000));
     polygon.ExteriorRing.Vertices.Add(new Point(1000000, 1000000));
     polygon.ExteriorRing.Vertices.Add(new Point(1000000, 0));
     polygon.ExteriorRing.Vertices.Add(new Point(0, 0));
     return polygon;
 }
Esempio n. 6
0
        private static IEnumerable<Point> AllVertices(Polygon polygon)
        {
            if (polygon == null) throw new ArgumentNullException("polygon");

            foreach (var point in polygon.ExteriorRing.Vertices)
                yield return point;
            foreach (var ring in polygon.InteriorRings)
                foreach (var point in ring.Vertices)
                    yield return point;
        }
Esempio n. 7
0
        public void AddHexagon(Zone zone, LandStatus landStatus, bool isOwnLand)
        {
            var sphericalCoordinates = ConvertHexCoordinates(zone.getHexCoords());
            var polygon = new Polygon { ExteriorRing = new LinearRing(sphericalCoordinates) };
            var feature = new Feature {Geometry = polygon};
            feature["hexcode"] = zone.code;

            feature.Styles.Add(GetVectorStyle(landStatus, isOwnLand));
            
            source.Features.Add(feature);
        }
        public void AddBasecamp(Land land)
        {
            var zone = GeoHex.Decode(land.GeohexKey);

             var isOwn = Current.Instance.Lands.Any(x => x.GeohexKey == land.GeohexKey);
             var sphericalCoordinates = ConvertHexCoordinates(zone.getHexCoords());
             var polygon = new Polygon { ExteriorRing = new LinearRing(sphericalCoordinates) };
             var feature = new Feature { Geometry = polygon };
             feature["bccode"] = zone.code;

             _source.Features.Add(feature);
        }
Esempio n. 9
0
 private static Polygon CreatePolygon()
 {
     var polygon = new Polygon();
     polygon.ExteriorRing.Vertices.Add(new Point(0, 0));
     polygon.ExteriorRing.Vertices.Add(new Point(0, 10000000));
     polygon.ExteriorRing.Vertices.Add(new Point(10000000, 10000000));
     polygon.ExteriorRing.Vertices.Add(new Point(10000000, 0));
     polygon.ExteriorRing.Vertices.Add(new Point(0, 0));
     var linearRing = new LinearRing();
     linearRing.Vertices.Add(new Point(1000000, 1000000));
     linearRing.Vertices.Add(new Point(9000000, 1000000));
     linearRing.Vertices.Add(new Point(9000000, 9000000));
     linearRing.Vertices.Add(new Point(1000000, 9000000));
     linearRing.Vertices.Add(new Point(1000000, 1000000));
     polygon.InteriorRings.Add(linearRing);
     return polygon;
 }
Esempio n. 10
0
            private void UpdateCirclePolygon()
            {
                // Create new circle
                var centerX      = Attractor.Position.X;
                var centerY      = Attractor.Position.Y;
                var radius       = Attractor.WorkingRadius;
                var increment    = 2;
                var exteriorRing = new LinearRing();

                for (double angle = 0; angle < 360; angle += increment)
                {
                    var angleRad = angle / 180.0 * Math.PI;
                    exteriorRing.Vertices.Add(new Point(radius * Math.Sin(angleRad) + centerX, radius * Math.Cos(angleRad) + centerY));
                }

                Geometry = new MapsuiPolygon(exteriorRing);
            }
Esempio n. 11
0
        private static List <Polygon> CreatePolygon()
        {
            var result = new List <Polygon>();

            var polygon = new Polygon();

            polygon.ExteriorRing.Vertices.Add(new Point(0, 0));
            polygon.ExteriorRing.Vertices.Add(new Point(0, 10000000));
            polygon.ExteriorRing.Vertices.Add(new Point(10000000, 10000000));
            polygon.ExteriorRing.Vertices.Add(new Point(10000000, 0));
            polygon.ExteriorRing.Vertices.Add(new Point(0, 0));
            var linearRing = new LinearRing();

            linearRing.Vertices.Add(new Point(1000000, 1000000));
            linearRing.Vertices.Add(new Point(9000000, 1000000));
            linearRing.Vertices.Add(new Point(9000000, 9000000));
            linearRing.Vertices.Add(new Point(1000000, 9000000));
            linearRing.Vertices.Add(new Point(1000000, 1000000));
            polygon.InteriorRings.Add(linearRing);

            result.Add(polygon);

            polygon = new Polygon();
            polygon.ExteriorRing.Vertices.Add(new Point(-10000000, 0));
            polygon.ExteriorRing.Vertices.Add(new Point(-15000000, 5000000));
            polygon.ExteriorRing.Vertices.Add(new Point(-10000000, 10000000));
            polygon.ExteriorRing.Vertices.Add(new Point(-5000000, 5000000));
            polygon.ExteriorRing.Vertices.Add(new Point(-10000000, 0));

            /*
             *
             * linearRing = new LinearRing();
             * linearRing.Vertices.Add(new Point(-10000000, 1000000));
             * linearRing.Vertices.Add(new Point(-6000000, 5000000));
             * linearRing.Vertices.Add(new Point(-10000000, 9000000));
             * linearRing.Vertices.Add(new Point(-14000000, 5000000));
             * linearRing.Vertices.Add(new Point(-10000000, 1000000));
             * polygon.InteriorRings.Add(linearRing);
             \
             */
            result.Add(polygon);

            return(result);
        }
Esempio n. 12
0
        public TestLayer(string name)
            : base(name)
        {
            _source = new MemoryProvider();
            DataSource = _source;

            List<Location> locations = new List<Location>();
            locations.Add(new Location(-63.307, -23.203));
            locations.Add(new Location(-63.200, -23.203));
            locations.Add(new Location(-63.200, -23.350));
            locations.Add(new Location(-63.307, -23.350));
            locations.Add(new Location(-63.307, -23.203));

            var polygon = new Polygon { ExteriorRing = new LinearRing(ConvertHexCoordinates(locations)) };
            
            var feature = new Feature { Geometry = polygon };

            var color = Color.Blue;

            if (name.Equals("08-may"))
            {
                color = Color.Green;
            }
            else if (name.Equals("03-jun"))
            {
                color = Color.Red;
            }

            var vStyle = new VectorStyle
            {
                Fill = new Brush { Color = color },
                Outline = new Pen { Color = Color.Black, Width = 0 },
            };

            feature.Styles.Add(vStyle);

            _source.Features.Add(feature);

            //Current.Instance.MapControl.OnViewChanged(true);
        }
Esempio n. 13
0
        public static CALayer RenderPolygonOnLayer(Polygon polygon, IStyle style, IViewport viewport)
        {
            var tile = new CAShapeLayer();

            if (!(style is VectorStyle)) throw new ArgumentException("Style is not of type VectorStyle");
            var vectorStyle = style as VectorStyle;

            var strokeAlpha = (float)vectorStyle.Outline.Color.A / 255;
            var fillAlpha = (float)vectorStyle.Fill.Color.A / 255;

            var strokeColor = new CGColor(new CGColor(vectorStyle.Outline.Color.R, vectorStyle.Outline.Color.G,
                vectorStyle.Outline.Color.B), strokeAlpha);
            var fillColor = new CGColor(new CGColor(vectorStyle.Fill.Color.R, vectorStyle.Fill.Color.G,
                vectorStyle.Fill.Color.B), fillAlpha);

            tile.StrokeColor = strokeColor;
            tile.FillColor = fillColor;
            tile.LineWidth = (float)vectorStyle.Outline.Width;
            tile.Path = polygon.ToUIKit(viewport).CGPath;

            return tile;
        }
Esempio n. 14
0
        private static ILayer CreateMutatingTriangleLayer(BoundingBox envelope)
        {
            var layer = new MemoryLayer();

            var polygon = new Polygon(new LinearRing(GenerateRandomPoints(envelope, 3)));
            var feature = new Feature() { Geometry = polygon };
            var features = new Features();
            features.Add(feature);

            layer.DataSource = new MemoryProvider(features);

            PeriodicTask.Run(() =>
            {
                polygon.ExteriorRing = new LinearRing(GenerateRandomPoints(envelope, 3));
                // Clear cache for change to show
                feature.RenderedGeometry.Clear();
                // Trigger DataChanged notification
                layer.ViewChanged(true, layer.Envelope, 1);
            },
            TimeSpan.FromMilliseconds(1000));

            return layer;
        }
Esempio n. 15
0
        public static Polygon ConvertScreenToWorld(Polygon sharpmapPolygon)
        {
            // Log4netLogger.Debug("Start converting screen polygon to map polygon");

            var linearRing = new LinearRing();
            foreach (var vertex in sharpmapPolygon.ExteriorRing.Vertices)
            {
                linearRing.Vertices.Add(ConvertScreenToWorld(vertex));
            }

            // Log4netLogger.Debug("Screen polygon to map polygon conversion ended");
            return new Polygon(linearRing);
        }
Esempio n. 16
0
 /// <summary>
 /// Converts a Polygon to &lt;Polygon Text&gt; format, then
 /// Appends it to the writer.
 /// </summary>
 /// <param name="polygon">The Polygon to process.</param>
 /// <param name="writer"></param>
 private static void AppendPolygonText(Polygon polygon, StringWriter writer)
 {
     if (polygon == null || polygon.IsEmpty())
         writer.Write("EMPTY");
     else
     {
         writer.Write("(");
         AppendLineStringText(polygon.ExteriorRing, writer);
         foreach (LinearRing t in polygon.InteriorRings)
         {
             writer.Write(", ");
             AppendLineStringText(t, writer);
         }
         writer.Write(")");
     }
 }
Esempio n. 17
0
 /// <summary>
 ///  Converts a Polygon to &lt;Polygon Tagged Text&gt; format,
 ///  then Appends it to the writer.
 /// </summary>
 /// <param name="polygon">Th Polygon to process.</param>
 /// <param name="writer">The stream writer to Append to.</param>
 private static void AppendPolygonTaggedText(Polygon polygon, StringWriter writer)
 {
     writer.Write("POLYGON ");
     AppendPolygonText(polygon, writer);
 }
Esempio n. 18
0
        /// <summary>
        /// Creates a Polygon using the next token in the stream.
        /// </summary>
        /// <param name="tokenizer">Tokenizer over a stream of text in Well-known Text
        ///  format. The next tokens must form a &lt;Polygon Text&gt;.</param>
        /// <returns>Returns a Polygon specified by the next token
        ///  in the stream</returns>
        ///  <remarks>
        ///  ParseException is thown if the coordinates used to create the Polygon
        ///  shell and holes do not form closed linestrings, or if an unexpected
        ///  token is encountered.
        ///  </remarks>
        private static Polygon ReadPolygonText(WktStreamTokenizer tokenizer)
        {
            var pol = new Polygon();
            string nextToken = GetNextEmptyOrOpener(tokenizer);
            if (nextToken == "EMPTY")
                return pol;

            pol.ExteriorRing = new LinearRing(GetCoordinates(tokenizer));
            nextToken = GetNextCloserOrComma(tokenizer);
            while (nextToken == ",")
            {
                //Add holes
                pol.InteriorRings.Add(new LinearRing(GetCoordinates(tokenizer)));
                nextToken = GetNextCloserOrComma(tokenizer);
            }
            return pol;
        }
Esempio n. 19
0
        /// <summary>
        /// This method parses quickly without paying attention to
        /// context validation, polygon boundaries and multi-geometries.
        /// This accelerates the geometry parsing process, 
        /// but in scarce cases can lead to errors. 
        /// </summary>
        /// <param name="geometryType">The geometry type (Point, LineString, Polygon, MultiPoint, MultiCurve, 
        /// MultiLineString (deprecated), MultiSurface, MultiPolygon (deprecated)</param>
        /// <returns>The created geometries</returns>
        internal virtual Collection<Geometry> createQuickGeometries(string geometryType)
        {
            // Ignore multi-geometries
            if (geometryType.Equals("MultiPointPropertyType")) geometryType = "PointPropertyType";
            else if (geometryType.Equals("MultiLineStringPropertyType")) geometryType = "LineStringPropertyType";
            else if (geometryType.Equals("MultiPolygonPropertyType")) geometryType = "PolygonPropertyType";
            else if (geometryType.Equals("MultiCurvePropertyType")) geometryType = "CurvePropertyType";
            else if (geometryType.Equals("MultiSurfacePropertyType")) geometryType = "SurfacePropertyType";

            string serviceException = null;

            while (_XmlReader.Read())
            {
                if (_CoordinatesNode.Matches(_XmlReader))
                {
                    try
                    {
                        switch (geometryType)
                        {
                            case "PointPropertyType":
                                _Geoms.Add(ParseCoordinates(_XmlReader.ReadSubtree())[0]);
                                break;
                            case "LineStringPropertyType":
                            case "CurvePropertyType":
                                _Geoms.Add(new LineString(ParseCoordinates(_XmlReader.ReadSubtree())));
                                break;
                            case "PolygonPropertyType":
                            case "SurfacePropertyType":
                                Polygon polygon = new Polygon();
                                polygon.ExteriorRing = new LinearRing(ParseCoordinates(_XmlReader.ReadSubtree()));
                                _Geoms.Add(polygon);
                                break;
                            default:
                                break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("An exception occured while parsing a " + geometryType + " geometry: " +
                                         ex.Message);
                        throw ex;
                    }
                    continue;
                }

                if (_ServiceExceptionNode.Matches(_XmlReader))
                {
                    serviceException = _XmlReader.ReadInnerXml();
                    Trace.TraceError("A service exception occured: " + serviceException);
                    throw new Exception("A service exception occured: " + serviceException);
                }
            }

            return _Geoms;
        }
Esempio n. 20
0
        protected override List<IGeometry> GetGeometries()
        {
            List<IGeometry> res = new List<IGeometry>();
            MultiPolygon mult = new MultiPolygon();
            Polygon poly = new Polygon();
            mult.Polygons.Add(poly);
            int current = 0;

            for (int i = 0; i < _points.Count; i++)
            {

                Point p = _currentProjection.Project(_points[i].X, _points[i].Y);
                if (p == null)
                {
                    return null;
                }
                if (poly.ExteriorRing.Vertices.Count == 0)
                {
                    poly.ExteriorRing.Vertices.Add(p);
                }
                else
                {
                    var prev = _currentProjection.Inverse(poly.ExteriorRing.Vertices.LastOrDefault().X, poly.ExteriorRing.Vertices.LastOrDefault().Y);

                    if (Math.Abs(prev.X - _points[i].X) > 180)
                    {

                        double x1 = prev.X >= 0 ? 180 : -180;
                        double x2 = -x1;
                        double y = prev.Y + (_points[i].Y - prev.Y) * Math.Abs(x1 - prev.X) / (Math.Abs(_points[i].X - x2) + Math.Abs(x1 - prev.X));
                        var p1 = _currentProjection.Project(x1, y);
                        if (p1 != null)
                        {
                            poly.ExteriorRing.Vertices.Add(p1);
                        }
                        else
                        {
                            return null;
                        }
                        if (mult.Polygons.Count >= 2 && Math.Abs(mult.Polygons[current - 1].ExteriorRing.EndPoint.X - _points[i].X) < 180)
                        {
                            current--;

                            poly = mult.Polygons[current];
                        }
                        else
                        {
                            current++;
                            poly = new Polygon();
                            mult.Polygons.Add(poly);
                        }
                        var p2 = _currentProjection.Project(x2, y);
                        if (p2 != null)
                        {
                            poly.ExteriorRing.Vertices.Add(p2);
                        }
                        else
                        {
                            return null;
                        }
                        poly.ExteriorRing.Vertices.Add(p);
                    }
                    else
                    {
                        poly.ExteriorRing.Vertices.Add(p);
                    }
                }

            }

            if (mult.Polygons.Count > 1)
            {
                res.Add(mult);
            }
            res.Add(poly);
            return res;
        }
Esempio n. 21
0
 /// <summary>
 /// Return a copy of this geometry
 /// </summary>
 /// <returns>Copy of Geometry</returns>
 public new Polygon Clone()
 {
     var p = new Polygon();
     p.ExteriorRing = exteriorRing.Clone();
     foreach (var t in interiorRings)
         p.InteriorRings.Add(t.Clone());
     return p;
 }
Esempio n. 22
0
        /// <summary>
        /// Reads and parses the geometry with ID 'oid' from the ShapeFile
        /// </summary>
        /// <remarks><see cref="FilterDelegate">Filtering</see> is not applied to this method</remarks>
        /// <param name="oid">Object ID</param>
        /// <returns>geometry</returns>
        // ReSharper disable once CyclomaticComplexity // Fix when changes need to be made here
        private Geometry ReadGeometry(uint oid)
        {
            _brShapeFile.BaseStream.Seek(GetShapeIndex(oid) + 8, 0); //Skip record number and content length
            var type = (ShapeType)_brShapeFile.ReadInt32(); //Shape type
            if (type == ShapeType.Null)
                return null;
            if (_shapeType == ShapeType.Point || _shapeType == ShapeType.PointM || _shapeType == ShapeType.PointZ)
            {
                return new Point(_brShapeFile.ReadDouble(), _brShapeFile.ReadDouble());
            }
            if (_shapeType == ShapeType.Multipoint || _shapeType == ShapeType.MultiPointM ||
                _shapeType == ShapeType.MultiPointZ)
            {
                _brShapeFile.BaseStream.Seek(32 + _brShapeFile.BaseStream.Position, 0); //skip min/max box
                var feature = new MultiPoint();
                int nPoints = _brShapeFile.ReadInt32(); // get the number of points
                if (nPoints == 0)
                    return null;
                for (int i = 0; i < nPoints; i++)
                    feature.Points.Add(new Point(_brShapeFile.ReadDouble(), _brShapeFile.ReadDouble()));

                return feature;
            }
            if (_shapeType == ShapeType.PolyLine || _shapeType == ShapeType.Polygon ||
                _shapeType == ShapeType.PolyLineM || _shapeType == ShapeType.PolygonM ||
                _shapeType == ShapeType.PolyLineZ || _shapeType == ShapeType.PolygonZ)
            {
                _brShapeFile.BaseStream.Seek(32 + _brShapeFile.BaseStream.Position, 0); //skip min/max box

                int nParts = _brShapeFile.ReadInt32(); // get number of parts (segments)
                if (nParts == 0)
                    return null;
                int nPoints = _brShapeFile.ReadInt32(); // get number of points

                var segments = new int[nParts + 1];
                //Read in the segment indexes
                for (int b = 0; b < nParts; b++)
                    segments[b] = _brShapeFile.ReadInt32();
                //add end point
                segments[nParts] = nPoints;

                if ((int)_shapeType % 10 == 3)
                {
                    var mline = new MultiLineString();
                    for (int lineId = 0; lineId < nParts; lineId++)
                    {
                        var line = new LineString();
                        for (int i = segments[lineId]; i < segments[lineId + 1]; i++)
                            line.Vertices.Add(new Point(_brShapeFile.ReadDouble(), _brShapeFile.ReadDouble()));
                        mline.LineStrings.Add(line);
                    }
                    if (mline.LineStrings.Count == 1)
                        return mline[0];
                    return mline;
                }
                else //(_ShapeType == ShapeType.Polygon etc...)
                {
                    //First read all the rings
                    var rings = new List<LinearRing>();
                    for (int ringId = 0; ringId < nParts; ringId++)
                    {
                        var ring = new LinearRing();
                        for (int i = segments[ringId]; i < segments[ringId + 1]; i++)
                            ring.Vertices.Add(new Point(_brShapeFile.ReadDouble(), _brShapeFile.ReadDouble()));
                        rings.Add(ring);
                    }
                    var isCounterClockWise = new bool[rings.Count];
                    int polygonCount = 0;
                    for (int i = 0; i < rings.Count; i++)
                    {
                        isCounterClockWise[i] = rings[i].IsCCW();
                        if (!isCounterClockWise[i])
                            polygonCount++;
                    }
                    if (polygonCount == 1) //We only have one polygon
                    {
                        var poly = new Polygon { ExteriorRing = rings[0] };
                        if (rings.Count > 1)
                            for (int i = 1; i < rings.Count; i++)
                                poly.InteriorRings.Add(rings[i]);
                        return poly;
                    }
                    else
                    {
                        var mpoly = new MultiPolygon();
                        var poly = new Polygon { ExteriorRing = rings[0] };
                        for (var i = 1; i < rings.Count; i++)
                        {
                            if (!isCounterClockWise[i])
                            {
                                mpoly.Polygons.Add(poly);
                                poly = new Polygon(rings[i]);
                            }
                            else
                                poly.InteriorRings.Add(rings[i]);
                        }
                        mpoly.Polygons.Add(poly);
                        return mpoly;
                    }
                }
            }

            throw (new ApplicationException("Shapefile type " + _shapeType.ToString() + " not supported"));
        }
Esempio n. 23
0
        void layerRequest_LayerRecived(object sender, EventArgs e)
        {
            isFirstTime = false;

            Polygon poligono;
            Earthwatchers.Models.KmlModels.Layer layer = sender as Earthwatchers.Models.KmlModels.Layer;
            if (layer != null)
            {
                foreach (Earthwatchers.Models.KmlModels.Zone zon in layer.Zones)
                {
                    if (zon.Name == "Zona Amarilla")
                    {
                        #region YellowArea

                        foreach (var p in zon.Polygons)
                        {
                            poligono = new Polygon { ExteriorRing = new LinearRing(ConvertHexCoordinates(p.Locations.Select(l => new Location(l.Longitude.Value, l.Latitude.Value)).ToList())) };
                            var feature = new Feature { Geometry = poligono };
                            var vStyle = new VectorStyle
                            {
                                Fill = new Brush { Color = Color.FromArgb(58, 254, 238, 0) },
                                Outline = new Pen { Color = Color.FromArgb(0, 255, 255, 0), Width = 2 },
                            };
                            feature.Styles.Add(vStyle);
                            _source.Features.Add(feature);
                        }
                        #endregion
                    }
                    else if (zon.Name == "Zona Roja")
                    {
                        #region RedArea
                        foreach (var p in zon.Polygons)
                        {
                            poligono = new Polygon { ExteriorRing = new LinearRing(ConvertHexCoordinates(p.Locations.Select(l => new Location(l.Longitude.Value, l.Latitude.Value)).ToList())) };
                            var feature = new Feature { Geometry = poligono };
                            var vStyle = new VectorStyle
                            {
                                Fill = new Brush { Color = Color.FromArgb(58, 255, 0, 0) },
                                Outline = new Pen { Color = Color.FromArgb(0, 255, 0, 0), Width = 2 },
                            };
                            feature.Styles.Add(vStyle);
                            _source.Features.Add(feature);
                        }
                        #endregion
                    }
                    else if (zon.Name == "Zona Verde")
                    {
                        #region GreenArea
                        foreach (var p in zon.Polygons)
                        {
                            poligono = new Polygon { ExteriorRing = new LinearRing(ConvertHexCoordinates(p.Locations.Select(l => new Location(l.Longitude.Value, l.Latitude.Value)).ToList())) };
                            var feature = new Feature { Geometry = poligono };
                            var vStyle = new VectorStyle
                            {
                                Fill = new Brush { Color = Color.FromArgb(110, 0, 144, 69) },
                                Outline = new Pen { Color = Color.FromArgb(0, 3, 255, 3), Width = 2 },
                            };
                            feature.Styles.Add(vStyle);
                            _source.Features.Add(feature);
                        }
                        #endregion
                    }

                }
                Current.Instance.MapControl.OnViewChanged(true);
            }

            Loaded(this, EventArgs.Empty);
        }
Esempio n. 24
0
        /// <summary>
        /// Writes a polygon.
        /// </summary>
        /// <param name="poly">The polygon to be written.</param>
        /// <param name="bWriter">Stream to write to.</param>
        /// <param name="byteorder">Byte order</param>
        private static void WritePolygon(Polygon poly, BinaryWriter bWriter, WkbByteOrder byteorder)
        {
            //Get the number of rings in this polygon.
            int numRings = poly.InteriorRings.Count + 1;

            //Write the number of rings to the stream (add one for the shell)
            WriteUInt32((uint) numRings, bWriter, byteorder);

            //Write the exterior of this polygon.
            WriteLineString(poly.ExteriorRing, bWriter, byteorder);

            //Loop on the number of rings - 1 because we already wrote the shell.
            foreach (LinearRing lr in poly.InteriorRings)
                //Write the (lineString)LinearRing.
                WriteLineString(lr, bWriter, byteorder);
        }
        public static void DrawPolygon(Graphics graphics, Polygon pol, Brush brush, Pen pen, IViewport viewport)
        {
            if (pol.ExteriorRing == null)
                return;
            if (pol.ExteriorRing.Vertices.Count > 2)
            {
                //Use a graphics path instead of DrawPolygon. DrawPolygon has a problem with several interior holes
                var gp = new GraphicsPath();

                //Add the exterior polygon
                gp.AddPolygon(ConvertPoints(WorldToView(pol.ExteriorRing, viewport)));
                //Add the interior polygons (holes)
                foreach (LinearRing linearRing in pol.InteriorRings)
                    gp.AddPolygon(ConvertPoints(WorldToView(linearRing, viewport)));

                // Only render inside of polygon if the brush isn't null or isn't transparent
                if (brush != null && brush != Brushes.Transparent)
                    graphics.FillPath(brush, gp);
                // Create an outline if a pen style is available
                if (pen != null)
                    graphics.DrawPath(pen, gp);
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Reads and parses the geometry with ID 'oid' from the ShapeFile
        /// </summary>
        /// <remarks><see cref="FilterDelegate">Filtering</see> is not applied to this method</remarks>
        /// <param name="oid">Object ID</param>
        /// <returns>geometry</returns>
        private Geometry ReadGeometry(uint oid)
        {
            brShapeFile.BaseStream.Seek(GetShapeIndex(oid) + 8, 0); //Skip record number and content length
            ShapeType type = (ShapeType) brShapeFile.ReadInt32(); //Shape type
            if (type == ShapeType.Null)
                return null;
            if (_ShapeType == ShapeType.Point || _ShapeType == ShapeType.PointM || _ShapeType == ShapeType.PointZ)
            {
                Point tempFeature = new Point();
                return new Point(brShapeFile.ReadDouble(), brShapeFile.ReadDouble());
            }
            else if (_ShapeType == ShapeType.Multipoint || _ShapeType == ShapeType.MultiPointM ||
                     _ShapeType == ShapeType.MultiPointZ)
            {
                brShapeFile.BaseStream.Seek(32 + brShapeFile.BaseStream.Position, 0); //skip min/max box
                MultiPoint feature = new MultiPoint();
                int nPoints = brShapeFile.ReadInt32(); // get the number of points
                if (nPoints == 0)
                    return null;
                for (int i = 0; i < nPoints; i++)
                    feature.Points.Add(new Point(brShapeFile.ReadDouble(), brShapeFile.ReadDouble()));

                return feature;
            }
            else if (_ShapeType == ShapeType.PolyLine || _ShapeType == ShapeType.Polygon ||
                     _ShapeType == ShapeType.PolyLineM || _ShapeType == ShapeType.PolygonM ||
                     _ShapeType == ShapeType.PolyLineZ || _ShapeType == ShapeType.PolygonZ)
            {
                brShapeFile.BaseStream.Seek(32 + brShapeFile.BaseStream.Position, 0); //skip min/max box

                int nParts = brShapeFile.ReadInt32(); // get number of parts (segments)
                if (nParts == 0)
                    return null;
                int nPoints = brShapeFile.ReadInt32(); // get number of points

                int[] segments = new int[nParts + 1];
                //Read in the segment indexes
                for (int b = 0; b < nParts; b++)
                    segments[b] = brShapeFile.ReadInt32();
                //add end point
                segments[nParts] = nPoints;

                if ((int) _ShapeType%10 == 3)
                {
                    MultiLineString mline = new MultiLineString();
                    for (int LineID = 0; LineID < nParts; LineID++)
                    {
                        LineString line = new LineString();
                        for (int i = segments[LineID]; i < segments[LineID + 1]; i++)
                            line.Vertices.Add(new Point(brShapeFile.ReadDouble(), brShapeFile.ReadDouble()));
                        mline.LineStrings.Add(line);
                    }
                    if (mline.LineStrings.Count == 1)
                        return mline[0];
                    return mline;
                }
                else //(_ShapeType == ShapeType.Polygon etc...)
                {
                    //First read all the rings
                    List<LinearRing> rings = new List<LinearRing>();
                    for (int RingID = 0; RingID < nParts; RingID++)
                    {
                        LinearRing ring = new LinearRing();
                        for (int i = segments[RingID]; i < segments[RingID + 1]; i++)
                            ring.Vertices.Add(new Point(brShapeFile.ReadDouble(), brShapeFile.ReadDouble()));
                        rings.Add(ring);
                    }
                    bool[] IsCounterClockWise = new bool[rings.Count];
                    int PolygonCount = 0;
                    for (int i = 0; i < rings.Count; i++)
                    {
                        IsCounterClockWise[i] = rings[i].IsCCW();
                        if (!IsCounterClockWise[i])
                            PolygonCount++;
                    }
                    if (PolygonCount == 1) //We only have one polygon
                    {
                        Polygon poly = new Polygon();
                        poly.ExteriorRing = rings[0];
                        if (rings.Count > 1)
                            for (int i = 1; i < rings.Count; i++)
                                poly.InteriorRings.Add(rings[i]);
                        return poly;
                    }
                    else
                    {
                        MultiPolygon mpoly = new MultiPolygon();
                        Polygon poly = new Polygon();
                        poly.ExteriorRing = rings[0];
                        for (int i = 1; i < rings.Count; i++)
                        {
                            if (!IsCounterClockWise[i])
                            {
                                mpoly.Polygons.Add(poly);
                                poly = new Polygon(rings[i]);
                            }
                            else
                                poly.InteriorRings.Add(rings[i]);
                        }
                        mpoly.Polygons.Add(poly);
                        return mpoly;
                    }
                }
            }
            else
                throw (new ApplicationException("Shapefile type " + _ShapeType.ToString() + " not supported"));
        }
Esempio n. 27
0
 /// <summary>
 ///     Return a copy of this geometry
 /// </summary>
 /// <returns>Copy of Geometry</returns>
 public new Polygon Clone()
 {
     var polygon = new Polygon {ExteriorRing = ExteriorRing.Clone()};
     foreach (var interiorRing in InteriorRings)
     {
         polygon.InteriorRings.Add(interiorRing.Clone());
     }
     return polygon;
 }
Esempio n. 28
0
        /// <summary>
        /// This method produces instances of type <see cref="Mapsui.Geometries.Polygon"/>.
        /// </summary>
        /// <returns>The created geometries</returns>
        internal override Collection<Geometry> CreateGeometries(Features features)
        {
            IPathNode polygonNode = new PathNode(Gmlns, "Polygon", (NameTable) XmlReader.NameTable);
            IPathNode outerBoundaryNode = new PathNode(Gmlns, "outerBoundaryIs", (NameTable) XmlReader.NameTable);
            IPathNode exteriorNode = new PathNode(Gmlns, "exterior", (NameTable) XmlReader.NameTable);
            IPathNode outerBoundaryNodeAlt = new AlternativePathNodesCollection(outerBoundaryNode, exteriorNode);
            IPathNode innerBoundaryNode = new PathNode(Gmlns, "innerBoundaryIs", (NameTable) XmlReader.NameTable);
            IPathNode interiorNode = new PathNode(Gmlns, "interior", (NameTable) XmlReader.NameTable);
            IPathNode innerBoundaryNodeAlt = new AlternativePathNodesCollection(innerBoundaryNode, interiorNode);
            IPathNode linearRingNode = new PathNode(Gmlns, "LinearRing", (NameTable) XmlReader.NameTable);
            var labelValue = new string[1];
            bool geomFound = false;

            try
            {
                // Reading the entire feature's node makes it possible to collect label values that may appear before or after the geometry property
                while ((FeatureReader = GetSubReaderOf(XmlReader, null, FeatureNode)) != null)
                {
                    while ((GeomReader = GetSubReaderOf(FeatureReader, labelValue, polygonNode)) != null)
                    {
                        var polygon = new Polygon();

                        XmlReader outerBoundaryReader;
                        if (
                            (outerBoundaryReader =
                             GetSubReaderOf(GeomReader, null, outerBoundaryNodeAlt, linearRingNode, CoordinatesNode)) !=
                            null)
                            polygon.ExteriorRing = new LinearRing(ParseCoordinates(outerBoundaryReader));

                        XmlReader innerBoundariesReader;
                        while (
                            (innerBoundariesReader =
                             GetSubReaderOf(GeomReader, null, innerBoundaryNodeAlt, linearRingNode, CoordinatesNode)) !=
                            null)
                            polygon.InteriorRings.Add(new LinearRing(ParseCoordinates(innerBoundariesReader)));

                        Geoms.Add(polygon);
                        geomFound = true;
                    }
                    if (geomFound) features.Add(CreateFeature(Geoms[Geoms.Count - 1], FeatureTypeInfo.LableField, labelValue[0]));
                    geomFound = false;
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("An exception occured while parsing a polygon geometry: " + ex.Message);
                throw;
            }

            return Geoms;
        }
Esempio n. 29
0
 /// <summary>
 ///     Determines if this Polygon and the specified Polygon object has the same values
 /// </summary>
 /// <param name="p">Polygon to compare with</param>
 /// <returns></returns>
 public bool Equals(Polygon p)
 {
     if (p == null)
         return false;
     if (!p.ExteriorRing.Equals(ExteriorRing))
         return false;
     if (p.InteriorRings.Count != InteriorRings.Count)
         return false;
     for (var i = 0; i < p.InteriorRings.Count; i++)
     {
         if (!p.InteriorRings[i].Equals(InteriorRings[i]))
             return false;
     }
     return true;
 }
Esempio n. 30
0
        private static Polygon CreateWKBPolygon(BinaryReader reader, WkbByteOrder byteOrder)
        {
            // Get the Number of rings in this Polygon.
            var numRings = (int) ReadUInt32(reader, byteOrder);

            Debug.Assert(numRings >= 1, "Number of rings in polygon must be 1 or more.");

            var shell = new Polygon(CreateWKBLinearRing(reader, byteOrder));

            // Create a new array of linearrings for the interior rings.
            for (var i = 0; i < (numRings - 1); i++)
                shell.InteriorRings.Add(CreateWKBLinearRing(reader, byteOrder));

            // Create and return the Poylgon.
            return shell;
        }