예제 #1
0
파일: Main.cs 프로젝트: 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 + " 加载完成");
        }
예제 #2
0
        //Creates a shape file that contains all flights lat and long points and then generates a feald in the table that contains all flights images
        private void CreatePointShapefile()
        {
            axMap1.Projection   = tkMapProjection.PROJECTION_WGS84;
            axMap1.TileProvider = tkTileProvider.OpenStreetMap;
            var positions = pR.GetPositionsFromDB();
            var sfPoints  = new Shapefile();

            sfPoints.CreateNewWithShapeID("", ShpfileType.SHP_POINT);
            // creating points and inserting them in the shape
            foreach (Position position in positions)
            {
                int count = 0;
                var pnt   = new Point();
                pnt.x = Convert.ToDouble(position.longitude);
                pnt.y = Convert.ToDouble(position.latitude);
                Shape shp = new Shape();
                shp.Create(ShpfileType.SHP_POINT);
                int index = 0;
                shp.InsertPoint(pnt, ref index);
                sfPoints.EditInsertShape(shp, ref count);
                count++;
            }
            var _idShape = axMap1.AddLayer(sfPoints, true);
            int indexo   = sfPoints.Table.FieldIndexByName["MWShapeId"];
            var names    = new HashSet <string>();

            for (int i = 0; i < sfPoints.Table.NumRows; i++)
            {
                names.Add(sfPoints.Table.CellValue[indexo, i].ToString());
            }
            string[] files = Directory.GetFiles(@"D:\Faks\Druga godina\Treci Semestar\Programiranje_u_NET_okolini\Konstrukcijska_Vjezba\FlightTracker\FlightTracker\Resources\imagesOfPlanes");
            foreach (string file in files)
            {
                string name = Path.GetFileNameWithoutExtension(file);
                if (Path.GetExtension(file).ToLower() == ".png" && names.Contains(name))
                {
                    MapWinGIS.Image img = new MapWinGIS.Image();
                    if (img.Open(file, ImageType.USE_FILE_EXTENSION, true, null))
                    {
                        ShapefileCategory ct = new ShapefileCategory();
                        ct = sfPoints.Categories.Add(name);
                        ct.DrawingOptions.PointType     = tkPointSymbolType.ptSymbolPicture;
                        ct.DrawingOptions.PictureScaleX = 0.8;
                        ct.DrawingOptions.PictureScaleY = 0.8;
                        ct.DrawingOptions.DrawingMode   = tkVectorDrawingMode.vdmGDIPlus;
                        sfPoints.CollisionMode          = tkCollisionMode.AllowCollisions;
                        ct.Expression             = "[MWShapeId]=" + name;
                        ct.DrawingOptions.Picture = img;

                        sfPoints.DefaultDrawingOptions = ct.DrawingOptions;
                    }
                }
            }
            sfPoints.Categories.ApplyExpressions();
            axMap1.KnownExtents = tkKnownExtents.keCroatia;
        }
예제 #3
0
        /// <summary>
        /// Changes the textures
        /// </summary>
        void iconControl1_SelectionChanged()
        {
            string filename = iconControl1.SelectedName;

            if (filename == string.Empty)
            {
                return;
            }

            // seeking the transarent color
            Bitmap bmp            = new Bitmap(filename);
            Color  clrTransparent = Color.White;

            for (int i = 0; i < bmp.Width; i++)
            {
                int j;
                for (j = 0; j < bmp.Height; j++)
                {
                    Color clr = bmp.GetPixel(i, j);
                    if (clr.A == 0)
                    {
                        clrTransparent = clr;
                        break;
                    }
                }
                if (j != bmp.Width)
                {
                    break;
                }
            }

            MapWinGIS.Image img = new MapWinGIS.Image();
            if (img.Open(filename, ImageType.USE_FILE_EXTENSION, true, null))
            {
                img.LoadBuffer(50);

                img.TransparencyColor    = Colors.ColorToUInteger(clrTransparent);
                img.TransparencyColor2   = Colors.ColorToUInteger(clrTransparent);
                img.UseTransparencyColor = true;

                _options.Picture = img;

                DrawPreview();
            }
            else
            {
                string errString = string.Empty;
                if (img.LastErrorCode != 0)
                {
                    errString = ": " + img.get_ErrorMsg(img.LastErrorCode);
                }
                Globals.MessageBoxError("Failed to open image: " + errString);
            }
        }
