コード例 #1
0
        private void btnEdit_Click(object sender, EventArgs e)
        {
            LayerOverlay          layerOverlay = (LayerOverlay)winformsMap1.Overlays["StreetsOverlay"];
            ShapeFileFeatureLayer layer1       = (ShapeFileFeatureLayer)layerOverlay.Layers["Streets"];

            //Edit the geometry of a street feature.
            layer1.Open();
            layer1.FeatureSource.BeginTransaction();

            Collection <Feature> features = layer1.FeatureSource.GetFeaturesByColumnValue("RECID", "13762", ReturningColumnsType.AllColumns);

            //Gets the MultilineShape and add a vertes
            MultilineShape newMultiLineShape = (MultilineShape)features[0].GetShape();

            newMultiLineShape.Lines[0].Vertices.Add(new Vertex(-97.8015, 30.2880));
            //Sets the Id of the MultilineShape the same as the feature
            newMultiLineShape.Id = features[0].Id;
            //Updates the feature with the new geometry.
            layer1.FeatureSource.UpdateFeature(newMultiLineShape, features[0].ColumnValues);

            layer1.FeatureSource.CommitTransaction();
            layer1.Close();

            winformsMap1.Refresh(layerOverlay);

            btnEdit.Enabled = false;
        }
コード例 #2
0
        public static MultilineShape GetDifference(this LineShape masterLine, AreaBaseShape clippingArea)
        {
            MultilineShape resultMultiLineShape = new MultilineShape();
            var            masterGeoLine        = SqlGeometry.STGeomFromWKB(new SqlBytes(masterLine.GetWellKnownBinary()), 0);
            var            clippingGeoArea      = SqlGeometry.STGeomFromWKB(new SqlBytes(clippingArea.GetWellKnownBinary()), 0);
            var            resultWkb            = masterGeoLine.STSymDifference(clippingGeoArea).MakeValid().STAsBinary().Value;
            var            resultFeature        = new Feature(resultWkb);
            var            resultShape          = resultFeature.GetShape();

            if (resultShape is GeometryCollectionShape)
            {
                foreach (var line in ((GeometryCollectionShape)resultFeature.GetShape()).Shapes.OfType <LineShape>())
                {
                    resultMultiLineShape.Lines.Add(line);
                }
            }
            else if (resultShape is MultilineShape)
            {
                foreach (var item in ((MultilineShape)resultShape).Lines)
                {
                    resultMultiLineShape.Lines.Add(item);
                }
            }
            else if (resultShape is LineShape)
            {
                resultMultiLineShape.Lines.Add((LineShape)resultShape);
            }

            return(resultMultiLineShape);
        }
コード例 #3
0
        private void mapView_Loaded(object sender, RoutedEventArgs e)
        {
            mapView.MapUnit       = GeographyUnit.Meter;
            mapView.ZoomLevelSet  = new ThinkGeoCloudMapsZoomLevelSet();
            mapView.CurrentExtent = new RectangleShape(-15495673, 20037508, 13458526, -20037508);

            // Create background world map with vector tile requested from ThinkGeo Cloud Service.
            ThinkGeoCloudVectorMapsOverlay thinkGeoCloudVectorMapsOverlay = new ThinkGeoCloudVectorMapsOverlay(SampleHelper.ThinkGeoCloudId, SampleHelper.ThinkGeoCloudSecret, ThinkGeoCloudVectorMapsMapType.Light);

            mapView.Overlays.Add(thinkGeoCloudVectorMapsOverlay);

            // Setup the shapefile layer.
            ShapeFileFeatureLayer worldLayer = new ShapeFileFeatureLayer(SampleHelper.Get("Countries02_3857.shp"));

            worldLayer.ZoomLevelSet.ZoomLevel01.DefaultAreaStyle    = AreaStyle.CreateSimpleAreaStyle(GeoColors.Transparent, GeoColor.FromArgb(100, GeoColors.Green));
            worldLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;

            // Setup the mapshape layer.
            InMemoryFeatureLayer bitmapLayer = new InMemoryFeatureLayer();

            bitmapLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle.PointType = PointType.Image;
            bitmapLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle.Image     = new GeoImage(SampleHelper.Get("Prop Plane.png"));
            bitmapLayer.ZoomLevelSet.ZoomLevel01.DefaultLineStyle            = LineStyle.CreateSimpleLineStyle(GeoColors.Red, 1F, LineDashStyle.Dash, false);
            bitmapLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel         = ApplyUntilZoomLevel.Level20;

            ProjectionConverter project = new ProjectionConverter(4326, 3857);

            project.Open();
            PointShape     planeShape       = new PointShape(-95.2806, 38.9554);
            PointShape     destinationPoint = new PointShape(36.04, 48.49);
            MultilineShape airLineShape     = (MultilineShape)project.ConvertToExternalProjection(planeShape.GreatCircle(destinationPoint));

            airLineShape.Id = "AirLine";
            bitmapLayer.Open();
            bitmapLayer.EditTools.BeginTransaction();
            bitmapLayer.EditTools.Add(new Feature(project.ConvertToExternalProjection(planeShape).GetWellKnownBinary(), "Plane"));
            bitmapLayer.EditTools.Add(new Feature(airLineShape.GetWellKnownBinary(), "AirLine"));
            bitmapLayer.EditTools.CommitTransaction();
            bitmapLayer.Close();
            project.Close();

            LayerOverlay worldOverlay = new LayerOverlay();

            worldOverlay.Layers.Add("WorldLayer", worldLayer);
            mapView.Overlays.Add("WorldOverlay", worldOverlay);

            LayerOverlay planeOverlay = new LayerOverlay();

            planeOverlay.TileType = TileType.SingleTile;
            planeOverlay.Layers.Add("BitmapLayer", bitmapLayer);
            mapView.Overlays.Add("PlaneOverlay", planeOverlay);

            mapView.Refresh();

            timer.Start();
        }
コード例 #4
0
 private static IEnumerable <PointShape> CollectPoints(MultilineShape mline)
 {
     foreach (var line in mline.Lines)
     {
         foreach (var point in CollectPoints(line))
         {
             yield return(point);
         }
     }
 }
コード例 #5
0
        protected override void DrawCore(IEnumerable <Feature> features, GeoCanvas canvas, Collection <SimpleCandidate> labelsInThisLayer, Collection <SimpleCandidate> labelsInAllLayers)
        {
            PointStyle pointStyle = new PointStyle(geoImage);

            foreach (Feature feature in features)
            {
                MultilineShape lineShape = (MultilineShape)feature.GetShape();
                lineStyle.Draw(new BaseShape[] { lineShape }, canvas, labelsInThisLayer, labelsInAllLayers);

                List <Vertex> allVertices = lineShape.Lines.SelectMany(l => l.Vertices).ToList();

                double totalDistance = 0;
                for (int i = 0; i < allVertices.Count - 1; i++)
                {
                    PointShape pointShape1 = new PointShape(allVertices[i]);
                    PointShape pointShape2 = new PointShape(allVertices[i + 1]);

                    LineShape tempLineShape = new LineShape();
                    tempLineShape.Vertices.Add(allVertices[i]);
                    tempLineShape.Vertices.Add(allVertices[i + 1]);

                    double angle = GetAngleFromTwoVertices(allVertices[i], allVertices[i + 1]);
                    // Left side
                    if (imageDirection == ImageDirection.Left)
                    {
                        if (angle >= 270)
                        {
                            angle -= 180;
                        }
                    }
                    // Right side
                    else
                    {
                        if (angle <= 90)
                        {
                            angle += 180;
                        }
                    }
                    pointStyle.RotationAngle = (float)angle;

                    float  screenDistance  = ExtentHelper.GetScreenDistanceBetweenTwoWorldPoints(canvas.CurrentWorldExtent, pointShape1, pointShape2, canvas.Width, canvas.Height);
                    double currentDistance = Math.Round(pointShape1.GetDistanceTo(pointShape2, canvas.MapUnit, DistanceUnit.Meter), 2);
                    double worldInterval   = (currentDistance * imageSpacing) / screenDistance;
                    while (totalDistance <= currentDistance)
                    {
                        PointShape tempPointShape = tempLineShape.GetPointOnALine(StartingPoint.FirstPoint, totalDistance, canvas.MapUnit, DistanceUnit.Meter);
                        pointStyle.Draw(new BaseShape[] { tempPointShape }, canvas, labelsInThisLayer, labelsInAllLayers);
                        totalDistance = totalDistance + worldInterval;
                    }

                    totalDistance = totalDistance - currentDistance;
                }
            }
        }
