Esempio n. 1
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);
        }
Esempio n. 2
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";
 }
Esempio n. 3
0
        // <summary>
        // Creates a shapefile holding polygons with holes
        // </summary>
        public void PolygonsWithHoles(AxMap axMap1)
        {
            axMap1.Projection = tkMapProjection.PROJECTION_NONE;

            var  sf     = new Shapefile();
            bool result = sf.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON);

            if (!result)
            {
                MessageBox.Show(sf.ErrorMsg[sf.LastErrorCode]);
            }
            else
            {
                double xMin = 0.0;
                double yMin = 0.0;
                double xMax = 1000.0;
                double yMax = 1000.0;
                Random rnd  = new Random(DateTime.Now.Millisecond);

                // builds 10 polygons
                for (int i = 0; i < 40; i++)
                {
                    double xCenter = xMin + (xMax - xMin) * rnd.NextDouble();
                    double yCenter = yMin + (yMax - yMin) * rnd.NextDouble();

                    // random radius from 10 to 100
                    double radius = 10 + rnd.NextDouble() * 90;

                    var shp = new Shape();
                    shp.Create(ShpfileType.SHP_POLYGON);

                    // polygon must have clockwise order of points (first argument - true)
                    this.AddRing(true, xCenter, yCenter, radius, ref shp);

                    // holes must have counter-clockwise order of points (fale for the last argument)
                    this.AddRing(false, xCenter + radius / 2.0, yCenter, radius / 4.0, ref shp);
                    this.AddRing(false, xCenter - radius / 2.0, yCenter, radius / 4.0, ref shp);
                    this.AddRing(false, xCenter, yCenter + radius / 2.0, radius / 4.0, ref shp);
                    this.AddRing(false, xCenter, yCenter - radius / 2.0, radius / 4.0, ref shp);

                    for (int j = 0; j < shp.NumParts; j++)
                    {
                        Debug.Print("Part is clocwise: " + shp.PartIsClockWise[j]);
                    }

                    Debug.Print("Shape is valid: " + shp.IsValid);
                    if (!shp.IsValid)
                    {
                        Debug.Print("Reason: " + shp.IsValidReason);
                    }

                    sf.EditInsertShape(shp, ref i);
                }

                axMap1.AddLayer(sf, true);
                axMap1.ZoomToLayer(0);

                sf.SaveAs(@"c:\polygons.shp", null);
            }
        }
        private void Callback_MapControl_RasterReprojected(object sender, Events.MapControl_RasterReprojected e)
        {
            Console.WriteLine("Finished");
            Image img = new Image();

            if (img.Open(e.rasterLayer.FileName))
            {
                string proj        = img.GetProjection();
                int    layerHandle = AxMap.AddLayer(img, true);
                if (layerHandle == -1)
                {
                    Events.MapControl_Error imghandle_error = new Events.MapControl_Error()
                    {
                        ErrorCode = Events.ErrorCodes.CouldNotLoadLayer, InMethod = "AddRasterLayer", AxMapError = new GlobalSettings().GdalLastErrorMsg
                    };
                    On_Error(imghandle_error);
                }
                e.rasterLayer.Handle = layerHandle;
                MapControlTools.Layers.Add(e.rasterLayer);
                Events.MapControl_LayerChange layerchange = new Events.MapControl_LayerChange()
                {
                    LayerChangeReason = Events.LayerChangeReason.AddLayer, Layer = e.rasterLayer
                };
                On_LayerChange(layerchange);
            }
        }
Esempio n. 5
0
        public void MarkPoints(AxMap axMap1, string dataPath)
        {
            //axMap1.Projection = tkMapProjection.PROJECTION_GOOGLE_MERCATOR;
            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\buildings.shp";

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

            //sf.Open(filename, null);
            //m_layerHandle = axMap1.AddLayer(sf, true);
            sf = axMap1.get_Shapefile(m_layerHandle);     // in case a copy of shapefile was created by GlobalSettings.ReprojectLayersOnAdding
            sf = new Shapefile();
            if (!sf.CreateNewWithShapeID("", ShpfileType.SHP_POINT))
            {
                MessageBox.Show("Failed to create shapefile: " + sf.ErrorMsg[sf.LastErrorCode]);
                return;
            }
            m_layerHandle = axMap1.AddLayer(sf, true);
            ShapeDrawingOptions options = sf.DefaultDrawingOptions;

            options.PointType      = tkPointSymbolType.ptSymbolPicture;
            options.Picture        = this.OpenMarker(dataPath);
            sf.CollisionMode       = tkCollisionMode.AllowCollisions;
            axMap1.SendMouseDown   = true;
            axMap1.CursorMode      = tkCursorMode.cmNone;
            axMap1.MouseDownEvent += MainMap_MouseDownEvent;   // change MapEvents to axMap1
        }
