Beispiel #1
0
        public static DataRow FindIntersection(double latitude, double longitude, string ShapePath)
        {
            DataRow returnValue = null;

            if (!string.IsNullOrWhiteSpace(ShapePath))
            {
                string ShapeFilePath = Path.GetFileNameWithoutExtension(ShapePath);
                var    featureSet    = Shapefile.Open(ShapePath + ".shp");
                var    coordinate    = Project(ShapePath + ".prj", longitude, latitude);
                if (double.IsNaN(coordinate[0]) || double.IsNaN(coordinate[1]))
                {
                    return(returnValue);
                }

                foreach (var feature in featureSet.Features)
                {
                    if (feature.ShapeIndex.Intersects(new DotSpatial.Topology.Coordinate(coordinate)))
                    {
                        return(feature.DataRow);
                    }
                }
            }

            return(returnValue);
        }
Beispiel #2
0
        void showmap(int lv)
        {
            var shp = new Shapefile();

            shp.Open(label1.Text);

            var lt = WorldToGps(shp.Extents.xMin, shp.Extents.yMax, lv);
            var rt = WorldToGps(shp.Extents.xMax, shp.Extents.yMax, lv);
            var lb = WorldToGps(shp.Extents.xMin, shp.Extents.yMin, lv);

            var w = getdist(lt, rt); var h = getdist(lt, lb);

            var img = new Bitmap(8192, 8192);
            var g   = Graphics.FromImage(img);

            for (var i = 0; i < shp.NumShapes; i++)
            {
                var sp  = shp.Shape[i];
                var pts = new List <PointF>();
                for (var p = 0; p < sp.numPoints; p++)
                {
                    var lg  = sp.Point[p];
                    var pot = WorldToGps(lg.x, lg.y, lv);
                    pot.X = (pot.X - lt.X) * 256;
                    pot.Y = (pot.Y - lt.Y) * 256;
                    pts.Add(pot);
                }
                g.DrawPolygon(Pens.Red, pts.ToArray());
            }
            g.Dispose();
            img.Save("d:\\ss.jpg");
            pictureBox1.Image = img;
        }
Beispiel #3
0
 // <summary>
 // Opens a shapefile, registers event handler
 // </summary>
 public void ToolTip(AxMap axMap1)
 {
     axMap1.Projection = tkMapProjection.PROJECTION_NONE;
     foreach (var filename in _l)
     {
         if (!File.Exists(filename))
         {
             MessageBox.Show("Couldn't file the file: " + filename);
             return;
         }
         Shapefile sf = new Shapefile();
         sf.Open(filename, null);
         if (!sf.StartEditingShapes(true, null))
         {
             MessageBox.Show("Failed to start edit mode: " + sf.Table.ErrorMsg[sf.LastErrorCode]);
         }
         else
         {
             sf.UseQTree = true;
             sf.Labels.Generate("[Name]", tkLabelPositioning.lpCentroid, false);
             axMap1.AddLayer(sf, true);
             axMap1.SendMouseMove   = true;
             axMap1.ShowRedrawTime  = true;
             axMap1.MapUnits        = tkUnitsOfMeasure.umMeters;
             axMap1.CurrentScale    = 50000;
             axMap1.CursorMode      = tkCursorMode.cmNone;
             axMap1.MouseMoveEvent += AxMap1MouseMoveEvent;  // change MapEvents to axMap1
             _mDrawingHandle        = axMap1.NewDrawing(tkDrawReferenceList.dlScreenReferencedList);
             Labels labels = axMap1.get_DrawingLabels(_mDrawingHandle);
             labels.FrameVisible = true;
             labels.FrameType    = tkLabelFrameType.lfRectangle;
         }
     }
     //string filename = @"C:\Users\Admin\source\repos\GIS\GIS\bin\Debug\Shapefiles_Data\Hanoi\planet_105.141,20.676_106.164,21.273.osm.shp\shape\roads.shp";
 }
Beispiel #4
0
        public List <string> GetAllWardNames(string PathPrefix, string SubGroupIdentificationKey)
        {
            string connectionString = ConfigManager.Config.TableConnectionString;
            var    _StorageAccount  = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connectionString);
            var    blobClient       = _StorageAccount.CreateCloudBlobClient();

            container = blobClient.GetContainerReference("shapes");

            var ShapeBlockBlobReference = container.GetBlockBlobReference(this.GetPath(FileType.ShapeFile, PathPrefix, container.Uri.GetLeftPart(UriPartial.Path)));

            ShapeBlockBlobReference.DownloadToFile(PathPrefix + ".shp", FileMode.Create);

            var featureSet = Shapefile.Open(PathPrefix + ".shp");

            DataTable dt = featureSet.DataTable;

            List <string> subGroupNames = new List <string>();

            foreach (DataRow row in dt.Rows)
            {
                subGroupNames.Add(row[SubGroupIdentificationKey].ToString());
            }

            return(subGroupNames.Where(sgn => !string.IsNullOrEmpty(sgn)).ToList());
        }