コード例 #6
0
        private void btnGetShortestLine_Click(object sender, EventArgs e)
        {
            InMemoryFeatureLayer inMemoryLayer     = (InMemoryFeatureLayer)winformsMap1.FindFeatureLayer("InMemoryFeatureLayer");
            InMemoryFeatureLayer shortestLineLayer = (InMemoryFeatureLayer)winformsMap1.FindFeatureLayer("ShortestLineLayer");

            BaseShape      areaShape1     = inMemoryLayer.InternalFeatures["AreaShape1"].GetShape();
            BaseShape      areaShape2     = inMemoryLayer.InternalFeatures["AreaShape2"].GetShape();
            MultilineShape multiLineShape = areaShape1.GetShortestLineTo(areaShape2, GeographyUnit.Meter);

            shortestLineLayer.InternalFeatures.Clear();
            shortestLineLayer.InternalFeatures.Add("ShortestLine", new Feature(multiLineShape.GetWellKnownBinary(), "ShortestLine"));

            winformsMap1.Refresh(winformsMap1.Overlays["ShortestLineOverlay"]);
        }
コード例 #7
0
        private void EfficientlyMoveAPlaneImage_Load(object sender, EventArgs e)
        {
            timer.Interval       = 200;
            timer.Tick          += new EventHandler(timer_Tick);
            winformsMap1.MapUnit = GeographyUnit.DecimalDegree;

            winformsMap1.BackgroundOverlay.BackgroundBrush = new GeoSolidBrush(GeoColor.GeographicColors.ShallowOcean);

            WorldMapKitWmsDesktopOverlay worldMapKitDesktopOverlay = new WorldMapKitWmsDesktopOverlay();

            winformsMap1.Overlays.Add(worldMapKitDesktopOverlay);

            // Setup the shapefile layer.
            ShapeFileFeatureLayer worldLayer = new ShapeFileFeatureLayer(Samples.RootDirectory + @"Data\Countries02.shp");

            worldLayer.ZoomLevelSet.ZoomLevel01.DefaultAreaStyle    = AreaStyles.CreateSimpleAreaStyle(GeoColor.SimpleColors.Transparent, GeoColor.FromArgb(100, GeoColor.SimpleColors.Green));
            worldLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;

            // Setup the mapshape layer.
            InMemoryFeatureLayer bitmapLayer = new InMemoryFeatureLayer();

            bitmapLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle.PointType = PointType.Bitmap;
            bitmapLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle.Image     = new GeoImage(Samples.RootDirectory + @"Data\Prop Plane.png");
            bitmapLayer.ZoomLevelSet.ZoomLevel01.DefaultLineStyle            = LineStyles.ContestedBorder2;
            bitmapLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel         = ApplyUntilZoomLevel.Level20;

            PointShape     planeShape       = new PointShape(-95.2806, 38.9554);
            PointShape     destinationPoint = new PointShape(36.04, 48.49);
            MultilineShape airLineShape     = planeShape.GreatCircle(destinationPoint);

            bitmapLayer.InternalFeatures.Add("Plane", new Feature(planeShape));
            bitmapLayer.InternalFeatures.Add("AirLine", new Feature(airLineShape));

            LayerOverlay worldOverlay = new LayerOverlay();

            worldOverlay.Layers.Add("WorldLayer", worldLayer);
            winformsMap1.Overlays.Add("WorldOverlay", worldOverlay);

            LayerOverlay planeOverlay = new LayerOverlay();

            planeOverlay.Layers.Add("BitmapLayer", bitmapLayer);
            winformsMap1.Overlays.Add("PlaneOverlay", planeOverlay);

            winformsMap1.CurrentExtent = new RectangleShape(-139.2, 92.4, 120.9, -93.2);
            winformsMap1.Refresh();

            timer.Start();
        }
コード例 #8
0
        public void ShortestLineFeature(Map map, GeoCollection <object> args)
        {
            if (null != map)
            {
                InMemoryFeatureLayer mapShapeLayer     = (InMemoryFeatureLayer)((LayerOverlay)map.CustomOverlays[1]).Layers["InMemoryFeatureLayer"];
                InMemoryFeatureLayer shortestLineLayer = (InMemoryFeatureLayer)((LayerOverlay)map.CustomOverlays[1]).Layers["ShortestLineLayer"];

                BaseShape      areaShape1     = mapShapeLayer.InternalFeatures["AreaShape1"].GetShape();
                BaseShape      areaShape2     = mapShapeLayer.InternalFeatures["AreaShape2"].GetShape();
                MultilineShape multiLineShape = areaShape1.GetShortestLineTo(areaShape2, GeographyUnit.Meter);

                shortestLineLayer.InternalFeatures.Clear();
                shortestLineLayer.InternalFeatures.Add("ShortestLine", new Feature(multiLineShape));
                ((LayerOverlay)map.CustomOverlays[1]).Redraw();
            }
        }
コード例 #9
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.DisplayASimpleMap);

            androidMap               = FindViewById <MapView>(Resource.Id.androidmap);
            androidMap.MapUnit       = GeographyUnit.DecimalDegree;
            androidMap.CurrentExtent = new RectangleShape(0, 100, 100, 0);

            LayerOverlay inMemoryOverlay = new LayerOverlay();

            androidMap.Overlays.Add("InMemoryOverlay", inMemoryOverlay);

            LayerOverlay shortestLineOverlay = new LayerOverlay();

            shortestLineOverlay.TileType = TileType.SingleTile;
            androidMap.Overlays.Add("ShortestLineOverlay", shortestLineOverlay);

            BaseShape areaShape1 = BaseShape.CreateShapeFromWellKnownData("POLYGON((10 20,30 60,40 10,10 20))");
            BaseShape areaShape2 = new EllipseShape(new PointShape(70, 70), 10, 20);

            InMemoryFeatureLayer inMemoryLayer = new InMemoryFeatureLayer();

            inMemoryLayer.ZoomLevelSet.ZoomLevel01.DefaultAreaStyle.FillSolidBrush.Color = GeoColor.FromArgb(125, GeoColor.StandardColors.Gray);
            inMemoryLayer.ZoomLevelSet.ZoomLevel01.DefaultAreaStyle.OutlinePen.Color     = GeoColor.StandardColors.Black;
            inMemoryLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
            inMemoryLayer.InternalFeatures.Add("AreaShape1", new Feature(areaShape1));
            inMemoryLayer.InternalFeatures.Add("AreaShape2", new Feature(areaShape2));
            inMemoryOverlay.Layers.Add("InMemoryFeatureLayer", inMemoryLayer);

            InMemoryFeatureLayer shortestLineLayer = new InMemoryFeatureLayer();

            shortestLineLayer.ZoomLevelSet.ZoomLevel01.DefaultLineStyle.OuterPen.Color = GeoColor.StandardColors.Red;
            shortestLineLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel             = ApplyUntilZoomLevel.Level20;
            shortestLineOverlay.Layers.Add("ShortestLineLayer", shortestLineLayer);

            MultilineShape shortestLine = areaShape1.GetShortestLineTo(areaShape2, GeographyUnit.Meter);

            shortestLineLayer.InternalFeatures.Add("ShortestLine", new Feature(shortestLine));

            SampleViewHelper.InitializeInstruction(this, FindViewById <RelativeLayout>(Resource.Id.MainLayout), GetType());
        }
        private void winformsMap1_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDrawing)
            {
                LayerOverlay         lineOverlay = (LayerOverlay)winformsMap1.Overlays["LineOverlay"];
                InMemoryFeatureLayer shapeLayer  = (InMemoryFeatureLayer)lineOverlay.Layers["Shape"];
                InMemoryFeatureLayer shadowLayer = (InMemoryFeatureLayer)lineOverlay.Layers["Shadow"];

                try
                {
                    shapeLayer.InternalFeatures.Clear();
                    shadowLayer.InternalFeatures.Clear();

                    Point          screenPointEnd = e.Location;
                    RectangleShape extent         = winformsMap1.CurrentExtent;
                    ScreenPointF   currentPoint   = new ScreenPointF(screenPointEnd.X, screenPointEnd.Y);
                    PointShape     endPoint       = ExtentHelper.ToWorldCoordinate(extent, currentPoint, winformsMap1.Width, winformsMap1.Height);

                    shapeLayer.InternalFeatures.Add(new Feature(startPoint));
                    shapeLayer.InternalFeatures.Add(new Feature(endPoint));
                    MultilineShape line = startPoint.GetShortestLineTo(endPoint, GeographyUnit.DecimalDegree);
                    if (line != null)
                    {
                        shapeLayer.InternalFeatures.Add(new Feature(line));
                        LineShape shadow = new LineShape(new Collection <Vertex>()
                        {
                            new Vertex(startPoint.X, startPoint.Y), new Vertex(endPoint.X, endPoint.Y)
                        });
                        shadowLayer.InternalFeatures.Add(new Feature(shadow));
                    }

                    label2.Text = startPoint.GetDistanceTo(endPoint, GeographyUnit.DecimalDegree, DistanceUnit.Kilometer).ToString("N2") + " km.";
                    winformsMap1.Refresh();
                }
                catch
                {
                    return;
                }
            }
        }