Esempio n. 6
0
        // <summary>
        // Adds the layers and register event handler.
        // </summary>
        public void SelectBox(AxMap axMap1, string dataPath)
        {
            axMap1.Projection = tkMapProjection.PROJECTION_GOOGLE_MERCATOR;

            string filename = dataPath + "landuse.shp";

            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.SendSelectBoxFinal = true;
                MapEvents.SelectBoxFinal += AxMap1SelectBoxFinal; // change MapEvents to axMap1
                axMap1.MapUnits           = tkUnitsOfMeasure.umMeters;
                axMap1.CurrentScale       = 50000;
                axMap1.CursorMode         = tkCursorMode.cmSelection;
            }
        }
Esempio n. 7
0
        private int Add(AxMap map, object layer, bool Visible)
        {
            if (layer == null)
            {
                return(-1);
            }
            if (map == null)
            {
                throw new System.Exception("MapWinGIS.Map Object not yet set. Set Map Property before adding layers");
            }

            map.LockWindow(MapWinGIS.tkLockMode.lmLock);
            int MapLayerHandle = map.AddLayer(layer, Visible);

            if (MapLayerHandle < 0)
            {
                map.LockWindow(MapWinGIS.tkLockMode.lmUnlock);
                return(MapLayerHandle);
            }

            MapWinGIS.Shapefile sf = (layer as MapWinGIS.Shapefile);

            map.LockWindow(MapWinGIS.tkLockMode.lmUnlock);

            // FireLayerAdded(MapLayerHandle);

            return(MapLayerHandle);
        }
        public bool AddWMSLayer(string baseUrl, string layers, string name, Extents extents, int Epsg, string Format)
        {
            WmsLayer wmsLayer = new WmsLayer();

            wmsLayer.BaseUrl     = baseUrl;
            wmsLayer.BoundingBox = extents;
            wmsLayer.DoCaching   = false;
            wmsLayer.Epsg        = Epsg;
            wmsLayer.Format      = Format;
            wmsLayer.Layers      = layers;
            wmsLayer.Name        = name;
            wmsLayer.UseCache    = false;
            wmsLayer.Id          = 1;
            wmsLayer.Key         = "1";
            wmsLayer.Version     = tkWmsVersion.wv111;

            WmsLayerLayer layer = new WmsLayerLayer();

            layer.WmsLayerObj = wmsLayer;
            layer.Name        = name;
            layer.Handle      = AxMap.AddLayer(wmsLayer, true);
            layer.LayerType   = LayerType.CustomLayerWMS;

            MapControlTools.Layers.Add(layer);
            Events.MapControl_LayerChange layerchange = new Events.MapControl_LayerChange()
            {
                LayerChangeReason = Events.LayerChangeReason.AddLayer, Layer = layer
            };
            On_LayerChange(layerchange);

            return(true);
        }