Beispiel #5
0
        /// <summary>
        /// Open the filename as a shapefile
        /// </summary>
        /// <param name="shapefilename">
        /// The gridFilename.
        /// </param>
        /// <param name="theForm">
        /// The form.
        /// </param>
        /// <returns>
        /// The shapefile object
        /// </returns>
        internal static Shapefile OpenShapefile(string shapefilename, Form1 theForm)
        {
            if (!File.Exists(shapefilename))
            {
                theForm.Error(string.Empty, "Cannot find the file: " + shapefilename);
                return(null);
            }

            var sf = new Shapefile {
                GlobalCallback = theForm
            };

            theForm.Progress(string.Empty, 0, "Start opening " + Path.GetFileName(shapefilename));
            if (!sf.Open(shapefilename, theForm))
            {
                var msg = string.Format("Error opening shapefile: {0}", sf.ErrorMsg[sf.LastErrorCode]);
                Debug.WriteLine(msg);
                theForm.Error(string.Empty, msg);
                return(null);
            }

            // Log some characteristics:
            theForm.Progress(string.Empty, 100, "Number of shapes: " + sf.NumShapes);
            theForm.Progress(string.Empty, 100, "Number of fields: " + sf.NumFields);
            theForm.Progress(string.Empty, 100, "Type: " + sf.ShapefileType);
            theForm.Progress(string.Empty, 100, "Projection: " + sf.GeoProjection.ExportToProj4());
            theForm.Progress(string.Empty, 100, "Has spatial index: " + sf.HasSpatialIndex);

            return(sf);
        }
Beispiel #6
0
        public void ZonalStatistics()
        {
            const string rasterFile = @"GeoTiff\MWGIS-65.tif";

            if (!File.Exists(rasterFile))
            {
                throw new FileNotFoundException("Can't open " + rasterFile);
            }

            const string shapefileFile = @"sf\MWGIS-65.shp";

            if (!File.Exists(shapefileFile))
            {
                throw new FileNotFoundException("Can't open " + shapefileFile);
            }

            var grd = new Grid {
                GlobalCallback = this
            };

            if (!grd.Open(rasterFile, GridDataType.FloatDataType))
            {
                Assert.Fail("Can't open grid file: " + grd.ErrorMsg[grd.LastErrorCode]);
            }
            var sf = new Shapefile {
                GlobalCallback = this
            };

            if (!sf.Open(shapefileFile))
            {
                Assert.Fail("Can't open shapefile file: " + sf.ErrorMsg[sf.LastErrorCode]);
            }

            var utils = new Utils {
                GlobalCallback = this
            };

            Console.WriteLine("Before utils.GridStatisticsToShapefile");
            if (!utils.GridStatisticsToShapefile(grd, sf, false, true))
            {
                Assert.Fail("GridStatisticsToShapefile failed: " + utils.ErrorMsg[utils.LastErrorCode]);
            }

            var newShapefileFile = Path.Combine(Path.GetTempPath(), "ZonalStatistics.shp");

            if (File.Exists(newShapefileFile))
            {
                // ReSharper disable once AssignNullToNotNullAttribute
                foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(newShapefileFile), "ZonalStatistics.*"))
                {
                    File.Delete(f);
                }
            }

            Assert.IsTrue(sf.SaveAs(newShapefileFile), "Could not save resulting shapefile");

            Console.WriteLine("Saved as " + newShapefileFile);
        }
Beispiel #7
0
        /// <summary>
        /// creates a shapefile for grid labels given filename
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="labelProperties"></param>
        public void LoadLabelShapefile(string fileName, Dictionary <string, uint> labelProperties, Shapefile sfLabelPath)
        {
            _labelPropertiesDictionary = labelProperties;

            _shapeFileGrid25Labels = new Shapefile();
            _shapeFileGrid25Labels.Open(fileName, null);
            _shapeFileGrid25Labels.GenerateLabels(_shapeFileGrid25Labels.FieldIndexByName["Label"], tkLabelPositioning.lpCentroid);
            SetupLabelProperties();
        }