예제 #4
0
파일: Form1.cs 프로젝트: TheWind97/GIS
        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>
        /// Reprojects image
        /// </summary>
        public static TestingResult Reproject(MapWinGIS.Image image, out MapWinGIS.Image imageNew, MapWinGIS.GeoProjection projection, frmTesterReport report)
        {
            MapWinGIS.GeoProjection projImage = new MapWinGIS.GeoProjection();
            projImage.ImportFromProj4(image.GetProjection());

            string sourcePrj    = image.GetProjection();
            string targetPrj    = projection.ExportToProj4();
            string origFilename = image.Filename;

            MapWinGIS.ICallback callback = image.GlobalCallback;
            imageNew = null;

            LayerSource obj    = new LayerSource(image);
            LayerSource objNew = null;

            if (CoordinateTransformation.SeekSubstituteFile(obj, projection, out objNew))
            {
                imageNew = objNew.Image;
                return(TestingResult.Substituted);
            }

            string newFilename = CoordinateTransformation.FilenameWithProjectionSuffix(origFilename, projImage, projection);

            newFilename = CoordinateTransformation.GetSafeNewName(newFilename);

            // setting callback
            if (report != null)
            {
                if (!report.Visible)
                {
                    report.InitProgress(projection);
                }

                report.ShowFilename(image.Filename);
            }

            MapWinGIS.GeoProcess.SpatialReference.ProjectImage(sourcePrj, targetPrj, origFilename, newFilename, report);

            if (report != null)
            {
                report.ClearFilename();
            }

            imageNew = new MapWinGIS.Image();
            if (imageNew.Open(newFilename, MapWinGIS.ImageType.USE_FILE_EXTENSION, false, callback))
            {
                return(TestingResult.Ok);
            }
            else
            {
                imageNew = null;
                return(TestingResult.Error);
            }
        }
예제 #6
0
        public static IImageSource Open(string filename, bool inRam)
        {
            var img = new Image();

            if (!img.Open(filename, ImageType.USE_FILE_EXTENSION, inRam))
            {
                Logger.Current.Warn("Failed to open datasource: " + img.ErrorMsg[img.LastErrorCode]);
                return(null);
            }

            return(Wrap(img));
        }
예제 #7
0
        private void AddRasterLayerToolStripMenuItem1_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      = "Raster tif(*.tif)|*.tif|Raster png(*.png)|*.png|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(".tif") ||
                FilePath.ToLower().EndsWith(".png"))
            {
                MapWinGIS.Image img = new MapWinGIS.Image();
                if (img.Open(FilePath, ImageType.TIFF_FILE, false, null))
                {
                    layerHandle = axMap1.AddLayer(img, true);
                    //HandleValue[LayerNumbers] = axMap1.AddLayer(img, true);
                    //AllLoadedFileName[LayerNumbers] = FilePath.ToString();
                    AllLoadedFileName[layerHandle] = 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);
                    ///LayerNumbers++;
                }
                else
                {
                    MessageBox.Show(img.ErrorMsg[img.LastErrorCode]);
                }
            }
            //TxtLayerNumber.Text = LayerNumbers.ToString();
        }
예제 #8
0
        public static IRasterSource Open(string filename)
        {
            var img = new Image();

            if (!img.Open(filename))
            {
                throw new ApplicationException("Failed to open datasource: " + img.ErrorMsg[img.LastErrorCode]);
            }
            if (img.SourceType != tkImageSourceType.istGDALBased)
            {
                // TODO: force opening BMP files with GDAL as well for uniformity
                throw new ApplicationException("Image format isn't supported by RasterSource");
            }
            return(new RasterSource(img));
        }