Esempio n. 9
0
        public void TrackCars(AxMap axMap1, string dataPath)
        {
            if (!InitMap(axMap1, dataPath))
            {
                return;
            }

            string filename = dataPath + "path.shp";

            if (!File.Exists(filename))
            {
                MessageBox.Show("Path.shp wasn't found: " + dataPath);
                return;
            }

            int handle = axMap1.AddLayerFromFilename(filename, tkFileOpenStrategy.fosAutoDetect, false);

            var sf      = axMap1.get_Shapefile(handle);
            var service = new CarService(axMap1.Extents as Extents, sf, 20);

            _carShapefile               = CreateCarShapefile(service);
            _carShapefile.Volatile      = true;
            _carShapefile.CollisionMode = tkCollisionMode.AllowCollisions;
            axMap1.AddLayer(_carShapefile, true);

            axMap1.ZoomToLayer(handle);

            service.StateChanged += ServiceStateChanged;
        }
        public bool AddProjectLayer(ResTBPostGISLayer resTBPostGISLayer, bool visible = true)
        {
            if (!MapControlTools.Layers.Where(m => m.Name == resTBPostGISLayer.Name).Any())
            {
                Type t = resTBPostGISLayer.GetType();

                // Handle the damage potential differently
                if (resTBPostGISLayer.GetType() == typeof(ResTBDamagePotentialLayer))
                {
                    return(AddProjectLayer((ResTBDamagePotentialLayer)resTBPostGISLayer, visible));
                }
                if (resTBPostGISLayer.GetType() == typeof(ResTBRiskMapLayer))
                {
                    return(AddProjectLayer((ResTBRiskMapLayer)resTBPostGISLayer, visible));
                }

                var layer = ds.RunQuery(resTBPostGISLayer.SQL);
                if (layer == null)
                {
                    Events.MapControl_Error error = new Events.MapControl_Error()
                    {
                        ErrorCode = Events.ErrorCodes.FailedToRunSQLQuery, InMethod = "AddPostGISLayer", AxMapError = ds.GdalLastErrorMsg
                    };
                    On_Error(error);
                    return(false);
                }
                else
                {
                    int handle = AxMap.AddLayer(layer, visible);

                    if (handle == -1)
                    {
                        Events.MapControl_Error error = new Events.MapControl_Error()
                        {
                            ErrorCode = Events.ErrorCodes.CouldNotLoadLayer, InMethod = "AddPostGISLayer", AxMapError = AxMap.FileManager.get_ErrorMsg(AxMap.FileManager.LastErrorCode)
                        };
                        On_Error(error);


                        return(false);
                    }
                    else
                    {
                        resTBPostGISLayer.Handle = handle;

                        resTBPostGISLayer.ApplyStyle(AxMap);

                        MapControlTools.Layers.Add(resTBPostGISLayer);
                        Events.MapControl_LayerChange layerchange = new Events.MapControl_LayerChange()
                        {
                            LayerChangeReason = Events.LayerChangeReason.AddLayer, Layer = resTBPostGISLayer
                        };
                        On_LayerChange(layerchange);
                    }

                    return(true);
                }
            }
            return(false);
        }
Esempio n. 11
0
        private bool InitMap(AxMap axMap1, string dataPath)
        {
            axMap1.Projection             = tkMapProjection.PROJECTION_GOOGLE_MERCATOR;
            axMap1.GrabProjectionFromData = true;
            axMap1.ZoomBehavior           = tkZoomBehavior.zbUseTileLevels;

            axMap1.DisableWaitCursor = true;

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


            if (!File.Exists(filename1) || !File.Exists(filename2))
            {
                MessageBox.Show("Couldn't find the files (buildings.shp, roads.shp): " + dataPath);
                return(false);
            }

            Shapefile sf = new Shapefile();

            sf.Open(filename1, null);
            axMap1.AddLayer(sf, true);

            Debug.Print(axMap1.GeoProjection.ExportToWKT());

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

            axMap1.ZoomToMaxExtents();
            return(true);
        }
        public bool AddSHPLayer()
        {
            string    filename = @"c:\users\suter\documents\test.shp";
            Shapefile sf       = new Shapefile();

            if (sf.Open(filename))
            {
                int m_layerHandle = AxMap.AddLayer(sf, true);
                sf = AxMap.get_Shapefile(m_layerHandle);     // in case a copy of shapefile was created by GlobalSettings.ReprojectLayersOnAdding

                ShpLayer sl = new ShpLayer();
                sl.LayerType = LayerType.CustomLayerSHP;
                sl.Name      = "Gefahrenkarte";
                sl.Shapefile = sf;
                sl.Handle    = m_layerHandle;

                MapControlTools.Layers.Add(sl);
                Events.MapControl_LayerChange layerchange = new Events.MapControl_LayerChange()
                {
                    LayerChangeReason = Events.LayerChangeReason.AddLayer, Layer = sl
                };
                On_LayerChange(layerchange);
                return(true);
            }
            else
            {
                Events.MapControl_Error error = new Events.MapControl_Error()
                {
                    ErrorCode = Events.ErrorCodes.CouldNotLoadLayer, InMethod = "AddShpLayer", AxMapError = sf.ErrorMsg[sf.LastErrorCode]
                };
                On_Error(error);
                return(false);
            }
        }