Beispiel #8
0
Datei: Main.cs Projekt: orapow/yt
        void addLayer(Tn tn)
        {
            var    ext = tn.file.Substring(tn.file.LastIndexOf("."));
            object lay = null;

            if (ext == ".shp")
            {
                var shp = new Shapefile();
                shp.Open(tn.file);
                lay        = shp;
                tn.tp      = 3;
                tn.extents = shp.Extents;

                tn.Fields = new List <ShpLayer.Field>();
                for (var f = 0; f < shp.NumFields; f++)
                {
                    var fe = shp.Field[f];
                    tn.Fields.Add(new ShpLayer.Field()
                    {
                        Name = fe.Name, Length = fe.Width, Type = fe.Type.ToString("G")
                    });
                }

                tn.Shapges = new List <ShpLayer.Shape>();
                for (var i = 0; i < shp.NumShapes; i++)
                {
                    showtip("正在加载文件:" + tn.file + " " + i + "/" + shp.NumShapes);
                    var sp  = shp.Shape[i];
                    var spe = new ShpLayer.Shape();
                    spe.Tp     = (byte)sp.ShapeType;
                    spe.Extent = new Extend(sp.Extents.xMin, sp.Extents.yMin, sp.Extents.xMax, sp.Extents.yMax);
                    var data = new Dictionary <string, string>();
                    for (var f = 0; f < shp.NumFields; f++)
                    {
                        data.Add(shp.Field[f].Name, shp.Table.CellValue[f, i] + "");
                    }
                    spe.Data = data;
                    for (var j = 0; j < sp.NumParts; j++)
                    {
                        spe.Points.Add(j, getPoints(sp.PartAsShape[j]));
                    }
                    tn.Shapges.Add(spe);
                }
            }
            else
            {
                var img = new MapWinGIS.Image();
                img.Open(tn.file);
                var r = false;
                img.SetNoDataValue(0, ref r);
                lay        = img;
                tn.tp      = 2;
                tn.extents = img.Extents;
            }
            tn.inptr = map1.AddLayer(lay, true);
            showtip("文件:" + tn.file + " 加载完成");
        }
        public void SetMaxDimensionGridName(string folderPath, string gridName)
        {
            var    sf   = new Shapefile();
            string file = $@"{folderPath}\{gridName}_gridlabels.shp";

            if (File.Exists(file) && sf.Open(file))
            {
                int reprojectedCount = 0;
                MaxDimensionMBR = sf.Reproject(_mapcontrol.GeoProjection, ref reprojectedCount);
            }
        }