コード例 #11
0
        internal static Collection <LineShape> GetLineShapes(Feature feature)
        {
            Collection <LineShape> lineShapes = new Collection <LineShape>();

            LineBaseShape lineBaseShape = feature.GetShape() as LineBaseShape;

            if (lineBaseShape is MultilineShape)
            {
                MultilineShape multiLineShape = lineBaseShape as MultilineShape;
                lineShapes = multiLineShape.Lines;
            }
            else if (lineBaseShape is LineShape)
            {
                lineShapes.Add((LineShape)lineBaseShape);
            }
            else
            {
                throw new NotSupportedException("Only the data which includes the line shapes is supported.");
            }

            return(lineShapes);
        }
コード例 #12
0
        public string GetDistance(Map map, GeoCollection <object> args)
        {
            PointShape           pointShape      = new PointShape(string.Format("POINT ({0} {1})", args[0], args[1]));
            LayerOverlay         dynamicOverlay  = (LayerOverlay)map.CustomOverlays["DynamicOverlay"];
            InMemoryFeatureLayer pointShapeLayer = (InMemoryFeatureLayer)dynamicOverlay.Layers["pointShapeLayer"];
            Feature newPoint = new Feature(pointShape);
            InMemoryFeatureLayer lineShapeLayer = (InMemoryFeatureLayer)dynamicOverlay.Layers["lineShapeLayer"];

            if (Session["StartPoint"] == null)
            {
                pointShapeLayer.InternalFeatures.Clear();
                lineShapeLayer.InternalFeatures.Clear();
            }

            pointShapeLayer.InternalFeatures.Add(newPoint.Id, newPoint);

            string popupContentHtml = string.Empty;

            if (Session["StartPoint"] != null)
            {
                PointShape     startPoint = (PointShape)Session["StartPoint"];
                MultilineShape line       = startPoint.GetShortestLineTo(pointShape, GeographyUnit.DecimalDegree);

                Feature lineFeature   = new Feature(line);
                string  distanceValue = String.Format("<span class='popup'>{0} Mile</span>", line.GetLength(GeographyUnit.DecimalDegree, DistanceUnit.Mile).ToString("N2"));
                lineShapeLayer.InternalFeatures.Add(lineFeature.Id, lineFeature);

                popupContentHtml = distanceValue;

                Session["StartPoint"] = null;
            }
            else
            {
                Session["StartPoint"] = pointShape;
            }

            return(popupContentHtml);
        }
コード例 #13
0
        private Feature GetGreatCircle(Feature feature)
        {
            LineShape line = feature.GetShape() as LineShape;

            if (line != null)
            {
                MultilineShape greatCircle = new MultilineShape();
                for (int i = 0; i < line.Vertices.Count; i++)
                {
                    if (i != line.Vertices.Count - 1)
                    {
                        PointShape     point     = new PointShape(line.Vertices[i]);
                        MultilineShape multiline = point.GreatCircle(new PointShape(line.Vertices[i + 1]));
                        if (multiline != null)
                        {
                            foreach (var l in multiline.Lines)
                            {
                                greatCircle.Lines.Add(l);
                            }
                        }
                    }
                }

                if (greatCircle.Lines.Count > 0)
                {
                    Feature wrapperFeature = new Feature(greatCircle);
                    foreach (var columnValue in feature.ColumnValues)
                    {
                        wrapperFeature.ColumnValues.Add(columnValue.Key, columnValue.Value);
                    }

                    return(wrapperFeature);
                }
            }

            return(null);
        }
コード例 #14
0
        private static Feature GetMultiLineFromCollection(Feature feature)
        {
            var shapeColleciton = (GeometryCollectionShape)feature.GetShape();
            var multiline       = new MultilineShape();

            foreach (var shape in shapeColleciton.Shapes)
            {
                var shapeWellKnownType = shape.GetWellKnownType();

                if (shapeWellKnownType == WellKnownType.Polygon)
                {
                    multiline.Lines.Add(shape as LineShape);
                }
                else if (shapeWellKnownType == WellKnownType.Multipolygon)
                {
                    foreach (var polygon in ((MultilineShape)shape).Lines)
                    {
                        multiline.Lines.Add(polygon);
                    }
                }
            }

            return(new Feature(multiline.GetWellKnownBinary(), feature.Id, feature.ColumnValues));
        }