예제 #9
0
        /// <summary>
        ///当选择了icon,更新预览
        /// </summary>
        private void IconControl1SelectionChanged()
        {
            string filename = iconControl1.SelectedName;

            if (string.IsNullOrWhiteSpace(filename))
            {
                return;
            }

            var   bmp            = new Bitmap(filename);
            Color clrTransparent = Color.White;

            MapWinGIS.Image img = new MapWinGIS.Image();
            if (img.Open(filename, ImageType.USE_FILE_EXTENSION, true, null))
            {
                img.LoadBuffer(50);

                img.TransparencyColor    = Colors.ColorToUInteger(clrTransparent);
                img.TransparencyColor2   = Colors.ColorToUInteger(clrTransparent);
                img.UseTransparencyColor = true;

                _options.PointType = tkPointSymbolType.ptSymbolPicture;
                _options.Picture   = img;

                UpdatePrictureScale();

                DrawPreview();
            }
            else
            {
                string errString = string.Empty;
                if (img.LastErrorCode != 0)
                {
                    errString = ": " + img.ErrorMsg[img.LastErrorCode];
                }
                MessageBox.Show("Failed to open image: " + errString);
            }

            if (!_noEvents)
            {
                btnApply.Enabled = true;
            }
        }
예제 #10
0
        private void UpdateGridToMap()
        {
            int layerHandler;

            /*
             * foreach (MapWinGIS.Image UpdateMapGridImage in gridImages)
             * {
             *  layerHandler = Map.AddLayer(GridImage, true);
             *  gridLayerHandlers.Add(layerHandler);
             *  Map.set_ImageLayerPercentTransparent(layerHandler, ((float)vSclbTransparent.Value) / 100);
             * }
             *
             * Map.ZoomToMaxExtents();
             */
            MapWinGIS.Image img = new MapWinGIS.Image();
            img.Open((string)Map.Tag);
            layerHandler = Map.AddLayer(img, true);
            gridLayerHandlers.Add(layerHandler);
            Map.set_ImageLayerPercentTransparent(layerHandler, ((float)vSclbTransparent.Value) / 100);
            Map.ZoomToMaxExtents();
        }
예제 #11
0
 private MapWinGIS.Image OpenMarker(string path)
 {
     if (!File.Exists(path))
     {
         MessageBox.Show("Can't find the file: " + path);
     }
     else
     {
         MapWinGIS.Image img = new MapWinGIS.Image();
         if (!img.Open(path, ImageType.USE_FILE_EXTENSION, true, null))
         {
             MessageBox.Show(img.ErrorMsg[img.LastErrorCode]);
             img.Close();
         }
         else
         {
             return(img);
         }
     }
     return(null);
 }
예제 #12
0
        private void PointIco(string icopath)
        {
            int index = _shape.Table.FieldIndexByName["cat"];
            var names = new HashSet <string>();

            for (int i = 0; i < _shape.Table.NumRows; i++)
            {
                names.Add(_shape.Table.CellValue[index, i].ToString());
            }

            string[] files = Directory.GetFiles(icopath);
            foreach (string file in files)
            {
                string name = Path.GetFileNameWithoutExtension(file);
                if (Path.GetExtension(file).ToLower() == ".png" && names.Contains(name))
                {
                    MapWinGIS.Image img = new MapWinGIS.Image();
                    if (img.Open(file, ImageType.USE_FILE_EXTENSION, true, null))
                    {
                        ShapefileCategory ct = new ShapefileCategory();
                        ct = _shape.Categories.Add(name);

                        ct.DrawingOptions.PointType = tkPointSymbolType.ptSymbolPicture;

                        ct.DrawingOptions.PictureScaleX = 0.8;
                        ct.DrawingOptions.PictureScaleY = 0.8;

                        ct.DrawingOptions.DrawingMode = tkVectorDrawingMode.vdmGDIPlus;

                        _shape.CollisionMode      = tkCollisionMode.AllowCollisions;
                        ct.Expression             = " [cat]=" + name;
                        ct.DrawingOptions.Picture = img;

                        _shape.DefaultDrawingOptions = ct.DrawingOptions;
                    }
                }

                _shape.Categories.ApplyExpressions();
            }
        }