Beispiel #10
0
        public void MergeFeature(FeatureSet m_MergeFeaSet)
        {
            if (m_MergeFeaSet.Features.Count < 2 || m_CurrentFeaLyr == null)
            {
                return;
            }

            //确保目标图层只选中编辑的那一个要素,因为后面会把选中要素移除
            //m_CurrentFeaLyr.UnSelectAll();
            //m_CurrentFeaLyr.Selection.Clear();

            //merge
            IFeature MergeFea = m_MergeFeaSet.GetFeature(0);

            for (int i = 0; i < m_MergeFeaSet.Features.Count; i++)
            {
                var fea = m_MergeFeaSet.GetFeature(i);
                MergeFea = MergeFea.Union(fea.Geometry);
                if (MergeFea == null)
                {
                    break;
                }
            }
            lFeaM = m_InputFeaSet.AddFeature(MergeFea.Geometry);
            m_CurrentFeaLyr.RemoveSelectedFeatures();

            MainWindow.m_DotMap.ResetBuffer();
            MainWindow.m_DotMap.Refresh();


            if (MessageBox.Show("Save edit?", "", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                m_CurrentFeaLyr.FeatureSet.Save();
                MessageBox.Show("Save successfully!");
            }
            //移除图层重新加载,因为底层bug 移动节点之后选择要素会报错。
            MainWindow.m_AddFeaType          = Enum.FeaType.None;
            MainWindow.m_DotMap.FunctionMode = FunctionMode.None;
            MainWindow.m_DotMap.Cursor       = System.Windows.Forms.Cursors.Default;
            string      shpPath = m_CurrentFeaLyr.FeatureSet.FilePath;
            string      name    = m_CurrentFeaLyr.LegendText;
            var         symbol  = m_CurrentFeaLyr.Symbolizer;
            var         extent  = m_CurrentFeaLyr.Extent;
            IFeatureSet s       = Shapefile.Open(shpPath);

            MainWindow.m_DotMap.Layers.Remove(m_CurrentFeaLyr as IMapLayer);
            var result = MainWindow.m_DotMap.Layers.Add(s);

            result.Symbolizer = symbol;
            result.Projection = MainWindow.m_DotMap.Projection;
            result.LegendText = name;
            //result.Select((result as FeatureLayer).FeatureSet.Features[(result as FeatureLayer).FeatureSet.Features.Count - 1]);
            this.Close();
        }
Beispiel #11
0
        public bool AddLayers(string name)
        {
            //this.mapControl.RemoveAllLayers();

            //this.mapControl.LockWindow(tkLockMode.lmLock);
            if (name.ToLower().EndsWith(".shp"))
            {
                Shapefile shp = new Shapefile();
                shp.Open(name, null);
                int layerID = mapControl.AddLayer(shp, true);
                //indexLayers.Insert(0, layerID);
            }
            else if (openDialog.SafeFileName.ToLower().EndsWith(".tif") ||
                     openDialog.SafeFileName.ToLower().EndsWith(".png") ||
                     openDialog.SafeFileName.ToLower().EndsWith(".jpg"))
            {
                MapWinGIS.Image img = new MapWinGIS.Image();
                img.Open(name, ImageType.TIFF_FILE, false, null);
                img.UseRgbBandMapping = true;
                for (int i = 0; i < img.NoBands; i++)
                {
                    bandIndex.Add(i);
                }
                //MessageBox.Show(img.UseRgbBandMapping.ToString());
                int layer = mapControl.AddLayer(img, true);

                //indexLayers.Insert(0, layer);
            }


            // List on Tree Layers
            var splited = openDialog.FileName.Split('\\');

            treeLayers.CheckBoxes  = true;
            treeLayers.AfterCheck += treeLayer_AfterCheck;
            TreeNode layerNode = new TreeNode(splited[splited.Length - 1].Split('.')[0]);

            layerNode.Checked = true;
            treeLayers.Nodes[0].Nodes.Add(layerNode);
            layerNode.Parent.Checked = true;

            // Draw Marker
            shp_tmp = new Shapefile();
            if (!shp_tmp.CreateNewWithShapeID("", ShpfileType.SHP_POINT))
            {
                MessageBox.Show("Failed to create shapefile: " + shp_tmp.ErrorMsg[shp_tmp.LastErrorCode]);
                return(false);
            }
            int layer_tmp = mapControl.AddLayer(shp_tmp, true);

            mapControl.CursorMode      = tkCursorMode.cmNone;
            mapControl.MouseDownEvent += mapControl_MouseDownEvent;
            return(this.mapControl.NumLayers > 0);
        }
        // <summary>
        // Split a shapefile into several ones according the values the specified attribute.
        // </summary>
        public void SplitByAttribute(AxMap axMap1, string dataPath)
        {
            axMap1.Projection             = tkMapProjection.PROJECTION_NONE;
            axMap1.GrabProjectionFromData = true;

            string filename = dataPath + "natural.shp";

            if (!File.Exists(filename))
            {
                MessageBox.Show("Couldn't file the file: " + filename);
            }
            else
            {
                Shapefile sf = new Shapefile();
                sf.Open(filename, null);

                int fieldIndex = sf.Table.FieldIndexByName["type"];
                sf.Categories.Generate(fieldIndex, tkClassificationType.ctUniqueValues, 0);
                sf.Categories.ApplyExpressions();

                ColorScheme scheme = new ColorScheme();
                scheme.SetColors2(tkMapColor.White, tkMapColor.Black);

                for (int i = 0; i < sf.Categories.Count; i++)
                {
                    Shapefile sfNew       = sf.Clone();
                    int       layerHandle = axMap1.AddLayer(sfNew, true);

                    for (int shapeIndex = 0; shapeIndex < sf.NumShapes; shapeIndex++)
                    {
                        if (sf.ShapeCategory[shapeIndex] == i)
                        {
                            Shape shape = sf.Shape[shapeIndex].Clone();
                            int   index = sfNew.NumShapes;
                            sfNew.EditInsertShape(shape, ref index);
                        }
                    }

                    ShapefileCategory category = sf.Categories.Item[i];
                    string            name     = category.Name.Substring(category.Name.IndexOf("=") + 1);

                    uint color = scheme.get_RandomColor((i + 1) / sf.Categories.Count);
                    sfNew.DefaultDrawingOptions.FillColor = color;

                    axMap1.set_LayerName(layerHandle, name);

                    //sfNew.SaveAs(path + name + ".shp", null);    // saves shapefile
                }
                ShowLegend();
                axMap1.ZoomToMaxExtents();
                axMap1.Redraw();
            }
        }
        // <summary>
        // To apply the same options on the next loading
        // </summary>
        private void RestoreCategories(AxMap axMap1, string dataPath)
        {
            string    filename = dataPath + "landuse.shp";
            Shapefile sf       = new Shapefile();

            if (sf.Open(filename, null))
            {
                int    handle      = axMap1.AddLayer(sf, true);
                string description = "";
                axMap1.LoadLayerOptions(handle, "categories_sample", ref description);
            }
        }
        private static void ImportShapefile(IOgrDatasource ds, string filename, string name)
        {
            // Check file:
            if (!File.Exists(filename))
            {
                Assert.Fail(filename + " does not exists.");
            }
            // Open shapefile:
            var sf = new Shapefile();

            if (!sf.Open(filename))
            {
                Assert.Fail("Failed to open shapefile: " + sf.ErrorMsg[sf.LastErrorCode]);
            }
            // Import:
            if (!ds.ImportShapefile(sf, name, "OVERWRITE=YES", tkShapeValidationMode.NoValidation))
            {
                Assert.Fail("Failed to import shapefile");
            }
            Debug.Print($"ds.Error: {ds.ErrorMsg[ds.LastErrorCode]} Gdal error: {ds.GdalLastErrorMsg}");

            // Check:
            Debug.Print("Layer was imported: " + name);
            var layer = ds.GetLayerByName(name);

            Assert.IsNotNull(layer, "layer is null");
            Debug.Print("Imported features count: " + layer.FeatureCount);
            Assert.AreEqual(sf.NumShapes, layer.FeatureCount,
                            $"The amount of imported shapes is incorrect. GDAL Error: {layer.GdalLastErrorMsg} Error: {layer.ErrorMsg[layer.LastErrorCode]}");

            // Export again, using GetBuffer:
            var sfFromBuffer = layer.GetBuffer();

            Debug.Print("Number shapes from GetBuffer: " + sfFromBuffer.NumShapes);
            Assert.AreEqual(sf.NumShapes, sfFromBuffer.NumShapes, "The amount of exported shapes is incorrect.");

            // Save shapefile:
            var tmpFilename = Path.ChangeExtension(Path.Combine(Path.GetTempPath(), Path.GetTempFileName()), ".shp");

            DeleteShapefile(tmpFilename);
            if (!sfFromBuffer.SaveAs(tmpFilename))
            {
                Assert.Fail("Failed to save shapefile: " + sfFromBuffer.ErrorMsg[sfFromBuffer.LastErrorCode]);
            }

            if (!ds.ImportShapefile(sfFromBuffer, "sfFromBuffer", "OVERWRITE=YES",
                                    tkShapeValidationMode.NoValidation))
            {
                Assert.Fail("Failed to import buffered shapefile");
            }

            layer.Close();
        }
        private void btnSelectFilePath_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog f = new OpenFileDialog();

            f.CheckFileExists = true;
            f.Title           = "Select ShapeFile";
            f.Filter          = "ShapeFile(*.shp)|*.shp";
            if (f.ShowDialog() == true)
            {
                this.txtFilePath.Text = f.FileName;
                m_RemoteFeaSet        = Shapefile.Open(f.FileName);
            }
        }