Esempio n. 13
0
        public void EditAddShapeTest()
        {
            // https://mapwindow.discourse.group/t/system-accessviolationexception-after-editaddshape/196
            var pnt = new Point {
                x = 6.7369281, y = 53.1603648
            };

            var shp = new Shape();

            shp.Create(ShpfileType.SHP_POLYGON);
            shp.InsertPoint(pnt, 0);

            var sf     = new Shapefile();
            var result = sf.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON);

            Assert.IsTrue(result, "CreateNewWithShapeID failed: " + sf.ErrorMsg[sf.LastErrorCode]);

            var shpIndex = sf.EditAddShape(shp);

            Assert.IsTrue(shpIndex > -1, "EditAddShape failed: " + sf.ErrorMsg[sf.LastErrorCode]);

            sf.InteractiveEditing = true;
            Assert.IsTrue(sf.InteractiveEditing, "InteractiveEditing failed: " + sf.ErrorMsg[sf.LastErrorCode]);

            var layerIndex = _axMap1.AddLayer(sf, true);

            Assert.IsTrue(layerIndex > -1, "AddLayer failed: " + sf.ErrorMsg[sf.LastErrorCode]);

            result = _axMap1.ShapeEditor.StartEdit(layerIndex, shpIndex);
            Assert.IsTrue(result, "ShapeEditor.StartEdit failed: " + sf.ErrorMsg[sf.LastErrorCode]);
        }
Esempio n. 14
0
        private void AddPoint(AxMap Map, double lng, double lat, string pointName)
        {
            var sf = new Shapefile();

            if (PointShapefileLayerHandle != -1)
            {
                sf = Map.get_Shapefile(PointShapefileLayerHandle);
            }

            if (PointShapefileLayerHandle == -1)
            {
                if (!sf.CreateNewWithShapeID("", ShpfileType.SHP_POINT))
                {
                    MessageBox.Show("Failed to create shapefile: " + sf.ErrorMsg[sf.LastErrorCode]);
                    return;
                }
                PointShapefileLayerHandle = Map.AddLayer(sf, true);
            }

            var utils = new Utils();
            ShapeDrawingOptions options = sf.DefaultDrawingOptions;

            options.PointType        = tkPointSymbolType.ptSymbolStandard;
            options.PointShape       = tkPointShapeType.ptShapeCross;
            options.FillColor        = utils.ColorByName(tkMapColor.Black);
            sf.DefaultDrawingOptions = options;
            sf.CollisionMode         = tkCollisionMode.AllowCollisions;


            Shape shp = new Shape();


            //shp = sf.get_Shape(shapeIndex);
            shp.Create(ShpfileType.SHP_POINT);



            MapWinGIS.Point pnt = new MapWinGIS.Point();
            pnt.x   = lng;
            pnt.y   = lat;
            pnt.Key = pointName;

            int Index;

            Index = shp.NumPoints;

            shp.InsertPoint(pnt, ref Index);

            Index = sf.NumShapes;

            if (!sf.EditInsertShape(shp, Index))
            {
                MessageBox.Show("Failed to insert shape: " + sf.ErrorMsg[sf.LastErrorCode]);
                return;
            }

            points.Add(pnt);
            Map.Redraw();
        }
Esempio n. 15
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();
            }
        }
Esempio n. 16
0
        public static void CreatePointShapefile(AxMap Map, List <GisPoint>[] ListData, int num)
        {
            var  sf     = new Shapefile();                                         //创建一个新的shp文件
            bool result = sf.CreateNewWithShapeID("", ShpfileType.SHP_MULTIPOINT); //初始化shp文件

            for (int j = 0; j < num - 1; j++)
            {
                Shape shp = new Shape(); //创建shp图层
                shp.Create(ShpfileType.SHP_MULTIPOINT);
                for (int i = 0; i < ListData[j].Count; i++)
                {
                    var pnt = new Point();
                    pnt.x   = ListData[j][i].X;
                    pnt.y   = ListData[j][i].Y;
                    pnt.Key = "fang";
                    int index = 0;
                    shp.InsertPoint(pnt, ref index);
                }
                sf.EditAddShape(shp);
                if (j == 0)
                {
                    var utils            = new Utils();
                    ShapefileCategory ct = sf.Categories.Add("0");
                    ct.DrawingOptions.FillType  = tkFillType.ftGradient;
                    ct.DrawingOptions.FillColor = utils.ColorByName(tkMapColor.Green);
                    sf.set_ShapeCategory(0, 0);
                }
                else if (j == 1)
                {
                    var utils            = new Utils();
                    ShapefileCategory ct = sf.Categories.Add("1");
                    ct.DrawingOptions.FillType  = tkFillType.ftStandard;
                    ct.DrawingOptions.FillColor = utils.ColorByName(tkMapColor.Blue);
                    sf.set_ShapeCategory(1, 1);
                }
                else if (j == 2)
                {
                    var utils            = new Utils();
                    ShapefileCategory ct = sf.Categories.Add("2");
                    ct.DrawingOptions.FillType  = tkFillType.ftStandard;
                    ct.DrawingOptions.FillColor = utils.ColorByName(tkMapColor.Yellow);
                    sf.set_ShapeCategory(2, 2);
                }
                else
                {
                    var utils            = new Utils();
                    ShapefileCategory ct = sf.Categories.Add("3");
                    ct.DrawingOptions.FillType  = tkFillType.ftStandard;
                    ct.DrawingOptions.FillColor = utils.ColorByName(tkMapColor.Red);
                    sf.set_ShapeCategory(3, 3);
                }
            }
            sf.DefaultDrawingOptions.SetDefaultPointSymbol(tkDefaultPointSymbol.dpsTriangleUp);
            Map.AddLayer(sf, true);
            Map.SendMouseMove = true;
        }