コード例 #15
0
        private IEnumerable <Feature> InverseClip(FeatureLayer featureLayer, IEnumerable <Feature> clippingFeatures)
        {
            lock (featureLayer)
            {
                if (!featureLayer.IsOpen)
                {
                    featureLayer.Open();
                }
                Collection <Feature> results         = featureLayer.FeatureSource.GetFeaturesOutsideBoundingBox(ExtentHelper.GetBoundingBoxOfItems(clippingFeatures), featureLayer.GetDistinctColumnNames());
                Collection <Feature> sourceFeatures  = new Collection <Feature>();
                SimpleShapeType      simpleShapeType = GisEditor.LayerManager.GetFeatureSimpleShapeType(featureLayer);
                int index = 1;
                if (simpleShapeType == SimpleShapeType.Point)
                {
                    featureLayer.Open();
                    Collection <Feature> allFeatures = featureLayer.FeatureSource.GetAllFeatures(featureLayer.GetDistinctColumnNames());
                    featureLayer.Close();
                    foreach (Feature f in results)
                    {
                        allFeatures.Remove(f);
                    }
                    foreach (var f in InverseClipPoints(allFeatures, clippingFeatures, simpleShapeType))
                    {
                        results.Add(f);
                    }
                }
                else if (simpleShapeType == SimpleShapeType.Line)
                {
                    bool isOpen = false;
                    Proj4ProjectionInfo projectionInfo = featureLayer.GetProj4ProjectionInfo();
                    //MultipolygonShape areaBaseShape = AreaBaseShape.Union(GetValidFeatures(clippingFeatures));
                    List <AreaBaseShape> clippingAreaShapes = GetValidFeatures(clippingFeatures)
                                                              .Select(f => f.GetShape())
                                                              .OfType <AreaBaseShape>()
                                                              .ToList();
                    MultipolygonShape areaBaseShape = AreaBaseShape.Union(clippingAreaShapes);

                    if (projectionInfo != null && projectionInfo.CanProject)
                    {
                        if (featureLayer.IsOpen)
                        {
                            featureLayer.Close();
                            projectionInfo.Close();
                            isOpen = true;
                        }
                        featureLayer.FeatureSource.Projection = null;
                    }
                    featureLayer.Open();
                    featureLayer.FeatureSource.GetFeaturesInsideBoundingBox(areaBaseShape.GetBoundingBox(), featureLayer.GetDistinctColumnNames()).ForEach(f => { if (!areaBaseShape.Contains(f))
                                                                                                                                                                  {
                                                                                                                                                                      sourceFeatures.Add(f);
                                                                                                                                                                  }
                                                                                                                                                           });
                    int count = sourceFeatures.Count;
                    if (projectionInfo != null)
                    {
                        featureLayer.FeatureSource.Projection = projectionInfo.Projection;
                        if (isOpen)
                        {
                            featureLayer.Open();
                        }
                    }
                    if (featureLayer.IsOpen)
                    {
                        featureLayer.Close();
                    }
                    foreach (var feature in sourceFeatures)
                    {
                        isCanceled = ReportProgress(index, count);
                        if (isCanceled)
                        {
                            break;
                        }

                        index++;
                        try
                        {
                            //if (areaBaseShape.IsDisjointed(feature))
                            if (SqlTypesGeometryHelper.IsDisjointed(areaBaseShape, feature))
                            {
                                results.Add(feature);
                            }
                            else
                            {
                                MultilineShape multiLine   = (MultilineShape)feature.GetShape();
                                MultilineShape resultShape = new MultilineShape();
                                foreach (LineShape lineShape in multiLine.Lines)
                                {
                                    //if (areaBaseShape.IsDisjointed(lineShape))
                                    if (SqlTypesGeometryHelper.IsDisjointed(areaBaseShape, lineShape))
                                    {
                                        resultShape.Lines.Add(lineShape);
                                    }
                                    else
                                    {
                                        var resultLine = lineShape.GetDifference(areaBaseShape);
                                        foreach (var line in resultLine.Lines)
                                        {
                                            resultShape.Lines.Add(line);
                                        }
                                    }
                                }
                                if (resultShape != null && resultShape.Lines.Count > 0)
                                {
                                    results.Add(new Feature(resultShape.GetWellKnownBinary(), feature.Id, feature.ColumnValues));
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            GisEditor.LoggerManager.Log(LoggerLevel.Debug, ex.Message, new ExceptionInfo(ex));
                            HandleExceptionFromInvalidFeature(feature.Id, ex.Message);
                        }
                    }
                }
                else if (simpleShapeType == SimpleShapeType.Area)
                {
                    //MultipolygonShape areaBaseShape = AreaBaseShape.Union(GetValidFeatures(clippingFeatures));
                    List <AreaBaseShape> clippingAreaShapes = GetValidFeatures(clippingFeatures)
                                                              .Select(f => f.GetShape())
                                                              .OfType <AreaBaseShape>()
                                                              .ToList();

                    BaseShape         unionResultShape = SqlTypesGeometryHelper.Union(clippingAreaShapes);
                    MultipolygonShape areaBaseShape    = ConvertSqlQueryResultToMultiPolygonShape(unionResultShape);

                    bool isOpen = false;
                    Proj4ProjectionInfo projectionInfo = featureLayer.GetProj4ProjectionInfo();
                    if (projectionInfo != null && projectionInfo.CanProject)
                    {
                        if (featureLayer.IsOpen)
                        {
                            featureLayer.Close();
                            if (projectionInfo != null)
                            {
                                projectionInfo.Close();
                            }
                            isOpen = true;
                        }
                        featureLayer.FeatureSource.Projection = null;
                    }
                    if (!featureLayer.IsOpen)
                    {
                        featureLayer.Open();
                    }
                    featureLayer.FeatureSource.GetFeaturesInsideBoundingBox(areaBaseShape.GetBoundingBox(), featureLayer.GetDistinctColumnNames()).ForEach(f => sourceFeatures.Add(f));
                    if (featureLayer.IsOpen)
                    {
                        featureLayer.Close();
                    }
                    if (projectionInfo != null)
                    {
                        featureLayer.FeatureSource.Projection = projectionInfo.Projection;
                        if (isOpen)
                        {
                            featureLayer.Open();
                        }
                    }

                    int count = sourceFeatures.Count;
                    foreach (var feature in sourceFeatures)
                    {
                        isCanceled = ReportProgress(index, count);
                        if (isCanceled)
                        {
                            break;
                        }

                        index++;
                        try
                        {
                            //if (areaBaseShape.IsDisjointed(feature))
                            if (SqlTypesGeometryHelper.IsDisjointed(areaBaseShape, feature))
                            {
                                results.Add(feature);
                            }
                            else
                            {
                                //var clippedShape = ((AreaBaseShape)feature.GetShape()).GetDifference(areaBaseShape);
                                BaseShape         differenceResultShape = SqlTypesGeometryHelper.GetDifference((AreaBaseShape)feature.GetShape(), areaBaseShape);
                                MultipolygonShape clippedShape          = ConvertSqlQueryResultToMultiPolygonShape(differenceResultShape);
                                if (clippedShape != null && clippedShape.Polygons.Count > 0)
                                {
                                    results.Add(new Feature(clippedShape.GetWellKnownBinary(), feature.Id, feature.ColumnValues));
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            GisEditor.LoggerManager.Log(LoggerLevel.Debug, ex.Message, new ExceptionInfo(ex));
                            HandleExceptionFromInvalidFeature(feature.Id, ex.Message);
                        }
                    }
                }
                else
                {
                    throw new NotSupportedException("The ShapeFileType is not supported.");
                }
                return(results);
            }
        }
コード例 #16
0
        private IEnumerable <Feature> InverseClip(FeatureSource featureSource, IEnumerable <Feature> clippingFeatures)
        {
            lock (featureSource)
            {
                if (!featureSource.IsOpen)
                {
                    featureSource.Open();
                }
                Collection <Feature> results        = featureSource.GetFeaturesOutsideBoundingBox(ExtentHelper.GetBoundingBoxOfItems(clippingFeatures), ReturningColumnsType.AllColumns);
                Collection <Feature> sourceFeatures = new Collection <Feature>();
                ShapeFileType        shapeFileType  = ((ShapeFileFeatureSource)featureSource).GetShapeFileType();
                int index = 1;
                if (shapeFileType == ShapeFileType.Point || shapeFileType == ShapeFileType.Multipoint)
                {
                    featureSource.Open();
                    Collection <Feature> allFeatures = featureSource.GetAllFeatures(ReturningColumnsType.AllColumns);
                    featureSource.Close();
                    foreach (Feature f in results)
                    {
                        allFeatures.Remove(f);
                    }
                    foreach (var f in InverseClipPoints(allFeatures, clippingFeatures, shapeFileType))
                    {
                        results.Add(f);
                    }
                }
                else if (shapeFileType == ShapeFileType.Polyline)
                {
                    bool              isOpen        = false;
                    Projection        tmpProjection = null;
                    MultipolygonShape areaBaseShape = AreaBaseShape.Union(GetValidFeatures(clippingFeatures));
                    if (featureSource.Projection != null &&
                        featureSource.Projection is GISEditorManagedProj4Projection &&
                        ((GISEditorManagedProj4Projection)featureSource.Projection).IsProjectionParametersEqual)
                    {
                        tmpProjection = featureSource.Projection;
                        if (featureSource.IsOpen)
                        {
                            featureSource.Close();
                            featureSource.Projection.Close();
                            isOpen = true;
                        }
                        featureSource.Projection = null;
                    }
                    featureSource.Open();
                    featureSource.GetFeaturesInsideBoundingBox(areaBaseShape.GetBoundingBox(), ReturningColumnsType.AllColumns).ForEach(f => { if (!areaBaseShape.Contains(f))
                                                                                                                                               {
                                                                                                                                                   sourceFeatures.Add(f);
                                                                                                                                               }
                                                                                                                                        });
                    int count = sourceFeatures.Count;
                    if (tmpProjection != null)
                    {
                        featureSource.Projection = tmpProjection;
                        if (isOpen)
                        {
                            featureSource.Open();
                        }
                    }
                    if (featureSource.IsOpen)
                    {
                        featureSource.Close();
                    }
                    foreach (var feature in sourceFeatures)
                    {
                        ReportProgress(index * 100 / count);
                        index++;
                        try
                        {
                            if (areaBaseShape.IsDisjointed(feature))
                            {
                                results.Add(feature);
                            }
                            else
                            {
                                MultilineShape multiLine   = (MultilineShape)feature.GetShape();
                                MultilineShape resultShape = new MultilineShape();
                                foreach (LineShape lineShape in multiLine.Lines)
                                {
                                    if (areaBaseShape.IsDisjointed(lineShape))
                                    {
                                        resultShape.Lines.Add(lineShape);
                                    }
                                    else
                                    {
                                        Collection <PointShape> points = new Collection <PointShape>();
                                        points.Add(new PointShape(lineShape.Vertices[0]));
                                        lineShape.GetIntersection(areaBaseShape).Lines.ForEach(l =>
                                        {
                                            PointShape p1 = new PointShape(l.Vertices[0]);
                                            if (points.Count(p => p.X == p1.X && p.Y == p1.Y && p.Z == p1.Z) <= 0)
                                            {
                                                points.Add(p1);
                                            }
                                            PointShape p2 = new PointShape(l.Vertices[l.Vertices.Count - 1]);
                                            if (points.Count(p => p.X == p2.X && p.Y == p2.Y && p.Z == p2.Z) <= 0)
                                            {
                                                points.Add(p2);
                                            }
                                        });
                                        PointShape endPoint = new PointShape(lineShape.Vertices[lineShape.Vertices.Count - 1]);
                                        if (points.Count(p => p.X == endPoint.X && p.Y == endPoint.Y && p.Z == endPoint.Z) <= 0)
                                        {
                                            points.Add(endPoint);
                                        }

                                        for (int i = 0; i < points.Count; i++)
                                        {
                                            if (i != points.Count - 1)
                                            {
                                                LineBaseShape lineBaseShape = lineShape.GetLineOnALine(points[i], points[i + 1]);

                                                if (!areaBaseShape.Intersects(lineBaseShape.GetCenterPoint()))
                                                {
                                                    resultShape.Lines.Add((LineShape)lineBaseShape);
                                                }
                                            }
                                        }
                                    }
                                }
                                if (resultShape != null && resultShape.Lines.Count > 0)
                                {
                                    results.Add(new Feature(resultShape.GetWellKnownBinary(), feature.Id, feature.ColumnValues));
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            HandleExceptionFromInvalidFeature(feature.Id, ex.Message);
                        }
                    }
                }
                else if (shapeFileType == ShapeFileType.Polygon)
                {
                    MultipolygonShape areaBaseShape = AreaBaseShape.Union(GetValidFeatures(clippingFeatures));

                    bool       isOpen        = false;
                    Projection tmpProjection = null;
                    if (featureSource.Projection != null &&
                        featureSource.Projection is GISEditorManagedProj4Projection &&
                        ((GISEditorManagedProj4Projection)featureSource.Projection).IsProjectionParametersEqual)
                    {
                        tmpProjection = featureSource.Projection;
                        if (featureSource.IsOpen)
                        {
                            featureSource.Close();
                            featureSource.Projection.Close();
                            isOpen = true;
                        }
                        featureSource.Projection = null;
                    }
                    if (!featureSource.IsOpen)
                    {
                        featureSource.Open();
                    }
                    featureSource.GetFeaturesInsideBoundingBox(areaBaseShape.GetBoundingBox(), ReturningColumnsType.AllColumns).ForEach(f => { if (!areaBaseShape.IsDisjointed(f))
                                                                                                                                               {
                                                                                                                                                   sourceFeatures.Add(f);
                                                                                                                                               }
                                                                                                                                        });
                    if (featureSource.IsOpen)
                    {
                        featureSource.Close();
                    }
                    if (tmpProjection != null)
                    {
                        featureSource.Projection = tmpProjection;
                        if (isOpen)
                        {
                            featureSource.Open();
                        }
                    }

                    int count = sourceFeatures.Count;
                    foreach (var feature in sourceFeatures)
                    {
                        ReportProgress(index * 100 / count);
                        index++;
                        try
                        {
                            if (areaBaseShape.IsDisjointed(feature))
                            {
                                results.Add(feature);
                            }
                            else
                            {
                                var clippedShape = ((AreaBaseShape)feature.GetShape()).GetDifference(areaBaseShape);
                                if (clippedShape != null && clippedShape.Polygons.Count > 0)
                                {
                                    results.Add(new Feature(clippedShape.GetWellKnownBinary(), feature.Id, feature.ColumnValues));
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            HandleExceptionFromInvalidFeature(feature.Id, ex.Message);
                        }
                    }
                }
                else
                {
                    throw new NotSupportedException("The ShapeFileType is not supported.");
                }
                return(results);
            }
        }
コード例 #17
0
ファイル: MBTilesGenerator.cs プロジェクト: bymin/EasyGIS.NET
        private static void ProcessLineShape(int zoom, int tileSize, RectangleInt tileScreenBoundingBox, TileFeature tileFeature, MultilineShape multiLineShape, int simplificationFactor, RectangleShape tileBoundingBox)
        {
            foreach (LineShape line in multiLineShape.Lines)
            {
                PointInt[] pixelPoints = new PointInt[line.Vertices.Count];
                for (int n = 0; n < line.Vertices.Count; ++n)
                {
                    pixelPoints[n] = WorldPointToTilePoint(line.Vertices[n].X, line.Vertices[n].Y, zoom, tileSize, tileBoundingBox);
                }

                PointInt[] simplifiedPixelPoints = SimplifyPointData(pixelPoints, simplificationFactor);

                //output count may be zero for short records at low zoom levels as
                //the pixel coordinates wil be a single point after simplification
                if (simplifiedPixelPoints.Length > 0)
                {
                    List <int> clippedPoints = new List <int>();
                    List <int> parts         = new List <int>();
                    ClipPolyline(simplifiedPixelPoints, tileScreenBoundingBox, clippedPoints, parts);
                    if (parts.Count > 0)
                    {
                        //output the clipped polyline
                        for (int n = 0; n < parts.Count; ++n)
                        {
                            int index1 = parts[n];
                            int index2 = n < parts.Count - 1 ? parts[n + 1] : clippedPoints.Count;

                            List <PointInt> lineString = new List <PointInt>();
                            tileFeature.Geometry.Add(lineString);
                            //clipped points store separate x/y pairs so there will be two values per measure
                            for (int i = index1; i < index2; i += 2)
                            {
                                lineString.Add(new PointInt(clippedPoints[i], clippedPoints[i + 1]));
                            }
                        }
                    }
                }
            }
        }
コード例 #18
0
ファイル: MBTilesGenerator.cs プロジェクト: bymin/EasyGIS.NET
        private static TileFeature GetVectorTileFeature(Feature feature, int zoom, int tileSize, RectangleInt tileScreenBoundingBox, int simplificationFactor, RectangleShape tileBoundingBox)
        {
            TileFeature tileFeature = new TileFeature();

            switch (feature.GetWellKnownType())
            {
            case WellKnownType.Line:
            case WellKnownType.Multiline:
                tileFeature.Type = GeometryType.LineString;
                MultilineShape multiLineShape = new MultilineShape(feature.GetWellKnownBinary());
                ProcessLineShape(zoom, tileSize, tileScreenBoundingBox, tileFeature, multiLineShape, simplificationFactor, tileBoundingBox);
                break;

            case WellKnownType.Polygon:
            case WellKnownType.Multipolygon:
                tileFeature.Type = GeometryType.Polygon;
                MultipolygonShape multiPolygonShape = new MultipolygonShape(feature.GetWellKnownBinary());
                foreach (PolygonShape polygonShape in multiPolygonShape.Polygons)
                {
                    ProcessRingShape(zoom, tileSize, tileScreenBoundingBox, tileFeature, polygonShape.OuterRing, simplificationFactor, tileBoundingBox);
                    foreach (RingShape ringShape in polygonShape.InnerRings)
                    {
                        ProcessRingShape(zoom, tileSize, tileScreenBoundingBox, tileFeature, ringShape, simplificationFactor, tileBoundingBox);
                    }
                }
                break;

            case WellKnownType.Point:
            case WellKnownType.Multipoint:
                tileFeature.Type = GeometryType.Point;
                List <PointInt> coordinates = new List <PointInt>();

                MultipointShape multiPointShape = new MultipointShape();

                if (feature.GetWellKnownType() == WellKnownType.Point)
                {
                    PointShape pointShape = new PointShape(feature.GetWellKnownBinary());
                    multiPointShape.Points.Add(pointShape);
                }
                else if (feature.GetWellKnownType() == WellKnownType.Multipoint)
                {
                    multiPointShape = new MultipointShape(feature.GetWellKnownBinary());
                }

                foreach (PointShape point in multiPointShape.Points)
                {
                    PointInt pointI = WorldPointToTilePoint(point.X, point.Y, zoom, tileSize, tileBoundingBox);
                    coordinates.Add(new PointInt(pointI.X, pointI.Y));
                }
                if (coordinates.Count > 0)
                {
                    tileFeature.Geometry.Add(coordinates);
                }
                break;

            default:
                tileFeature.Type = GeometryType.Unknown;
                break;
            }

            //add the record attributes
            foreach (var attributes in feature.ColumnValues)
            {
                tileFeature.Attributes.Add(new TileAttribute(attributes.Key, attributes.Value));
            }

            return(tileFeature);
        }
コード例 #19
0
        // Tuple
        // item1: columnName,
        // item2: columnType,
        // item3: OperatorMode.
        public static Collection <Feature> Dissolve(IEnumerable <string> dissolveColumnNames
                                                    , IEnumerable <Tuple <string, string, DissolveOperatorMode> > pairedColumnStrategies
                                                    , IEnumerable <Feature> featuresToDissovle)
        {
            var featureGroupByShapeType = featuresToDissovle.GroupBy(f =>
            {
                return(f.GetShape().GetType());
            });

            Collection <Feature> dissolveFeatures = new Collection <Feature>();
            Action <IGrouping <Type, Feature>, Action <IEnumerable <Feature>, Dictionary <string, string> > > dissolveAction
                = new Action <IGrouping <Type, Feature>, Action <IEnumerable <Feature>, Dictionary <string, string> > >
                      ((groupByType, finalProcessAction) =>
            {
                var groupByColumns = GroupByColumns(groupByType, dissolveColumnNames);
                groupByColumns.ForEach(groupFeature =>
                {
                    Dictionary <string, string> newColumnValues = new Dictionary <string, string>();
                    foreach (var tmpMatchColumn in dissolveColumnNames)
                    {
                        newColumnValues.Add(tmpMatchColumn, groupFeature.First().ColumnValues[tmpMatchColumn]);
                    }

                    foreach (var operatorPair in pairedColumnStrategies)
                    {
                        CollectNewColumnValues(groupFeature, newColumnValues, operatorPair);
                    }

                    newColumnValues.Add("Count", groupFeature.Count().ToString());

                    try
                    {
                        if (finalProcessAction != null)
                        {
                            finalProcessAction(groupFeature, newColumnValues);
                        }
                    }
                    catch (Exception ex)
                    {
                        GisEditor.LoggerManager.Log(LoggerLevel.Debug, ex.Message, new ExceptionInfo(ex));
                    }
                });
            });

            featureGroupByShapeType.ForEach(groupByType =>
            {
                if (groupByType.Key.IsSubclassOf(typeof(AreaBaseShape)))
                {
                    dissolveAction(groupByType, (tmpFeatures, tmpColumnValues) =>
                    {
                        MultipolygonShape dissolveShape = AreaBaseShape.Union(GetValidFeatures(tmpFeatures));
                        if (dissolveShape != null)
                        {
                            Feature dissolveFeature = new Feature(dissolveShape, tmpColumnValues);
                            dissolveFeatures.Add(dissolveFeature);
                        }
                    });
                }
                else if (groupByType.Key.IsSubclassOf(typeof(LineBaseShape)))
                {
                    dissolveAction(groupByType, (tmpFeatures, tmpColumnValues) =>
                    {
                        //MultilineShape dissolveShape = LineBaseShape.Union(tmpFeatures);
                        //Feature dissolveFeature = new Feature(dissolveShape, tmpColumnValues);
                        //dissolveFeatures.Add(dissolveFeature);
                        MultilineShape dissolveShape = new MultilineShape();
                        tmpFeatures.ForEach(tmpFeature =>
                        {
                            BaseShape tmpShape      = tmpFeature.GetShape();
                            LineShape tmpLine       = tmpShape as LineShape;
                            MultilineShape tmpMLine = tmpShape as MultilineShape;
                            if (tmpLine != null)
                            {
                                dissolveShape.Lines.Add(tmpLine);
                            }
                            else if (tmpMLine != null)
                            {
                                tmpMLine.Lines.ForEach(tmpLineInMLine => dissolveShape.Lines.Add(tmpLineInMLine));
                            }
                        });

                        if (dissolveShape.Lines.Count > 0)
                        {
                            dissolveFeatures.Add(new Feature(dissolveShape, tmpColumnValues));
                        }
                    });
                }
                else if (groupByType.Key.IsSubclassOf(typeof(PointBaseShape)))
                {
                    dissolveAction(groupByType, (tmpFeatures, tmpColumnValues) =>
                    {
                        MultipointShape multipointShape = new MultipointShape();
                        tmpFeatures.ForEach(tmpFeature =>
                        {
                            BaseShape tmpShape        = tmpFeature.GetShape();
                            PointShape tmpPoint       = tmpShape as PointShape;
                            MultipointShape tmpMPoint = tmpShape as MultipointShape;
                            if (tmpPoint != null)
                            {
                                multipointShape.Points.Add(tmpPoint);
                            }
                            else if (tmpMPoint != null)
                            {
                                tmpMPoint.Points.ForEach(tmpPointInMPointShape => multipointShape.Points.Add(tmpPointInMPointShape));
                            }
                        });
                        dissolveFeatures.Add(new Feature(multipointShape, tmpColumnValues));
                    });
                }
            });

            return(dissolveFeatures);
        }
コード例 #20
0
        private void Dissolve()
        {
            try
            {
                Collection <Feature> dissolvedFeatures = new Collection <Feature>();
                // get features to dissolve.
                Collection <Feature> featuresToDissolve = GetFeaturesToDissolve();
                // group features.
                var featureGroupByShapeType = featuresToDissolve.GroupBy(f =>
                {
                    return(f.GetShape().GetType());
                });

                Action <IGrouping <Type, Feature>, Action <IEnumerable <Feature>, Dictionary <string, string> > > dissolveAction
                    = new Action <IGrouping <Type, Feature>, Action <IEnumerable <Feature>, Dictionary <string, string> > >
                          ((groupByType, finalProcessAction) =>
                {
                    //CancelTask(this.CancellationSource.Token, content, parameter);
                    var groupByColumns = GroupByColumns(groupByType, this.matchColumns);
                    groupByColumns.ForEach(groupFeature =>
                    {
                        //CancelTask(this.CancellationSource.Token, content, parameter);
                        Dictionary <string, string> newColumnValues = new Dictionary <string, string>();
                        foreach (var tmpMatchColumn in this.matchColumns)
                        {
                            newColumnValues.Add(tmpMatchColumn, groupFeature.First().ColumnValues[tmpMatchColumn]);
                        }

                        foreach (var operatorPair in this.operatorPairs)
                        {
                            //CancelTask(this.CancellationSource.Token, content, parameter);
                            CollectNewColumnValues(groupFeature, newColumnValues, operatorPair);
                        }

                        newColumnValues.Add("Count", groupFeature.Count().ToString());

                        try
                        {
                            if (finalProcessAction != null)
                            {
                                finalProcessAction(groupFeature, newColumnValues);
                            }
                        }
                        catch { }
                    });
                });

                featureGroupByShapeType.ForEach(groupByType =>
                {
                    //CancelTask(this.CancellationSource.Token, content, parameter);
                    if (groupByType.Key.IsSubclassOf(typeof(AreaBaseShape)))
                    {
                        dissolveAction(groupByType, (tmpFeatures, tmpColumnValues) =>
                        {
                            MultipolygonShape dissolveShape = AreaBaseShape.Union(GetValidFeatures(tmpFeatures));
                            if (dissolveShape != null)
                            {
                                Feature dissolveFeature = new Feature(dissolveShape, tmpColumnValues);
                                dissolvedFeatures.Add(dissolveFeature);
                            }
                        });
                    }
                    else if (groupByType.Key.IsSubclassOf(typeof(LineBaseShape)))
                    {
                        dissolveAction(groupByType, (tmpFeatures, tmpColumnValues) =>
                        {
                            //MultilineShape dissolveShape = LineBaseShape.Union(tmpFeatures);
                            //Feature dissolveFeature = new Feature(dissolveShape, tmpColumnValues);
                            //dissolveFeatures.Add(dissolveFeature);
                            MultilineShape dissolveShape = new MultilineShape();
                            tmpFeatures.ForEach(tmpFeature =>
                            {
                                BaseShape tmpShape      = tmpFeature.GetShape();
                                LineShape tmpLine       = tmpShape as LineShape;
                                MultilineShape tmpMLine = tmpShape as MultilineShape;
                                if (tmpLine != null)
                                {
                                    dissolveShape.Lines.Add(tmpLine);
                                }
                                else if (tmpMLine != null)
                                {
                                    tmpMLine.Lines.ForEach(tmpLineInMLine => dissolveShape.Lines.Add(tmpLineInMLine));
                                }
                            });

                            if (dissolveShape.Lines.Count > 0)
                            {
                                dissolvedFeatures.Add(new Feature(dissolveShape, tmpColumnValues));
                            }
                        });
                    }
                    else if (groupByType.Key.IsSubclassOf(typeof(PointBaseShape)))
                    {
                        dissolveAction(groupByType, (tmpFeatures, tmpColumnValues) =>
                        {
                            MultipointShape multipointShape = new MultipointShape();
                            tmpFeatures.ForEach(tmpFeature =>
                            {
                                BaseShape tmpShape        = tmpFeature.GetShape();
                                PointShape tmpPoint       = tmpShape as PointShape;
                                MultipointShape tmpMPoint = tmpShape as MultipointShape;
                                if (tmpPoint != null)
                                {
                                    multipointShape.Points.Add(tmpPoint);
                                }
                                else if (tmpMPoint != null)
                                {
                                    tmpMPoint.Points.ForEach(tmpPointInMPointShape => multipointShape.Points.Add(tmpPointInMPointShape));
                                }
                            });
                            dissolvedFeatures.Add(new Feature(multipointShape, tmpColumnValues));
                        });
                    }
                });

                // collect export columns.
                var filteredFeatureColumns = new Collection <FeatureSourceColumn>();
                foreach (var matchColumn in this.matchColumns)
                {
                    var tmpColumn = featureColumns.FirstOrDefault(f => f.ColumnName.Equals(matchColumn, StringComparison.Ordinal));
                    if (tmpColumn != null)
                    {
                        filteredFeatureColumns.Add(tmpColumn);
                    }
                }

                foreach (var extraColumn in this.operatorPairs)
                {
                    var tmpColumn = featureColumns.FirstOrDefault(f => f.ColumnName.Equals(extraColumn.ColumnName, StringComparison.Ordinal));
                    if (tmpColumn != null)
                    {
                        filteredFeatureColumns.Add(tmpColumn);
                    }
                }

                filteredFeatureColumns.Add(new FeatureSourceColumn("Count", "Integer", 8));

                string saveFolder = Path.GetDirectoryName(outputPath);
                if (!Directory.Exists(saveFolder))
                {
                    Directory.CreateDirectory(saveFolder);
                }

                ShpFileExporter exporter = new ShpFileExporter();
                exporter.ExportToFile(new FileExportInfo(dissolvedFeatures, filteredFeatureColumns, outputPath, Wkt));
            }
            catch (Exception e)
            {
            }
            finally
            {
                var args = new UpdatingProgressLongRunningTaskPluginEventArgs(LongRunningTaskState.Updating);
                args.Message = "Finished";

                OnUpdatingProgress(args);
            }
        }
コード例 #21
0
        private void btnCalculate_Click(object sender, RoutedEventArgs e)
        {
            //Get a reference to the results MapShapeLayer and clear it so we can display our new results.
            MapShapeLayer results = (MapShapeLayer)((LayerOverlay)mapView.Overlays["layerOverlay"]).Layers["Results"];

            results.MapShapes.Clear();

            //Get a reference to the test data layer.
            InMemoryFeatureLayer testDataLayer = (InMemoryFeatureLayer)((LayerOverlay)mapView.Overlays["layerOverlay"]).Layers["TestData"];

            //Check to see if the test data has been edited.
            if (mapView.EditOverlay.EditShapesLayer.InternalFeatures.Count > 0)
            {
                //Loop through the edited test data and update the test data layer.
                testDataLayer.EditTools.BeginTransaction();
                foreach (Feature feature in mapView.EditOverlay.EditShapesLayer.InternalFeatures)
                {
                    testDataLayer.EditTools.Update(feature.CloneDeep());
                }
                testDataLayer.EditTools.CommitTransaction();
                //Clear out the EditOverlay since we are done editing.
                mapView.EditOverlay.EditShapesLayer.InternalFeatures.Clear();
                //Since we are done editing, turn visibility back on the for the layer overlay so we can see our test data again.
                mapView.Overlays["layerOverlay"].IsVisible = true;
            }

            //Get the test point feature from the test data layer.
            Feature testPointFeature = testDataLayer.QueryTools.GetFeaturesByColumnValue("Name", "TestPoint", ReturningColumnsType.AllColumns)[0];
            //Get the test line feature from the test data layer.
            Feature testLineFeature = testDataLayer.QueryTools.GetFeaturesByColumnValue("Name", "TestLine", ReturningColumnsType.AllColumns)[0];
            //Take the test line feature and create a line shape so we can use line-specific APIs for finding the shortest line and line-on-line.
            LineShape testLine = new MultilineShape(testLineFeature.GetWellKnownText()).Lines[0];

            //Calculate the shortest line between our test line and test point.
            LineShape shortestLineResult = testLine.GetShortestLineTo(testPointFeature.GetShape(), GeographyUnit.Meter).Lines[0];
            //Take the result and create a MapShape so we can display the shortest line on the map in a blue color.
            MapShape shortestLine = new MapShape(new Feature(shortestLineResult));

            shortestLine.ZoomLevels.ZoomLevel01.DefaultLineStyle    = LineStyle.CreateSimpleLineStyle(GeoColors.Blue, 4, false);
            shortestLine.ZoomLevels.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
            results.MapShapes.Add("ShortestLine", shortestLine);
            string message = "Length of Blue Line is: " + shortestLineResult.GetLength(GeographyUnit.Meter, DistanceUnit.Kilometer).ToString() + " KM" + '\n';

            //Split the test line from the left side based on where the shortest line touches it.
            LineBaseShape leftSideOfLineResult = testLine.GetLineOnALine(new PointShape(testLine.Vertices[0]), new PointShape(shortestLineResult.Vertices[0]));

            //Make sure the split was valid and the closest point wasn't at the beginning or end of the line.
            if (leftSideOfLineResult.Validate(ShapeValidationMode.Simple).IsValid)
            {
                MapShape leftSideOfLine = new MapShape(new Feature(leftSideOfLineResult));
                leftSideOfLine.ZoomLevels.ZoomLevel01.DefaultLineStyle    = LineStyle.CreateSimpleLineStyle(GeoColors.Green, 2, false);
                leftSideOfLine.ZoomLevels.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
                results.MapShapes.Add("LeftSideofLine", leftSideOfLine);
                message += "Length of Green Line is: " + leftSideOfLineResult.GetLength(GeographyUnit.Meter, DistanceUnit.Kilometer).ToString() + " KM" + '\n';
            }

            //Split the test line from the right side based on where the shortest line touches it.
            LineBaseShape rightSideOfLineResult = testLine.GetLineOnALine(new PointShape(shortestLineResult.Vertices[0]), new PointShape(testLine.Vertices[testLine.Vertices.Count - 1]));

            //Make sure the split was valid and the closest point wasn't at the beginning or end of the line.
            if (rightSideOfLineResult.Validate(ShapeValidationMode.Simple).IsValid)
            {
                MapShape rightSideOfLine = new MapShape(new Feature(rightSideOfLineResult));
                rightSideOfLine.ZoomLevels.ZoomLevel01.DefaultLineStyle    = LineStyle.CreateSimpleLineStyle(GeoColors.Yellow, 2, false);
                rightSideOfLine.ZoomLevels.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
                results.MapShapes.Add("RightSideofLine", rightSideOfLine);
                message += "Length of Yellow Line is: " + rightSideOfLineResult.GetLength(GeographyUnit.Meter, DistanceUnit.Kilometer).ToString() + " KM" + '\n';
            }
            //Display the length of each line in kilometers.
            message += "Length of Red Line is: " + testLine.GetLength(GeographyUnit.Meter, DistanceUnit.Kilometer).ToString() + " KM";
            mapView.Refresh();
            MessageBox.Show(message, "Results");
        }
コード例 #22
0
        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            PointShape start = Points[((ComboBoxItem)cmbStart.SelectedItem).Content.ToString()];
            PointShape end   = Points[((ComboBoxItem)cmbEnd.SelectedItem).Content.ToString()];

            LineShape startSegment = GetNearestSegment(start);
            LineShape endSegment   = GetNearestSegment(end);

            LineShape route = new LineShape();

            if (startSegment.Id == endSegment.Id)
            {
                route = startSegment.GetLineOnALine(start, end) as LineShape;
            }
            else
            {
                double         tolerance        = double.Parse(txtTolerance.Text, CultureInfo.InvariantCulture);
                PolygonShape   bufferedPolygon  = endSegment.Buffer(tolerance, GeographyUnit.DecimalDegree, DistanceUnit.Meter).Polygons[0];
                MultilineShape intersectedLines = startSegment.GetIntersection(bufferedPolygon) as MultilineShape;
                if (intersectedLines.Lines.Count > 0)     // Just check the intersected within allowed tolerance.
                {
                    PointShape intersectedPoint = intersectedLines.Lines[0].GetCenterPoint();

                    PointShape nearestPointOnStart = intersectedPoint.GetClosestPointTo(startSegment, GeographyUnit.DecimalDegree);
                    PointShape nearestPointOnEnd   = intersectedPoint.GetClosestPointTo(endSegment, GeographyUnit.DecimalDegree);

                    LineShape routeSegmentOnStart = startSegment.GetLineOnALine(start, nearestPointOnStart) as LineShape;
                    LineShape routeSegmentOnEnd   = endSegment.GetLineOnALine(end, nearestPointOnEnd) as LineShape;

                    IEnumerable <Vertex> vertexs = route.Vertices;
                    int index = IndexOf(routeSegmentOnStart.Vertices, new Vertex(nearestPointOnStart));
                    if (index == 0)
                    {
                        vertexs = vertexs.Concat(routeSegmentOnStart.Vertices.Reverse());
                    }
                    else
                    {
                        vertexs = vertexs.Concat(routeSegmentOnStart.Vertices);
                    }

                    index = IndexOf(routeSegmentOnEnd.Vertices, new Vertex(nearestPointOnEnd));
                    if (index == 0)
                    {
                        vertexs = vertexs.Concat(routeSegmentOnEnd.Vertices);
                    }
                    else
                    {
                        vertexs = vertexs.Concat(routeSegmentOnEnd.Vertices.Reverse());
                    }

                    route = new LineShape(vertexs);
                }
            }

            routeResultLayer.InternalFeatures.Clear();
            if (route.Vertices.Count > 1)
            {
                routeResultLayer.InternalFeatures.Add(new Feature(route));
            }
            else
            {
                MessageBox.Show("No Route Found.");
            }

            Map1.Refresh();
        }
コード例 #23
0
        private static Feature MakeFeatureValidate(Feature feature)
        {
            Feature validFeature = feature.MakeValid();

            WellKnownType featureType   = feature.GetWellKnownType();
            WellKnownType validatedType = validFeature.GetWellKnownType();

            Feature result = validFeature;

            if (validatedType != featureType &&
                validatedType == WellKnownType.GeometryCollection)
            {
                GeometryCollectionShape geoCollectionShape = validFeature.GetShape() as GeometryCollectionShape;
                if (geoCollectionShape != null)
                {
                    BaseShape resultShape = null;
                    switch (featureType)
                    {
                    case WellKnownType.Point:
                    case WellKnownType.Multipoint:
                        Collection <PointShape> points = new Collection <PointShape>();
                        foreach (var shape in geoCollectionShape.Shapes)
                        {
                            PointShape point = shape as PointShape;
                            if (point != null)
                            {
                                points.Add(point);
                            }
                        }
                        resultShape = new MultipointShape(points);
                        break;

                    case WellKnownType.Line:
                    case WellKnownType.Multiline:
                        Collection <LineShape> lines = new Collection <LineShape>();
                        foreach (var shape in geoCollectionShape.Shapes)
                        {
                            LineShape line = shape as LineShape;
                            if (line != null)
                            {
                                lines.Add(line);
                            }
                        }
                        resultShape = new MultilineShape(lines);
                        break;

                    case WellKnownType.Polygon:
                    case WellKnownType.Multipolygon:
                        Collection <PolygonShape> polygons = new Collection <PolygonShape>();
                        foreach (var shape in geoCollectionShape.Shapes)
                        {
                            PolygonShape polygon = shape as PolygonShape;
                            if (polygon != null)
                            {
                                polygons.Add(polygon);
                            }
                        }
                        resultShape = new MultipolygonShape(polygons);
                        break;

                    default:
                        break;
                    }

                    if (resultShape != null)
                    {
                        result = new Feature(resultShape);
                    }
                }
            }

            return(result);
        }
コード例 #24
0
        //private IEnumerable<string> GetMatchColumnsFromString(string matchColumnsInString)
        //{
        //    string[] columns = matchColumnsInString.Split(',');
        //    return columns;
        //}

        private void Dissolve()
        {
            Collection <Feature> dissolvedFeatures = new Collection <Feature>();

            // get features to dissolve.
            Collection <Feature> featuresToDissolve = GetFeaturesToDissolve();

            // group features.
            var featureGroupByShapeType = featuresToDissolve.GroupBy(f =>
            {
                return(f.GetShape().GetType());
            });

            // collect export columns.
            var filteredFeatureColumns = new Collection <FeatureSourceColumn>();

            foreach (var matchColumn in this.matchColumns)
            {
                var tmpColumn = featureColumns.FirstOrDefault(f => f.ColumnName.Equals(matchColumn, StringComparison.Ordinal));
                if (tmpColumn != null)
                {
                    filteredFeatureColumns.Add(tmpColumn);
                }
            }

            foreach (var extraColumn in this.operatorPairs)
            {
                var tmpColumn = featureColumns.FirstOrDefault(f => f.ColumnName.Equals(extraColumn.ColumnName, StringComparison.Ordinal));
                if (tmpColumn != null)
                {
                    filteredFeatureColumns.Add(tmpColumn);
                }
            }

            filteredFeatureColumns.Add(new FeatureSourceColumn("Count", "Integer", 8));

            Action <IGrouping <Type, Feature>, Action <IEnumerable <Feature>, Dictionary <string, string> > > dissolveAction
                = new Action <IGrouping <Type, Feature>, Action <IEnumerable <Feature>, Dictionary <string, string> > >
                      ((groupByType, finalProcessAction) =>
            {
                //CancelTask(this.CancellationSource.Token, content, parameter);
                var groupByColumns = GroupByColumns(groupByType, this.matchColumns);
                groupByColumns.ForEach(groupFeature =>
                {
                    //CancelTask(this.CancellationSource.Token, content, parameter);
                    Dictionary <string, string> newColumnValues = new Dictionary <string, string>();
                    foreach (var tmpMatchColumn in this.matchColumns)
                    {
                        newColumnValues.Add(tmpMatchColumn, groupFeature.First().ColumnValues[tmpMatchColumn]);
                    }

                    foreach (var operatorPair in this.operatorPairs)
                    {
                        //CancelTask(this.CancellationSource.Token, content, parameter);
                        CollectNewColumnValues(groupFeature, newColumnValues, operatorPair);
                        var value        = newColumnValues[operatorPair.ColumnName];
                        var resultColumn = filteredFeatureColumns.FirstOrDefault(c => c.ColumnName.Equals(operatorPair.ColumnName));
                        if (resultColumn != null)
                        {
                            if (resultColumn.MaxLength < value.Length)
                            {
                                var indexOf = filteredFeatureColumns.IndexOf(resultColumn);
                                filteredFeatureColumns.RemoveAt(indexOf);
                                var newColumn = new FeatureSourceColumn(resultColumn.ColumnName, resultColumn.TypeName, value.Length);
                                filteredFeatureColumns.Insert(indexOf, newColumn);
                            }
                        }
                    }

                    newColumnValues.Add("Count", groupFeature.Count().ToString());

                    try
                    {
                        if (finalProcessAction != null)
                        {
                            finalProcessAction(groupFeature, newColumnValues);
                        }
                    }
                    catch (Exception e)
                    {
                        GisEditor.LoggerManager.Log(LoggerLevel.Debug, e.Message, new ExceptionInfo(e));
                        throw e;
                    }
                });
            });

            foreach (var groupByType in featureGroupByShapeType)
            {
                try
                {
                    //CancelTask(this.CancellationSource.Token, content, parameter);
                    if (groupByType.Key.IsSubclassOf(typeof(AreaBaseShape)))
                    {
                        dissolveAction(groupByType, (tmpFeatures, tmpColumnValues) =>
                        {
                            //MultipolygonShape dissolveShape = AreaBaseShape.Union(GetValidFeatures(tmpFeatures));
                            List <AreaBaseShape> areaShapes = GetValidFeatures(tmpFeatures)
                                                              .Select(f => f.GetShape())
                                                              .OfType <AreaBaseShape>()
                                                              .ToList();

                            MultipolygonShape dissolveShape = (MultipolygonShape)SqlTypesGeometryHelper.Union(areaShapes);

                            if (dissolveShape != null)
                            {
                                Feature dissolveFeature = new Feature(dissolveShape, tmpColumnValues);
                                dissolvedFeatures.Add(dissolveFeature);
                            }
                        });
                    }
                    else if (groupByType.Key.IsSubclassOf(typeof(LineBaseShape)))
                    {
                        dissolveAction(groupByType, (tmpFeatures, tmpColumnValues) =>
                        {
                            MultilineShape dissolveShape = new MultilineShape();
                            tmpFeatures.ForEach(tmpFeature =>
                            {
                                BaseShape tmpShape      = tmpFeature.GetShape();
                                LineShape tmpLine       = tmpShape as LineShape;
                                MultilineShape tmpMLine = tmpShape as MultilineShape;
                                if (tmpLine != null)
                                {
                                    dissolveShape.Lines.Add(tmpLine);
                                }
                                else if (tmpMLine != null)
                                {
                                    tmpMLine.Lines.ForEach(tmpLineInMLine => dissolveShape.Lines.Add(tmpLineInMLine));
                                }
                            });

                            if (dissolveShape.Lines.Count > 0)
                            {
                                dissolvedFeatures.Add(new Feature(dissolveShape, tmpColumnValues));
                            }
                        });
                    }
                    else if (groupByType.Key.IsSubclassOf(typeof(PointBaseShape)))
                    {
                        dissolveAction(groupByType, (tmpFeatures, tmpColumnValues) =>
                        {
                            MultipointShape multipointShape = new MultipointShape();
                            tmpFeatures.ForEach(tmpFeature =>
                            {
                                BaseShape tmpShape        = tmpFeature.GetShape();
                                PointShape tmpPoint       = tmpShape as PointShape;
                                MultipointShape tmpMPoint = tmpShape as MultipointShape;
                                if (tmpPoint != null)
                                {
                                    multipointShape.Points.Add(tmpPoint);
                                }
                                else if (tmpMPoint != null)
                                {
                                    tmpMPoint.Points.ForEach(tmpPointInMPointShape => multipointShape.Points.Add(tmpPointInMPointShape));
                                }
                            });
                            dissolvedFeatures.Add(new Feature(multipointShape, tmpColumnValues));
                        });
                    }
                    if (isCanceled)
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    var errorEventArgs = new UpdatingTaskProgressEventArgs(TaskState.Error);
                    errorEventArgs.Error = new ExceptionInfo(string.Format(CultureInfo.InvariantCulture, "Feature id: {0}, {1}"
                                                                           , groupByType.FirstOrDefault().Id, ex.Message)
                                                             , ex.StackTrace
                                                             , ex.Source);
                    GisEditor.LoggerManager.Log(LoggerLevel.Debug, ex.Message, new ExceptionInfo(ex));
                    errorEventArgs.Message = groupByType.FirstOrDefault().Id;
                    OnUpdatingProgress(errorEventArgs);
                    continue;
                }
            }
            if (!isCanceled)
            {
                string saveFolder = Path.GetDirectoryName(outputPathFileName);
                if (!Directory.Exists(saveFolder))
                {
                    Directory.CreateDirectory(saveFolder);
                }

                var info = new FileExportInfo(dissolvedFeatures, filteredFeatureColumns, outputPathFileName, Wkt);
                Export(info);
            }
        }