Beispiel #16
0
        /// <summary>
        /// 读入点shp
        /// </summary>
        /// <param name="file_path"></param>
        /// <returns></returns>
        public static List <MyPoint> inputMyPoint(string file_path)
        {
            List <MyPoint> point_list = new List <MyPoint>();
            Shapefile      shapefile  = Shapefile.Open(file_path) as Shapefile;

            shapefile.ReadProjection();
            foreach (Feature feature in shapefile.Features)
            {
                MyPoint mypoint = new MyPoint(feature.Coordinates[0].X, feature.Coordinates[0].Y);
                point_list.Add(mypoint);
            }
            return(point_list);
        }
Beispiel #17
0
        /// <summary>
        /// Creates a new instance of FeatureSet by opening disk-based shapefile.
        /// </summary>
        /// <param name="filename">Filename of shapefile to open (.shp extension).</param>
        public FeatureSet(string filename)
        {
            if (!File.Exists(filename))
            {
                throw new FileNotFoundException("File not found: " + filename);
            }

            _shapefile = new Shapefile();
            if (!_shapefile.Open(filename))
            {
                throw new ApplicationException("Failed to open shapefile: " + _shapefile.ErrorMessage());
            }
        }
Beispiel #18
0
        // <summary>
        // Adds all the shapefiles and images with .tif and .png extentions from the specified folder to the map
        // </summary>
        public bool AddLayers(AxMap axMap1, string dataPath)
        {
            axMap1.RemoveAllLayers();
            axMap1.LockWindow(tkLockMode.lmLock);

            try
            {
                string[] files = Directory.GetFiles(dataPath);
                foreach (string file in files)
                {
                    int layerHandle = -1;
                    if (file.ToLower().EndsWith(".shp"))
                    {
                        Shapefile sf = new Shapefile();
                        if (sf.Open(file, null))
                        {
                            layerHandle = axMap1.AddLayer(sf, true);
                        }
                        else
                        {
                            MessageBox.Show(sf.ErrorMsg[sf.LastErrorCode]);
                        }
                    }
                    else if (file.ToLower().EndsWith(".tif") ||
                             file.ToLower().EndsWith(".png"))
                    {
                        Image img = new Image();
                        if (img.Open(file, ImageType.TIFF_FILE, false, null))
                        {
                            layerHandle = axMap1.AddLayer(img, true);
                        }
                        else
                        {
                            MessageBox.Show(img.ErrorMsg[img.LastErrorCode]);
                        }
                    }

                    if (layerHandle != -1)
                    {
                        axMap1.set_LayerName(layerHandle, Path.GetFileName(file));
                    }
                }
            }
            finally
            {
                axMap1.LockWindow(tkLockMode.lmUnlock);
                Debug.Print("Layers added to the map: " + axMap1.NumLayers);
            }
            return(axMap1.NumLayers > 0);
        }
        private Shapefile ReadShapefile(string shapefile)
        {
            var catfoodShapefile = new Shapefile();

            try
            {
                catfoodShapefile.Open(shapefile);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Error : " + ex.Message);
                ErrorMessage = ex;
            }
            return(catfoodShapefile);
        }
Beispiel #20
0
        private void MenuForm_Load(object sender, EventArgs e)
        {
            GeoProjection proj = new GeoProjection();

            proj.ImportFromEPSG(3857);

            _shape = new Shapefile();
            _shape.Open(@"E:\POSTE DE TRAVAIL\PROJETS PARTAGES\PROJET DE STAGE\USA_P\usa.shp");

            _shape   = _shape.Reproject(proj, 1);
            _idshape = axMap1.AddLayer(_shape, true);


            PointIco(@"E:\POSTE DE TRAVAIL\PROJETS PARTAGES\PROJET DE STAGE\ICON");
        }