Esempio n. 17
0
        // <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);
            }
        }
        // <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();
            }
        }
Esempio n. 19
0
        private void UpdatePoint(AxMap Map, List <MapWinGIS.Point> PointsToUpdate)
        {
            var sf = new Shapefile();

            if (PointShapefileLayerHandle != -1)
            {
                sf = Map.get_Shapefile(PointShapefileLayerHandle);
            }

            if (PointShapefileLayerHandle == -1)
            {
                if (!sf.CreateNewWithShapeID("", ShpfileType.SHP_POINT))
                {
                    MessageBox.Show("Failed to create shapefile: " + sf.ErrorMsg[sf.LastErrorCode]);
                    return;
                }
                PointShapefileLayerHandle = Map.AddLayer(sf, true);
            }
            ShapeDrawingOptions options = sf.DefaultDrawingOptions;

            options.PointType        = tkPointSymbolType.ptSymbolStandard;
            options.PointShape       = tkPointShapeType.ptShapeCross;
            sf.DefaultDrawingOptions = options;
            sf.CollisionMode         = tkCollisionMode.AllowCollisions;
            sf.EditClear();

            foreach (MapWinGIS.Point PointToUpdate in PointsToUpdate)
            {
                Shape shp = new Shape();
                shp.Create(ShpfileType.SHP_POINT);
                MapWinGIS.Point pnt = PointToUpdate;

                int Index;
                Index = shp.NumPoints;

                shp.InsertPoint(pnt, ref Index);

                Index = sf.NumShapes;

                if (!sf.EditInsertShape(shp, Index))
                {
                    MessageBox.Show("Failed to insert shape: " + sf.ErrorMsg[sf.LastErrorCode]);
                    return;
                }

                Map.Redraw();
            }
            if (PointsToUpdate.Count == 0)
            {
                Map.Redraw();
            }
        }
        private bool AddProjectLayer(ResTBRiskMapLayer resTBRiskMapLayer, bool visible = true)
        {
            if (!MapControlTools.Layers.Where(m => m.Name == resTBRiskMapLayer.Name).Any())
            {
                var pointlayer   = ds.RunQuery(resTBRiskMapLayer.SQL_Point);
                var linelayer    = ds.RunQuery(resTBRiskMapLayer.SQL_Line);
                var polygonlayer = ds.RunQuery(resTBRiskMapLayer.SQL_Polygon);
                if ((pointlayer == null) || (linelayer == null) || (polygonlayer == null))
                {
                    Events.MapControl_Error error = new Events.MapControl_Error()
                    {
                        ErrorCode = Events.ErrorCodes.FailedToRunSQLQuery, InMethod = "AddPostGISLayer", AxMapError = ds.GdalLastErrorMsg
                    };
                    On_Error(error);
                    return(false);
                }
                else
                {
                    int pointhandle   = AxMap.AddLayer(pointlayer, visible);
                    int linehandle    = AxMap.AddLayer(linelayer, visible);
                    int polygonhandle = AxMap.AddLayer(polygonlayer, visible);

                    if ((pointhandle == -1) || (linehandle == -1) || (polygonhandle == -1))
                    {
                        Events.MapControl_Error error = new Events.MapControl_Error()
                        {
                            ErrorCode = Events.ErrorCodes.CouldNotLoadLayer, InMethod = "AddPostGISLayer", AxMapError = AxMap.FileManager.get_ErrorMsg(AxMap.FileManager.LastErrorCode)
                        };
                        On_Error(error);
                        return(false);
                    }
                    else
                    {
                        resTBRiskMapLayer.PointHandle   = pointhandle;
                        resTBRiskMapLayer.LineHandle    = linehandle;
                        resTBRiskMapLayer.PolygonHandle = polygonhandle;
                        resTBRiskMapLayer.ApplyStyle(AxMap);

                        MapControlTools.Layers.Add(resTBRiskMapLayer);
                        Events.MapControl_LayerChange layerchange = new Events.MapControl_LayerChange()
                        {
                            LayerChangeReason = Events.LayerChangeReason.AddLayer, Layer = resTBRiskMapLayer
                        };
                        On_LayerChange(layerchange);
                    }

                    return(true);
                }
            }
            return(false);
        }