예제 #13
0
        /// <summary>
        /// Load map layers from XML file generated by axmap.SaveMapState.
        ///
        /// Layers are added to the map and is followed by restoring the map extent.
        /// The first added layer automatically sets the map control's projection.
        /// </summary>
        /// <param name="restoreMapState">
        /// When restoreMapState:true, map state is restored
        /// We use restoreMapState:false to load the layers but not restore axMap extent.
        /// </param>
        public void LoadMapState(bool restoreMapState = true)
        {
            _fileMapState = $@"{global.ApplicationPath}\mapstate";
            if (File.Exists(_fileMapState))
            {
                var doc      = new XmlDocument();
                var proceed  = true;
                var fileName = "";
                try
                {
                    doc.Load(_fileMapState);
                }
                catch (XmlException ex)
                {
                    Logger.Log(ex.Message, "MapLayersHandler", "LoadMapState");
                    proceed = false;
                }
                if (proceed)
                {
                    foreach (XmlNode ly in doc.DocumentElement.SelectNodes("//Layer"))
                    {
                        fileName = ly.Attributes["Filename"].Value;
                        var isVisible = true;
                        isVisible = ly.Attributes["LayerVisible"]?.Value == "1";
                        if (ly.Attributes["LayerType"].Value == "Shapefile")
                        {
                            var sf = new Shapefile();
                            if (sf.Open(fileName))
                            {
                                var h = AddLayer(sf, ly.Attributes["LayerName"].Value, isVisible);
                                _sfSymbologyHandler.SymbolizeLayer(ly.InnerXml);
                                _currentMapLayer.Visible = ly.Attributes["LayerVisible"].Value == "1";
                                _sfLabelHandler          = new ShapefileLabelHandler(_currentMapLayer);

                                if (ly.FirstChild.Name == "ShapefileClass")
                                {
                                    foreach (XmlNode child in ly.FirstChild.ChildNodes)
                                    {
                                        if (child.Name == "LabelsClass" && child.Attributes["Generated"].Value == "1")
                                        {
                                            _currentMapLayer.IsLabeled = child.Attributes["Generated"].Value == "1";
                                            _sfLabelHandler.LabelShapefile(child.OuterXml);
                                        }
                                    }
                                }
                            }
                        }
                        else if (ly.Attributes["LayerType"].Value == "Image")
                        {
                            //code when layertype is image
                            var img = new MapWinGIS.Image();
                            if (img.Open(fileName))
                            {
                                var h = AddLayer(img, ly.Attributes["LayerName"].Value, isVisible);
                            }
                        }
                    }
                    if (restoreMapState)
                    {
                        //We restore saved extent of the map but not the projection. Since layers
                        //were already added to the map, the first layer sets the map's projection.
                        foreach (XmlNode ms in doc.DocumentElement.SelectNodes("//MapState "))
                        {
                            var ext = new Extents();
                            ext.SetBounds(
                                double.Parse(ms.Attributes["ExtentsLeft"].Value),
                                double.Parse(ms.Attributes["ExtentsBottom"].Value),
                                0,
                                double.Parse(ms.Attributes["ExtentsRight"].Value),
                                double.Parse(ms.Attributes["ExtentsTop"].Value),
                                0);
                            _axmap.Extents   = ext;
                            _axmap.ExtentPad = double.Parse(ms.Attributes["ExtentsPad"].Value);
                        }
                    }
                }
            }
            else
            {
                File.Create(_fileMapState);
            }
        }