Beispiel #21
0
        void ViewLine_AddLineEvent()
        {
            OpenFileDialog openLineDlg = new OpenFileDialog();

            openLineDlg.Filter = "矢量格式" + "|" + "*.shp";// + "|" + img.CdlgFilter;
            if (openLineDlg.ShowDialog() == DialogResult.OK)
            {
                String extention = Path.GetExtension(openLineDlg.FileName).ToLower();
                if (extention == ".shp")
                {
                    Shapefile lineShapefile = new Shapefile();
                    lineShapefile.Open(openLineDlg.FileName);
                    if (lineShapefile.ShapefileType != ShpfileType.SHP_POLYLINE)
                    {
                        return;
                    }

                    line = new Line(ref Map, lineShapefile, lineShapefileLayerHandle);
                    lineShapefileLayerHandle = line.LayerHandle;

                    var sf = new Shapefile();
                    if (PointShapefileLayerHandle != -1)
                    {
                        sf = Map.get_Shapefile(PointShapefileLayerHandle);
                        sf.EditClear();
                    }
                    foreach (MapWinGIS.Point pointFromLine in line.Points)
                    {
                        AddPoint(Map, pointFromLine.x, pointFromLine.y, pointFromLine.Key);
                    }

                    points = line.Points;

                    if (!(ViewLine == null || ViewLine.IsDisposed))
                    {
                        ViewLine.Close();
                    }
                    if (!(ViewPoint == null || ViewPoint.IsDisposed))
                    {
                        ViewPoint.Close();
                    }
                }
                else
                {
                    MessageBox.Show("罢工啦,亲~我只能识别.shp格式的线文件哦");
                }
            }
        }
Beispiel #22
0
        private void AddVectorLayerShpToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            string FilePath, Filename;

            FilePath = @"F:\AY\SCREEN_CAPTURE\ARCPY\Catchment\cat_poly\cat_poly.shp";

            OpenFileDialog openfiledialog1 = new OpenFileDialog();

            openfiledialog1.Filter      = "Shapefile(*.shp)|*.shp|All Files(*.*)|*.*";
            openfiledialog1.FilterIndex = 1;

            if (openfiledialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                FilePath = openfiledialog1.FileName;
            }
            //else if (openfiledialog1.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            //{
            //return;
            //}

            //FilePath = @"F:\AY\SCREEN_CAPTURE\ARCPY\Catchment\cat_poly\cat_poly.shp";

            int layerHandle = -1;

            if (FilePath.ToLower().EndsWith(".shp"))
            {
                Shapefile sf = new Shapefile();
                if (sf.Open(FilePath, null))
                {
                    layerHandle = axMap1.AddLayer(sf, true);
                    //AllLoadedFileName[layerHandle] = FilePath.ToString();

                    //HandleValue[LayerNumbers] = axMap1.AddLayer(sf, true);
                    //AllLoadedFileName[LayerNumbers] = FilePath.ToString();

                    //Level 2
                    //treeView1.Nodes[0].Nodes.Add(FilePath.ToString(), FilePath.ToString());         //0 0
                    Filename = Path.GetFileName(FilePath);
                    treeView1.Nodes[0].Nodes.Add(Filename);         //0 0
                    //LayerNumbers++;
                }
                else
                {
                    MessageBox.Show(sf.ErrorMsg[sf.LastErrorCode]);
                }
            }
            //TxtLayerNumber.Text = LayerNumbers.ToString();
        }
Beispiel #23
0
        private void ClipGridWithPolygon()
        {
            var workingFolder = @"C:\dev\TestingScripts\ScriptData\ClipGridWithPolygon";
            var tempFolder    = @"C:\dev\TestingScripts\Temp\ClipGridWithPolygon";

            var gridFilename = Path.Combine(workingFolder, "AHN2.asc");
            var sf           = new Shapefile();

            sf.Open(Path.Combine(workingFolder, "Areas.shp"), null);
            var numShapes    = sf.NumShapes;
            var clippedWrong = 0;
            var clippedGood  = 0;

            // Needed for the new method:
            var utils = new Utils();
            var grd   = new Grid();

            grd.Open(gridFilename, GridDataType.UnknownDataType, true, GridFileType.UseExtension, null);

            for (var i = 0; i < numShapes; i++)
            {
                var polygon    = sf.get_Shape(i);
                var resultGrid = Path.Combine(tempFolder, "AHN2_clipped" + i + ".asc");

                // Using thr mwGeoProc version takes almost 4 hours with this data:
                // if (MapWinGeoProc.SpatialOperations.ClipGridWithPolygon(ref gridFilename, ref polygon, ref resultGrid))
                if (utils.ClipGridWithPolygon2(grd, polygon, resultGrid, false))
                {
                    clippedGood++;
                }
                else
                {
                    clippedWrong++;

                    /*
                     * testsMethods.ReportMessage(
                     * string.Format(
                     *  "Clipping grid with polygon number {0} failed. Error: {1}", i, MapWinGeoProc.Error.GetLastErrorMsg()));
                     */
                }
            }

            var msg = string.Empty;

            msg = clippedWrong == 0 ? "All tests successful!" : string.Format("{0} clippings went OK, {1} went wrong", clippedGood, clippedWrong);
            MessageBox.Show(msg);
        }
        // <summary>
        // A simple GUI for editing attributes of the individual shapes.
        // </summary>
        public void EditAttributes(AxMap axMap1, string dataPath)
        {
            axMap1.Projection = tkMapProjection.PROJECTION_GOOGLE_MERCATOR;

            string filename = dataPath + "buildings.shp";

            if (!File.Exists(filename))
            {
                MessageBox.Show("Couldn't file the file: " + filename);
                return;
            }

            var sf = new Shapefile();

            sf.Open(filename, null);
            int layerHandle = axMap1.AddLayer(sf, true);

            sf = axMap1.get_Shapefile(layerHandle);     // in case a copy of shapefile was created by GlobalSettings.ReprojectLayersOnAdding

            if (!sf.Table.StartEditingTable(null))
            {
                MessageBox.Show("Failed to start edit mode: " + sf.Table.ErrorMsg[sf.LastErrorCode]);
            }
            else
            {
                string expression = "";
                for (int i = 1; i < sf.NumFields; i++)      // all the fields will be displayed apart the first one
                {
                    expression += "[" + sf.Field[i].Name + "]";
                    if (i != sf.NumFields - 1)
                    {
                        const string endLine = "\"\n\"";
                        expression += string.Format("+ {0} +", endLine);
                    }
                }
                sf.Labels.Generate(expression, tkLabelPositioning.lpCentroid, false);
                sf.Labels.TextRenderingHint = tkTextRenderingHint.SystemDefault;

                axMap1.SendMouseDown = true;

                axMap1.CursorMode         = tkCursorMode.cmNone;
                MapEvents.MouseDownEvent += AxMap1MouseDownEvent2;  // change MapEvents to axMap1

                this.ZoomToValue(sf, "Name", "Lakeview");
            }
        }