Esempio n. 21
0
        // <summary>
        // Adds randomly positioned labels to the image layer.
        // </summary>
        public void ImageLabels(AxMap axMap1)
        {
            axMap1.Projection             = tkMapProjection.PROJECTION_NONE;
            axMap1.GrabProjectionFromData = true;

            Image          img = new Image();
            OpenFileDialog dlg = new OpenFileDialog {
                Filter = img.CdlgFilter
            };

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                img.Open(dlg.FileName, ImageType.USE_FILE_EXTENSION, false, null);
                axMap1.AddLayer(img, true);

                Labels lbl = img.Labels;
                lbl.FontSize = 12;
                lbl.FontBold = true;

                lbl.FontOutlineVisible = true;
                lbl.FontOutlineColor   = (255 << 16) + (255 << 8) + 255; //white
                lbl.FontOutlineWidth   = 4;

                LabelCategory cat = lbl.AddCategory("Red");
                cat.FontColor = 255;

                cat           = lbl.AddCategory("Blue");
                cat.FontColor = 255 << 16;

                cat           = lbl.AddCategory("Yellow");
                cat.FontColor = 255 + 255 << 8;

                Extents ext    = img.Extents;
                double  xRange = ext.xMax - ext.xMin;
                double  yRange = ext.yMax - ext.yMin;
                Random  rnd    = new Random();

                for (int i = 0; i < 100; i++)
                {
                    double x = xRange * rnd.NextDouble();
                    double y = yRange * rnd.NextDouble();

                    int categoryIndex = i % 3;
                    lbl.AddLabel("label" + Convert.ToString(i),
                                 ext.xMin + x, ext.yMin + y, i * 3.6, categoryIndex);
                }

                axMap1.Redraw();
            }
        }
Esempio n. 22
0
        // <summary>
        // Loads the layers and registers event handlers
        // </summary>
        public void MarkPoints(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);
            m_layerHandle = axMap1.AddLayer(sf, true);
            sf            = axMap1.get_Shapefile(m_layerHandle); // in case a copy of shapefile was created by GlobalSettings.ReprojectLayersOnAdding

            sf = new Shapefile();
            if (!sf.CreateNewWithShapeID("", ShpfileType.SHP_POINT))
            {
                MessageBox.Show("Failed to create shapefile: " + sf.ErrorMsg[sf.LastErrorCode]);
                return;
            }

            m_layerHandle = axMap1.AddLayer(sf, true);

            ShapeDrawingOptions options = sf.DefaultDrawingOptions;

            options.PointType = tkPointSymbolType.ptSymbolPicture;
            options.Picture   = this.OpenMarker(dataPath);
            sf.CollisionMode  = tkCollisionMode.AllowCollisions;

            axMap1.SendMouseDown      = true;
            axMap1.CursorMode         = tkCursorMode.cmNone;
            MapEvents.MouseDownEvent += AxMap1MouseDownEvent;   // change MapEvents to axMap1
        }