Beispiel #25
0
        public static void StartMeasureingTool(tkMeasuringType toolType, string filename)
        {
            var sf = new Shapefile();

            if (!sf.Open(filename))
            {
                MessageBox.Show("Failed to open shapefile");
            }
            else
            {
                var ut = new Utils();
                axMap1.RemoveAllLayers();
                int handle = axMap1.AddLayer(sf, true);
                axMap1.ZoomToLayer(handle);
                axMap1.Measuring.MeasuringType = toolType;
                axMap1.CursorMode = tkCursorMode.cmMeasure;
            }
        }
Beispiel #26
0
        /// <summary>
        /// 读入线shp
        /// </summary>
        /// <param name="file_path"></param>
        public static List <MyLine> inputMyLine(string file_path)
        {
            List <MyLine> line_list = new List <MyLine>();
            Shapefile     shapefile = Shapefile.Open(file_path) as Shapefile;

            shapefile.ReadProjection();
            foreach (Feature feature in shapefile.Features)
            {
                MyLine myline = new MyLine();
                for (int j = 0; j < feature.Coordinates.Count; j++)
                {
                    MyPoint mypoint = new MyPoint(feature.Coordinates[j].X, feature.Coordinates[j].Y);
                    myline.points_mid.Add(mypoint);
                }
                line_list.Add(myline);
            }
            return(line_list);
        }
Beispiel #27
0
        public void FixUpShapes()
        {
            var utils = new Utils {
                GlobalCallback = this
            };
            // Open shapefile:
            var sfInvalid = new Shapefile();
            var sfFixed   = new Shapefile();

            try
            {
                var result = sfInvalid.Open(@"sf\invalid.shp");
                Assert.IsTrue(result, "Could not open shapefile");

                result = sfInvalid.HasInvalidShapes();
                Assert.IsTrue(result, "Shapefile has no invalid shapes");
                Helper.PrintExtents(sfInvalid.Extents);

                for (var i = 0; i < sfInvalid.NumShapes; i++)
                {
                    var shp = sfInvalid.Shape[i];
                    Assert.IsFalse(shp.IsValid, "Shape should be invalid");
                    var reason = shp.IsValidReason;
                    Console.WriteLine(reason);
                    Assert.IsFalse(string.IsNullOrEmpty(reason), "Cannot get validation reason");
                }

                var newFilename = Path.Combine(Path.GetTempPath(), "FixUpShapes.shp");
                result = utils.FixUpShapes(sfInvalid, false, newFilename, true);
                Assert.IsTrue(result, "Could not fix shapefile");
                Assert.IsTrue(File.Exists(newFilename), newFilename + " doesn't exists");

                result = sfFixed.Open(newFilename);
                Assert.IsTrue(result, "Could not open fixed shapefile");

                Assert.AreEqual(sfInvalid.NumShapes, sfFixed.NumShapes, "Number of shapes are not equal");
                Helper.PrintExtents(sfFixed.Extents);
            }
            finally
            {
                sfInvalid.Close();
                sfFixed.Close();
            }
        }
Beispiel #28
0
        // <summary>
        // Loads the layers, registers event handlers
        // </summary>
        public void Tracking(AxMap axMap1, string dataPath)
        {
            axMap1.Projection             = tkMapProjection.PROJECTION_NONE;
            axMap1.GrabProjectionFromData = true;

            axMap1.DisableWaitCursor = true;

            string filename1 = dataPath + "buildings.shp";
            string filename2 = dataPath + "roads.shp";
            string filename3 = dataPath + "path.shp";

            if (!File.Exists(filename1) || !File.Exists(filename2) || !File.Exists(filename3))
            {
                MessageBox.Show("Couldn't find the files (buildings.shp, roads.shp, path.shp): " + dataPath);
            }
            else
            {
                Shapefile sf = new Shapefile();
                sf.Open(filename1, null);
                axMap1.AddLayer(sf, true);

                sf = new Shapefile();
                sf.Open(filename2, null);
                sf.Labels.Generate("[Name]", tkLabelPositioning.lpLongestSegement, false);

                Utils       utils   = new Utils();
                LinePattern pattern = new LinePattern();
                pattern.AddLine(utils.ColorByName(tkMapColor.Brown), 10.0f, tkDashStyle.dsSolid);
                pattern.AddLine(utils.ColorByName(tkMapColor.Yellow), 9.0f, tkDashStyle.dsSolid);
                sf.DefaultDrawingOptions.LinePattern    = pattern;
                sf.DefaultDrawingOptions.UseLinePattern = true;
                axMap1.AddLayer(sf, true);

                sf = new Shapefile();
                sf.Open(filename3, null);
                m_path              = sf.Shape[0];
                axMap1.MapUnits     = tkUnitsOfMeasure.umMeters;
                axMap1.CurrentScale = 5000.0;

                m_timer.Interval = 250;
                m_timer.Tick    += TimerTick;
                m_timer.Start();
            }
        }
Beispiel #29
0
        private static bool ImportShapefilesFromFolder()
        {
            var ds = new OgrDatasource();

            if (!ds.Open(CONNECTION_STRING))
            {
                Debug.Print("Failed to establish connection: " + ds.GdalLastErrorMsg);
            }
            else
            {
                string path  = @"d:\data\sf\london";
                var    files = Directory.GetFiles(path, "*.shp");
                foreach (var file in files)
                {
                    var sf = new Shapefile();
                    if (!sf.Open(file))
                    {
                        Debug.Print("Failed to open shapefile: {0}\n{1}", file, sf.ErrorMsg[sf.LastErrorCode]);
                    }
                    else
                    {
                        string name = Path.GetFileNameWithoutExtension(file);
                        if (!ds.ImportShapefile(sf, name, "OVERWRITE=YES", tkShapeValidationMode.NoValidation))
                        {
                            Debug.Print("Failed to import shapefile: " + name);
                        }
                        else
                        {
                            Debug.Print("Layer was imported: " + name);
                            var layer = ds.GetLayerByName(name);
                            if (layer != null)
                            {
                                Debug.Print("Imported features count: " + layer.FeatureCount);
                                layer.Close();
                            }
                        }
                    }
                }
                ds.Close();
            }
            return(true);
        }
Beispiel #30
0
        private void ClipGridWithPolygon()
        {
            var workingFolder = @"C:\dev\TestingScripts\ScriptData\ClipGridWithPolygon";
            var tempFolder    = @"C:\dev\TestingScripts\Temp\ClipGridWithPolygon";

            var gridFilename = Path.Combine(workingFolder, "AHN2.asc");
            var sf           = new Shapefile();

            sf.Open(Path.Combine(workingFolder, "Areas.shp"));
            var numShapes    = sf.NumShapes;
            var clippedWrong = 0;
            var clippedGood  = 0;

            // Needed for the new method:
            var utils = new Utils();
            var grd   = new Grid();

            grd.Open(gridFilename);

            for (var i = 0; i < numShapes; i++)
            {
                var polygon    = sf.Shape[i];
                var resultGrid = Path.Combine(tempFolder, "AHN2_clipped" + i + ".asc");

                // Using thr mwGeoProc version takes almost 4 hours with this data:
                // if (MapWinGeoProc.SpatialOperations.ClipGridWithPolygon(ref gridFilename, ref polygon, ref resultGrid))
                if (utils.ClipGridWithPolygon2(grd, polygon, resultGrid, false))
                {
                    clippedGood++;
                }
                else
                {
                    clippedWrong++;
                }
            }

            var msg = clippedWrong == 0
                ? "All tests successful!"
                : $"{clippedGood} clippings went OK, {clippedWrong} went wrong";

            MessageBox.Show(msg);
        }
        // <summary>
        // Shows attributes of shape in mouse move event.
        // </summary>
        public void ShowAttributes(AxMap axMap1, string dataPath, ToolStripStatusLabel label)
        {
            axMap1.Projection = tkMapProjection.PROJECTION_GOOGLE_MERCATOR;
            axMap1.ProjectionMismatchBehavior = tkMismatchBehavior.mbCheckLooseAndReproject;

            string filename = dataPath + "landuse.shp";
            Shapefile sf = new Shapefile(); 
            if (sf.Open(filename))
            {
                m_layerHandle = axMap1.AddLayer(sf, true);
                sf = axMap1.get_Shapefile(m_layerHandle);     // in case a copy of shapefile was created by AxMap.ProjectionMismatchBehavior
                
                sf.HotTracking = true;
                axMap1.SendMouseMove = true;
                axMap1.CursorMode = tkCursorMode.cmNone;
                axMap1.ShapeHighlighted += AxMap1ShapeHighlighted;
                m_label = label;
            }
            else
            {
                MessageBox.Show("Failed to open shapefile");
            }
        }