Esempio n. 23
0
        // <summary>
        // Creates and displayes custom line patterns
        // </summary>
        public void LinePattern(AxMap axMap1, string iconPath)
        {
            axMap1.Projection = tkMapProjection.PROJECTION_NONE;

            var sf = this.CreateLines();

            axMap1.AddLayer(sf, true);

            var utils = new Utils();

            // railroad pattern
            LinePattern pattern = new LinePattern();

            pattern.AddLine(utils.ColorByName(tkMapColor.Black), 6.0f, tkDashStyle.dsSolid);
            pattern.AddLine(utils.ColorByName(tkMapColor.White), 5.0f, tkDashStyle.dsDot);

            ShapefileCategory ct = sf.Categories.Add("Railroad");

            ct.DrawingOptions.LinePattern    = pattern;
            ct.DrawingOptions.UseLinePattern = true;
            sf.set_ShapeCategory(0, 0);

            // river pattern
            pattern = new LinePattern();
            pattern.AddLine(utils.ColorByName(tkMapColor.DarkBlue), 6.0f, tkDashStyle.dsSolid);
            pattern.AddLine(utils.ColorByName(tkMapColor.LightBlue), 4.0f, tkDashStyle.dsSolid);

            ct = sf.Categories.Add("River");
            ct.DrawingOptions.LinePattern    = pattern;
            ct.DrawingOptions.UseLinePattern = true;
            sf.set_ShapeCategory(1, 1);

            // road with direction
            pattern = new LinePattern();
            pattern.AddLine(utils.ColorByName(tkMapColor.Gray), 8.0f, tkDashStyle.dsSolid);
            pattern.AddLine(utils.ColorByName(tkMapColor.Yellow), 7.0f, tkDashStyle.dsSolid);
            LineSegment segm = pattern.AddMarker(tkDefaultPointSymbol.dpsArrowRight);

            segm.Color          = utils.ColorByName(tkMapColor.Orange);
            segm.MarkerSize     = 10;
            segm.MarkerInterval = 32;

            ct = sf.Categories.Add("Direction");
            ct.DrawingOptions.LinePattern    = pattern;
            ct.DrawingOptions.UseLinePattern = true;
            sf.set_ShapeCategory(2, 2);
        }
        // <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");
            }
        }
Esempio n. 25
0
        public int AddNewShapefileLayer(string layerName, ShpfileType shapefileType, bool isVisile = true, bool visibleInUI = false)
        {
            var sf = new Shapefile();

            if (sf.CreateNewWithShapeID("", shapefileType))
            {
                sf.GeoProjection = _axmap.GeoProjection;
            }
            var h = _axmap.AddLayer(sf, isVisile);

            if (h >= 0)
            {
                _axmap.set_LayerName(h, layerName);
            }
            return(h);
        }
Esempio n. 26
0
        /// <summary>
        /// 根据坐标在地图上划线
        /// </summary>
        /// <param name="Xstart"></param>
        /// <param name="Ystart"></param>
        /// <param name="Xend"></param>
        /// <param name="Yend"></param>
        public int WriteLine(ClassLine line, LineSet lineSet)
        {
            Shape shp = new Shape();

            shp.Create(ShpfileType.SHP_POLYLINE);

            Point pnt = new Point();

            pnt.x = line.startX;
            pnt.y = line.startY;
            int index = shp.numPoints;

            shp.InsertPoint(pnt, ref index);

            pnt   = new Point();
            pnt.x = line.endX;
            pnt.y = line.endY;
            index = shp.numPoints;
            shp.InsertPoint(pnt, ref index);

            index = sf.NumShapes;
            sf.EditInsertShape(shp, ref index);


            //var utils = new Utils();
            //LinePattern pattern = new LinePattern();
            //pattern.AddLine(utils.ColorByName(lineSet.color), lineSet.Width, lineSet.style);
            //ShapefileCategory ct = sf.Categories.Add("Railroad");
            //ct.DrawingOptions.LinePattern = pattern;
            //ct.DrawingOptions.UseLinePattern = true;
            //sf.set_ShapeCategory(0, 0);

            var         utils   = new Utils();
            LinePattern pattern = new LinePattern();

            pattern.AddLine(utils.ColorByName(lineSet.color), lineSet.Width, lineSet.style);
            sf.DefaultDrawingOptions.LinePattern    = pattern;
            sf.DefaultDrawingOptions.UseLinePattern = true;
            layerHandle = map.AddLayer(sf, true);



            return(layerHandle);
        }
Esempio n. 27
0
        // <summary>
        // Selects shapes with certain attributes.
        // </summary>
        public void SelectByQuery(AxMap axMap1, string dataPath)
        {
            axMap1.Projection = tkMapProjection.PROJECTION_GOOGLE_MERCATOR;

            string filename = dataPath + "landuse.shp";
            var    sf       = new Shapefile();

            if (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

                // showing labels for [name] field
                sf.Labels.Generate("[type]", tkLabelPositioning.lpCentroid, true);

                string error  = "";
                object result = null;

                // the text values must be placed in quotes; we need to shield them with \ sign in C#
                // fields are must be placed in square brackets
                string query = "[type] = \"residential\" AND [osm_id] > 40000000";

                if (sf.Table.Query(query, ref result, ref error))
                {
                    int[] shapes = result as int[];
                    if (shapes != null)
                    {
                        for (int i = 0; i < shapes.Length; i++)
                        {
                            sf.set_ShapeSelected(shapes[i], true);
                        }
                    }
                    axMap1.ZoomToSelected(layerHandle);
                    MessageBox.Show("Objects selected: " + sf.NumSelected);
                }
                else
                {
                    MessageBox.Show("No shapes agree with the condition.");
                }
            }
        }
        // <summary>
        // Creates a point shapefile by placing 1000 points randomly
        // </summary>
        public void CreatePointShapefile(AxMap axMap1)
        {
            axMap1.Projection = tkMapProjection.PROJECTION_NONE;

            var sf = new Shapefile();

            // MWShapeId field will be added to attribute table
            bool result = sf.CreateNewWithShapeID("", ShpfileType.SHP_POINT);

            // bounding box for the new shapefile
            double xMin = 0.0;
            double yMin = 0.0;
            double xMax = 1000.0;
            double yMax = 1000.0;

            // the location of points will be random
            Random rnd = new Random(DateTime.Now.Millisecond);

            // creating points and inserting them in the shape
            for (int i = 0; i < 1000; i++)
            {
                var pnt = new Point();
                pnt.x = xMin + (xMax - xMin) * rnd.NextDouble();
                pnt.y = yMin + (yMax - yMin) * rnd.NextDouble();

                Shape shp = new Shape();
                shp.Create(ShpfileType.SHP_POINT);

                int index = 0;
                shp.InsertPoint(pnt, ref index);
                sf.EditInsertShape(shp, ref i);
            }

            sf.DefaultDrawingOptions.SetDefaultPointSymbol(tkDefaultPointSymbol.dpsStar);

            // adds shapefile to the map
            axMap1.AddLayer(sf, true);

            // save if needed
            //sf.SaveAs(@"c:\points.shp", null);
        }
Esempio n. 29
0
        // <summary>
        // Loads the layers and registers event handler
        // </summary>
        public void RemoveShape(AxMap axMap1, string dataPath)
        {
            axMap1.Projection = tkMapProjection.PROJECTION_GOOGLE_MERCATOR;

            string filename = dataPath + "natural.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.StartEditingShapes(true, null))
            {
                MessageBox.Show("Failed to start edit mode: " + sf.ErrorMsg[sf.LastErrorCode]);
            }
            else
            {
                int fieldIndex = sf.EditAddField("ShapeIndex", FieldType.INTEGER_FIELD, 0, 0);
                for (int i = 0; i < sf.NumShapes; i++)
                {
                    sf.EditCellValue(fieldIndex, i, i);
                }
                sf.Labels.Generate("[ShapeIndex]", tkLabelPositioning.lpCentroid, false);
                sf.Labels.Synchronized      = true;
                sf.Labels.TextRenderingHint = tkTextRenderingHint.SystemDefault;

                axMap1.SendMouseDown      = true;
                MapEvents.MouseDownEvent += AxMap1MouseDownEvent1;  // change MapEvents to axMap1
                axMap1.MapUnits           = tkUnitsOfMeasure.umMeters;
                axMap1.CurrentScale       = 50000;
                axMap1.CursorMode         = tkCursorMode.cmNone;
            }
        }
        // <summary>
        // Build a list of unique values of the given field and imlement zooming to them from the context menu
        // </summary>
        public void LabelSelection(AxMap axMap1, string dataPath)
        {
            axMap1.Projection = tkMapProjection.PROJECTION_GOOGLE_MERCATOR;

            string filename = dataPath + "buildings.shp";

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

            Shapefile sf = new Shapefile();

            sf.Open(filename, null);
            m_layerHandle = axMap1.AddLayer(sf, true);
            sf            = axMap1.get_Shapefile(m_layerHandle); // in case a copy of shapefile was created by GlobalSettings.ReprojectLayersOnAdding

            // let's add labels consisting of Name and type of building on a separate lines
            sf.Labels.Generate("[Type]", tkLabelPositioning.lpCenter, false);
            sf.Labels.FrameVisible = true;
            sf.Labels.FrameType    = tkLabelFrameType.lfRectangle;

            // now let's add categories
            Utils utils = new Utils();  // to specify colors

            LabelCategory ct = sf.Labels.AddCategory("Selected");

            ct.FrameBackColor = utils.ColorByName(tkMapColor.Yellow);

            ct         = sf.Labels.AddCategory("Hidden");
            ct.Visible = false;



            axMap1.SendSelectBoxFinal = true;
            axMap1.SendMouseDown      = true;
            axMap1.CursorMode         = tkCursorMode.cmSelection;
            MapEvents.SelectBoxFinal += AxMap1SelectBoxFinal2;
        }
Esempio n. 31
0
        // <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");
            }
        }