Exemplo n.º 1
0
        /// <summary>
        /// Initializes this map viewer and constructs the user interface based on the
        /// given AppLayout document
        /// </summary>
        /// <param name="layout"></param>
        /// <param name="provider"></param>
        public void Initialize(AppLayout layout, MgMapViewerProvider provider)
        {
            this.Text = layout.Title;

            if (!string.IsNullOrEmpty(layout.Language))
            {
                try
                {
                    var ci = CultureInfo.GetCultureInfo(layout.Language);
                    System.Threading.Thread.CurrentThread.CurrentUICulture 
                        = System.Threading.Thread.CurrentThread.CurrentCulture
                        = ci;
                    SetLanguage(ci);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, Strings.SetLanguage);
                }
            }

            _menuInvoker = new MgMenuItemComponentInvoker();
            _toolInvoker = new MgToolButtonComponentInvoker();

            ValidateMapNames(layout);

            InitializeComponentSet(layout);
            InitializeMenu(layout.Menu);
            InitializeToolbar(layout.Toolbar);
            InitializeContextMenu(layout.ContextMenu);
            InitializeTaskPaneMenu(layout.TaskPane.TaskMenu);

            _layout = layout;
            if (!string.IsNullOrEmpty(_layout.Icon) && System.IO.File.Exists(_layout.Icon))
            {
                this.Icon = new System.Drawing.Icon(_layout.Icon);
            }

            SetInfoPaneWidth(_layout.InfoPane.Width);
            SetInfoPaneVisible(_layout.InfoPane.IsVisible);
            if (_layout.InfoPane.IsVisible)
            {
                SetLegendVisbility(_layout.InfoPane.Legend.Visible);
                legend.ShowTooltips = _layout.InfoPane.Legend.ShowTooltips;
                if (_layout.InfoPane.Legend.ThemeCompressionLimit.HasValue)
                    legend.ThemeCompressionLimit = _layout.InfoPane.Legend.ThemeCompressionLimit.Value;
                SetPropertyPaneVisbility(_layout.InfoPane.PropertyPane.Visible);
            }
            SetTaskPaneWidth(_layout.TaskPane.Width);
            if (!string.IsNullOrEmpty(_layout.TaskPane.InitialComponentID))
            {
                var cmp = GetComponent(_layout.TaskPane.InitialComponentID) as MgViewerComponent;
                if (cmp != null)
                    taskPane.SetInitialComponent(cmp);
                else
                    MessageBox.Show(string.Format(Strings.WarnInitialTaskComponentNotFound, _layout.TaskPane.InitialComponentID));
            }

            _provider = provider;
            mapViewer.PropertyChanged += new PropertyChangedEventHandler(OnMapViewerPropertyChanged);
        }
Exemplo n.º 2
0
        private void btnSinglePlot_Click(object sender, EventArgs e)
        {
            MgdMap map = (MgdMap)_viewer.GetMap();
            MgMapViewerProvider  provider   = _viewer.GetProvider();
            MgdMappingService    mappingSvc = (MgdMappingService)provider.CreateService(MgServiceType.MappingService);
            MgResourceIdentifier layoutId   = new MgResourceIdentifier("Library://Samples/Sheboygan/Layouts/SheboyganMap.PrintLayout");

            using (SaveFileDialog save = new SaveFileDialog())
            {
                save.Filter = "DWF Files (*.dwf)|*.dwf";
                if (save.ShowDialog() == DialogResult.OK)
                {
                    MgdDwfVersion dwfVer = new MgdDwfVersion("6.01", "1.2");

                    MgdLayout            layout   = new MgdLayout(layoutId, "City of Sheboygan", MgdPageUnitsType.Inches);
                    MgdPlotSpecification plotSpec = new MgdPlotSpecification(8.5f, 11.0f, MgdPageUnitsType.Inches, 0.5f, 0.5f, 0.5f, 0.5f);

                    MgByteReader result = mappingSvc.GeneratePlot(map, plotSpec, layout, dwfVer);
                    MgByteSink   sink   = new MgByteSink(result);
                    sink.ToFile(save.FileName);

                    MessageBox.Show("Saved to " + save.FileName);
                }
            }
        }
Exemplo n.º 3
0
        private void btnListSelected_Click(object sender, EventArgs e)
        {
            // There's two ways to process a selection
            //
            // 1. Iterate through the layers of a MgSelectionSet and process
            // the feature reader for each layer
            //
            // 2. Use an MgSelectionSet helper class
            //
            // This example shows the 2nd way, which is the simpler one
            MgSelectionBase     selection = _viewer.GetSelection();
            MgMapViewerProvider provider  = _viewer.GetProvider();
            MgSelectionSet      sset      = new MgSelectionSet(selection);

            new SelectedFeaturesWindow(sset).ShowDialog();
        }
Exemplo n.º 4
0
        private void btnMultiPlot_Click(object sender, EventArgs e)
        {
            MgdMap map = (MgdMap)_viewer.GetMap();
            MgMapViewerProvider  provider   = _viewer.GetProvider();
            MgdMappingService    mappingSvc = (MgdMappingService)provider.CreateService(MgServiceType.MappingService);
            MgResourceIdentifier layoutId   = new MgResourceIdentifier("Library://Samples/Sheboygan/Layouts/SheboyganMap.PrintLayout");

            using (SaveFileDialog save = new SaveFileDialog())
            {
                save.Filter = "DWF Files (*.dwf)|*.dwf";
                if (save.ShowDialog() == DialogResult.OK)
                {
                    MgdDwfVersion dwfVer = new MgdDwfVersion("6.01", "1.2");

                    MgdLayout            layout   = new MgdLayout(layoutId, "City of Sheboygan", MgdPageUnitsType.Inches);
                    MgdPlotSpecification plotSpec = new MgdPlotSpecification(8.5f, 11.0f, MgdPageUnitsType.Inches, 0.5f, 0.5f, 0.5f, 0.5f);

                    MgdMapPlotCollection plotCollection = new MgdMapPlotCollection();

                    MgdMapPlot plot1 = new MgdMapPlot(map, plotSpec, layout);
                    plot1.SetCenterAndScale(map.GetViewCenter().GetCoordinate(), map.GetViewScale() * 2);
                    plotCollection.Add(plot1);

                    // Create a second map for the second sheet in the DWF. This second sheet uses the print layout
                    // to display a page title and legend.

                    MgdMap     map2  = new MgdMap(map.GetMapDefinition(), "Sheet 2");
                    MgdMapPlot plot2 = new MgdMapPlot(map2, plotSpec, layout);
                    plot2.SetCenterAndScale(map.GetViewCenter().GetCoordinate(), map.GetViewScale());
                    plotCollection.Add(plot2);

                    MgByteReader result = mappingSvc.GenerateMultiPlot(plotCollection, dwfVer);
                    MgByteSink   sink   = new MgByteSink(result);
                    sink.ToFile(save.FileName);

                    MessageBox.Show("Saved to " + save.FileName);
                }
            }
        }
Exemplo n.º 5
0
        private void btnRenderMap2_Click(object sender, EventArgs e)
        {
            //Note we're casting to mg-desktop specific subclasses as this is what mg-desktop rendering APIs expect
            MgdMap              map         = (MgdMap)_viewer.GetMap();
            MgdSelection        selection   = (MgdSelection)_viewer.GetSelection();
            MgMapViewerProvider provider    = _viewer.GetProvider();
            MgdRenderingService renderSvc   = (MgdRenderingService)provider.CreateService(MgServiceType.RenderingService);
            MgPoint             centerPt    = map.ViewCenter;
            MgCoordinate        centerCoord = centerPt.Coordinate;

            //MgdTransientMapState is a helper class which lets us apply transient state to a map, which is automatically
            //undone on disposal. This is how we can render custom views of a map with specific display parameters without
            //permanently changing the display parameters used by the map viewer
            using (MgTransientMapState tempState = provider.CreateTransientState(map))
            {
                MgMapDisplayParameters state = new MgMapDisplayParameters(centerCoord.X, centerCoord.Y, 5000, 1024, 768, 96);
                tempState.PushState(state);

                MgByteReader br = renderSvc.RenderMap(map, selection, "PNG");
                using (SaveFileDialog save = new SaveFileDialog())
                {
                    save.Filter = "Portable Network Graphics (*.png)|*.png";
                    if (save.ShowDialog() == DialogResult.OK)
                    {
                        //MgReadOnlyStream is a stream adapter class that provides a .net stream
                        //interface to the MgByteReader, allowing MgByteReader objects to be used
                        //anywhere a System.IO.Stream is expected.
                        using (MgReadOnlyStream stream = new MgReadOnlyStream(br))
                        {
                            Image img = Image.FromStream(stream);
                            img.Save(save.FileName);
                            MessageBox.Show("Image saved to: " + save.FileName);
                        }
                    }
                    br.Dispose();
                }
            }
        }
Exemplo n.º 6
0
        private void btnCreateBuffer_Click(object sender, EventArgs e)
        {
            MgSelectionBase           selection = _viewer.GetSelection();
            MgReadOnlyLayerCollection layers    = selection.GetLayers();

            if (layers == null)
            {
                MessageBox.Show("Select a parcel");
                return;
            }
            MgLayerBase parcels = null;

            for (int i = 0; i < layers.GetCount(); i++)
            {
                MgLayerBase layer = layers.GetItem(i);
                if (layer.Name == "Parcels")
                {
                    parcels = layer;
                    break;
                }
            }
            if (parcels == null)
            {
                MessageBox.Show("Select a parcel");
                return;
            }

            int bufferRingSize  = 100; // measured in metres
            int bufferRingCount = 5;

            // Set up some objects for coordinate conversion
            MgMapBase           map             = _viewer.GetMap();
            MgLayerCollection   mapLayers       = map.GetLayers();
            MgMapViewerProvider provider        = _viewer.GetProvider();
            MgResourceService   resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);
            //Casting to MgdFeatureService because we want to use convenience APIs
            MgFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService);

            String                    mapWktSrs               = map.GetMapSRS();
            MgAgfReaderWriter         agfReaderWriter         = new MgAgfReaderWriter();
            MgWktReaderWriter         wktReaderWriter         = new MgWktReaderWriter();
            MgCoordinateSystemFactory coordinateSystemFactory = new MgCoordinateSystemFactory();
            MgCoordinateSystem        srs        = coordinateSystemFactory.Create(mapWktSrs);
            MgMeasure                 srsMeasure = srs.GetMeasure();
            string                    sessionId  = Guid.NewGuid().ToString();

            BufferHelper helper = new BufferHelper();

            // Check for a buffer layer. If it exists, delete
            // the current features.
            // If it does not exist, create a feature source and
            // a layer to hold the buffer.

            MgdLayer bufferLayer = null;
            int      layerIndex  = mapLayers.IndexOf("Buffer");

            if (layerIndex < 0)
            {
                // The layer does not exist and must be created.

                MgResourceIdentifier bufferFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//Buffer.FeatureSource");
                helper.CreateBufferFeatureSource(featureService, mapWktSrs, bufferFeatureResId);
                bufferLayer = helper.CreateBufferLayer(resourceService, bufferFeatureResId, sessionId);
                mapLayers.Insert(0, bufferLayer);
            }
            else
            {
                bufferLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex);
                bufferLayer.DeleteFeatures("ID like '%'");
            }

            // Get the selected features from the MgSelection object
            MgFeatureReader featureReader = selection.GetSelectedFeatures(parcels, parcels.GetFeatureClassName(), false);

            // Process each item in the MgFeatureReader. Get the
            // geometries from all the selected features and
            // merge them into a single geometry.

            MgGeometryCollection inputGeometries = new MgGeometryCollection();

            while (featureReader.ReadNext())
            {
                MgByteReader featureGeometryData = featureReader.GetGeometry(parcels.GetFeatureGeometryName());
                MgGeometry   featureGeometry     = agfReaderWriter.Read(featureGeometryData);

                inputGeometries.Add(featureGeometry);
            }

            MgGeometryFactory geometryFactory  = new MgGeometryFactory();
            MgGeometry        mergedGeometries = geometryFactory.CreateMultiGeometry(inputGeometries);

            // Add buffer features to the temporary feature source.
            // Create multiple concentric buffers to show area.
            // If the stylization for the layer draws the features
            // partially transparent, the concentric rings will be
            // progressively darker towards the center.
            // The stylization is set in the layer template file, which
            // is used in function CreateBufferLayer().

            for (int bufferRing = 0; bufferRing < bufferRingCount; bufferRing++)
            {
                double     bufferDist     = srs.ConvertMetersToCoordinateSystemUnits(bufferRingSize * (bufferRing + 1));
                MgGeometry bufferGeometry = mergedGeometries.Buffer(bufferDist, srsMeasure);

                MgPropertyCollection properties = new MgPropertyCollection();
                properties.Add(new MgGeometryProperty("BufferGeometry", agfReaderWriter.Write(bufferGeometry)));

                MgFeatureReader fr = bufferLayer.InsertFeatures(properties);
                fr.Close();
            }

            bufferLayer.SetVisible(true);
            bufferLayer.ForceRefresh();
            bufferLayer.SetDisplayInLegend(true);

            MessageBox.Show("Buffer created");
            _viewer.RefreshMap();
            IMapLegend legend = Shell.Instance.Legend;

            if (legend != null)
            {
                legend.RefreshLegend();
            }
        }
Exemplo n.º 7
0
        private void btnFindFeaturesInBuffer_Click(object sender, EventArgs e)
        {
            MgSelectionBase           selection      = _viewer.GetSelection();
            MgReadOnlyLayerCollection selectedLayers = selection.GetLayers();

            if (selectedLayers == null)
            {
                MessageBox.Show("Select a parcel");
                return;
            }
            MgLayerBase parcels = null;

            for (int i = 0; i < selectedLayers.GetCount(); i++)
            {
                MgLayerBase layer = selectedLayers.GetItem(i);
                if (layer.Name == "Parcels")
                {
                    parcels = layer;
                    break;
                }
            }
            if (parcels == null)
            {
                MessageBox.Show("Select a parcel");
                return;
            }

            int bufferRingSize = 500; // measured in metres

            // Set up some objects for coordinate conversion

            MgMapBase           map             = _viewer.GetMap();
            MgLayerCollection   mapLayers       = map.GetLayers();
            MgMapViewerProvider provider        = _viewer.GetProvider();
            MgResourceService   resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);
            //Casting to MgdFeatureService because we want to use convenience APIs
            MgFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService);
            string           sessionId      = Guid.NewGuid().ToString();

            String                    mapWktSrs               = map.GetMapSRS();
            MgAgfReaderWriter         agfReaderWriter         = new MgAgfReaderWriter();
            MgWktReaderWriter         wktReaderWriter         = new MgWktReaderWriter();
            MgCoordinateSystemFactory coordinateSystemFactory = new MgCoordinateSystemFactory();
            MgCoordinateSystem        srs        = coordinateSystemFactory.Create(mapWktSrs);
            MgMeasure                 srsMeasure = srs.GetMeasure();

            // Check for a buffer layer. If it exists, delete
            // the current features.
            // If it does not exist, create a feature source and
            // a layer to hold the buffer.

            BufferHelper helper      = new BufferHelper();
            MgdLayer     bufferLayer = null;
            int          layerIndex  = map.GetLayers().IndexOf("Buffer");

            if (layerIndex < 0)
            {
                // The layer does not exist and must be created.

                MgResourceIdentifier bufferFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//Buffer.FeatureSource");
                helper.CreateBufferFeatureSource(featureService, mapWktSrs, bufferFeatureResId);
                bufferLayer = helper.CreateBufferLayer(resourceService, bufferFeatureResId, sessionId);
                map.GetLayers().Insert(0, bufferLayer);
            }
            else
            {
                bufferLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex);
                bufferLayer.DeleteFeatures("ID like '%'");
            }

            // Check for a parcel marker layer. If it exists, delete
            // the current features.
            // If it does not exist, create a feature source and
            // a layer to hold the parcel markers.

            MgdLayer parcelMarkerLayer = null;

            layerIndex = map.GetLayers().IndexOf("ParcelMarker");
            if (layerIndex < 0)
            {
                MgResourceIdentifier parcelFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//ParcelMarker.FeatureSource");
                helper.CreateParcelMarkerFeatureSource(featureService, mapWktSrs, parcelFeatureResId);
                parcelMarkerLayer = helper.CreateParcelMarkerLayer(resourceService, parcelFeatureResId, sessionId);
                map.GetLayers().Insert(0, parcelMarkerLayer);
            }
            else
            {
                parcelMarkerLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex);
                parcelMarkerLayer.DeleteFeatures("ID like '%'");
            }

            // Check each layer in the selection.

            for (int i = 0; i < selectedLayers.GetCount(); i++)
            {
                // Only check selected features in the Parcels layer.

                MgdLayer layer = (MgdLayer)selectedLayers.GetItem(i);

                if (layer.GetName() == "Parcels")
                {
                    string geomName = layer.GetFeatureGeometryName();
                    System.Diagnostics.Trace.TraceInformation("Marking all parcels inside the buffer that are of type 'MFG'");

                    MgFeatureReader featureReader = selection.GetSelectedFeatures(layer, layer.GetFeatureClassName(), false);


                    // Process each item in the MgFeatureReader. Get the
                    // geometries from all the selected features and
                    // merge them into a single geometry.

                    MgGeometryCollection inputGeometries = new MgGeometryCollection();
                    while (featureReader.ReadNext())
                    {
                        MgByteReader featureGeometryData = featureReader.GetGeometry(geomName);
                        MgGeometry   featureGeometry     = agfReaderWriter.Read(featureGeometryData);

                        inputGeometries.Add(featureGeometry);
                    }

                    MgGeometryFactory geometryFactory  = new MgGeometryFactory();
                    MgGeometry        mergedGeometries = geometryFactory.CreateMultiGeometry(inputGeometries);

                    // Create a buffer from the merged geometries

                    double     bufferDist     = srs.ConvertMetersToCoordinateSystemUnits(bufferRingSize);
                    MgGeometry bufferGeometry = mergedGeometries.Buffer(bufferDist, srsMeasure);

                    // Create a filter to select parcels within the buffer. Combine
                    // a basic filter and a spatial filter to select all parcels
                    // within the buffer that are of type "MFG".

                    MgFeatureQueryOptions queryOptions = new MgFeatureQueryOptions();
                    queryOptions.SetFilter("RTYPE = 'MFG'");
                    queryOptions.SetSpatialFilter(geomName, bufferGeometry, MgFeatureSpatialOperations.Inside);

                    featureReader = layer.SelectFeatures(queryOptions);

                    // Get the features from the feature source,
                    // determine the centroid of each selected feature, and
                    // add a point to the ParcelMarker layer to mark the
                    // centroid.
                    // Collect all the points into an MgFeatureCommandCollection,
                    // so they can all be added in one operation.

                    MgFeatureCommandCollection parcelMarkerCommands = new MgFeatureCommandCollection();
                    int inserted = 0;
                    while (featureReader.ReadNext())
                    {
                        MgByteReader byteReader = featureReader.GetGeometry(geomName);
                        MgGeometry   geometry   = agfReaderWriter.Read(byteReader);
                        MgPoint      point      = geometry.GetCentroid();

                        // Create an insert command for this parcel.
                        MgPropertyCollection properties = new MgPropertyCollection();
                        properties.Add(new MgGeometryProperty("ParcelLocation", agfReaderWriter.Write(point)));
                        //parcelMarkerCommands.Add(new MgInsertFeatures("ParcelMarkerClass", properties));
                        MgFeatureReader fr = parcelMarkerLayer.InsertFeatures(properties);
                        fr.Close();
                        inserted++;
                    }
                    featureReader.Close();

                    if (inserted == 0)
                    {
                        MessageBox.Show("No parcels within the buffer area match.");
                        return;
                    }

                    // Create a feature in the buffer feature source to show the area covered by the buffer.

                    MgPropertyCollection props = new MgPropertyCollection();
                    props.Add(new MgGeometryProperty("BufferGeometry", agfReaderWriter.Write(bufferGeometry)));
                    bufferLayer.InsertFeatures(props);

                    // Ensure that the buffer layer is visible and in the legend.

                    bufferLayer.SetVisible(true);
                    bufferLayer.ForceRefresh();
                    bufferLayer.SetDisplayInLegend(true);
                    parcelMarkerLayer.SetVisible(true);
                    parcelMarkerLayer.ForceRefresh();

                    MessageBox.Show("Done");
                    _viewer.RefreshMap();
                    IMapLegend legend = Shell.Instance.Legend;
                    if (legend != null)
                    {
                        legend.RefreshLegend();
                    }
                }
            }
        }
Exemplo n.º 8
0
 public void LoadMap(MgMapViewerProvider provider)
 {
     mapViewer.Init(provider);
 }
Exemplo n.º 9
0
 /// <summary>
 /// Reloads the map viewer
 /// </summary>
 /// <param name="provider"></param>
 public void ReloadViewer(MgMapViewerProvider provider)
 {
     _provider = provider;
     mapViewer.Init(_provider);
 }
Exemplo n.º 10
0
        /// <summary>
        /// Initializes this map viewer and constructs the user interface based on the
        /// given AppLayout document
        /// </summary>
        /// <param name="layout"></param>
        /// <param name="provider"></param>
        public void Initialize(AppLayout layout, MgMapViewerProvider provider)
        {
            this.Text = layout.Title;

            if (!string.IsNullOrEmpty(layout.Language))
            {
                try
                {
                    var ci = CultureInfo.GetCultureInfo(layout.Language);
                    System.Threading.Thread.CurrentThread.CurrentUICulture
                          = System.Threading.Thread.CurrentThread.CurrentCulture
                          = ci;
                    SetLanguage(ci);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, Strings.SetLanguage);
                }
            }

            _menuInvoker = new MgMenuItemComponentInvoker();
            _toolInvoker = new MgToolButtonComponentInvoker();

            ValidateMapNames(layout);

            InitializeComponentSet(layout);
            InitializeMenu(layout.Menu);
            InitializeToolbar(layout.Toolbar);
            InitializeContextMenu(layout.ContextMenu);
            InitializeTaskPaneMenu(layout.TaskPane.TaskMenu);

            _layout = layout;
            if (!string.IsNullOrEmpty(_layout.Icon) && System.IO.File.Exists(_layout.Icon))
            {
                this.Icon = new System.Drawing.Icon(_layout.Icon);
            }

            SetInfoPaneWidth(_layout.InfoPane.Width);
            SetInfoPaneVisible(_layout.InfoPane.IsVisible);
            if (_layout.InfoPane.IsVisible)
            {
                SetLegendVisbility(_layout.InfoPane.Legend.Visible);
                legend.ShowTooltips = _layout.InfoPane.Legend.ShowTooltips;
                if (_layout.InfoPane.Legend.ThemeCompressionLimit.HasValue)
                {
                    legend.ThemeCompressionLimit = _layout.InfoPane.Legend.ThemeCompressionLimit.Value;
                }
                SetPropertyPaneVisbility(_layout.InfoPane.PropertyPane.Visible);
            }
            SetTaskPaneWidth(_layout.TaskPane.Width);
            if (!string.IsNullOrEmpty(_layout.TaskPane.InitialComponentID))
            {
                var cmp = GetComponent(_layout.TaskPane.InitialComponentID) as MgViewerComponent;
                if (cmp != null)
                {
                    taskPane.SetInitialComponent(cmp);
                }
                else
                {
                    MessageBox.Show(string.Format(Strings.WarnInitialTaskComponentNotFound, _layout.TaskPane.InitialComponentID));
                }
            }

            _provider = provider;
            mapViewer.PropertyChanged += new PropertyChangedEventHandler(OnMapViewerPropertyChanged);
        }
Exemplo n.º 11
0
 /// <summary>
 /// Reloads the map viewer
 /// </summary>
 /// <param name="provider"></param>
 public void ReloadViewer(MgMapViewerProvider provider)
 {
     _provider = provider;
     mapViewer.Init(_provider);
 }
Exemplo n.º 12
0
        private void btnCreatePointsOfInterest_Click(object sender, EventArgs e)
        {
            string layerName   = "Points";
            string legendLabel = "Points of Interest";
            string groupName   = "Analysis";

            MgMapViewerProvider provider        = _viewer.GetProvider();
            MgResourceService   resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);
            //We use MgdFeatureService instead of MgFeatureService as this sample demonstrates APIs unique to mg-desktop
            MgdFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService);

            MgMapBase              map    = _viewer.GetMap();
            MgLayerCollection      layers = map.GetLayers();
            MgLayerGroupCollection groups = map.GetLayerGroups();

            //NOTE: mg-desktop has no formal concept of a session repository, but we still
            //support session-based resources as a form of temporary resource (for the duration
            //of the application). Session ids in mg-desktop can be any arbitrary string
            string sessionId = Guid.NewGuid().ToString();

            if (layers.IndexOf(layerName) >= 0)
            {
                MessageBox.Show("Layer (" + layerName + ") already created");
                return;
            }

            //---------------------------------------------------//
            // Create a feature source with point data.
            // (The Sheboygan sample data does not contain such data,
            // so we"ll create it.)

            // Create a feature class definition for the new feature source
            MgClassDefinition classDefinition = new MgClassDefinition();

            classDefinition.SetName("Points");
            classDefinition.SetDescription("Feature class with point data.");
            classDefinition.SetDefaultGeometryPropertyName("GEOM");

            MgPropertyDefinitionCollection idProps  = classDefinition.GetIdentityProperties();
            MgPropertyDefinitionCollection clsProps = classDefinition.GetProperties();

            // Create an identify property
            MgDataPropertyDefinition identityProperty = new MgDataPropertyDefinition("KEY");

            identityProperty.SetDataType(MgPropertyType.Int32);
            identityProperty.SetAutoGeneration(true);
            identityProperty.SetReadOnly(true);
            // Add the identity property to the class definition
            clsProps.Add(identityProperty);
            idProps.Add(identityProperty);

            // Create a name property
            MgDataPropertyDefinition nameProperty = new MgDataPropertyDefinition("NAME");

            nameProperty.SetDataType(MgPropertyType.String);
            // Add the name property to the class definition
            clsProps.Add(nameProperty);

            // Create a geometry property
            MgGeometricPropertyDefinition geometryProperty = new MgGeometricPropertyDefinition("GEOM");

            geometryProperty.SetGeometryTypes(MgFeatureGeometricType.Point);
            // Add the geometry property to the class definition
            clsProps.Add(geometryProperty);

            // Create a feature schema
            MgFeatureSchema             featureSchema = new MgFeatureSchema("PointSchema", "Point schema");
            MgClassDefinitionCollection classes       = featureSchema.GetClasses();

            // Add the feature schema to the class definition
            classes.Add(classDefinition);

            // Create the feature source
            String featureSourceName = "Library://Samples/DevGuide/Data/points.FeatureSource";
            MgResourceIdentifier resourceIdentifier = new MgResourceIdentifier(featureSourceName);
            //wkt = "LOCALCS[\"*XY-MT*\",LOCAL_DATUM[\"*X-Y*\",10000],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]]";
            String wkt = "GEOGCS[\"LL84\",DATUM[\"WGS84\",SPHEROID[\"WGS84\",6378137.000,298.25722293]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.01745329251994]]";
            MgFileFeatureSourceParams sdfParams = new MgFileFeatureSourceParams("OSGeo.SDF", "LatLong", wkt, featureSchema);

            featureService.CreateFeatureSource(resourceIdentifier, sdfParams);

            // We need to add some data to the sdf before using it.  The spatial context
            // reader must have an extent.
            MgBatchPropertyCollection batchPropertyCollection = new MgBatchPropertyCollection();
            MgWktReaderWriter         wktReaderWriter         = new MgWktReaderWriter();
            MgAgfReaderWriter         agfReaderWriter         = new MgAgfReaderWriter();
            MgGeometryFactory         geometryFactory         = new MgGeometryFactory();

            // Make four points
            batchPropertyCollection.Add(MakePoint("Point A", -87.727, 43.748, wktReaderWriter, agfReaderWriter));

            batchPropertyCollection.Add(MakePoint("Point B", -87.728, 43.730, wktReaderWriter, agfReaderWriter));

            batchPropertyCollection.Add(MakePoint("Point C", -87.726, 43.750, wktReaderWriter, agfReaderWriter));

            batchPropertyCollection.Add(MakePoint("Point D", -87.728, 43.750, wktReaderWriter, agfReaderWriter));

            // Old way commented out

            /*
             * // Add the batch property collection to the feature source
             * MgInsertFeatures cmd = new MgInsertFeatures("Points", batchPropertyCollection);
             * MgFeatureCommandCollection featureCommandCollection = new MgFeatureCommandCollection();
             * featureCommandCollection.Add(cmd);
             *
             * // Execute the "add" commands
             * featureService.UpdateFeatures(resourceIdentifier, featureCommandCollection, false);
             */

            // Here's the mg-desktop way
            MgFeatureReader insertResult = featureService.InsertFeatures(resourceIdentifier, "Points", batchPropertyCollection);

            insertResult.Close();

            // ...
            //---------------------------------------------------//
            // Create a new layer

            LayerDefinitionFactory factory = new LayerDefinitionFactory();

            // Create a mark symbol
            String resourceId = "Library://Samples/Sheboygan/Symbols/BasicSymbols.SymbolLibrary";
            String symbolName = "PushPin";
            String width      = "24"; // unit = points
            String height     = "24"; // unit = points
            String color      = "FFFF0000";
            String markSymbol = factory.CreateMarkSymbol(resourceId, symbolName, width, height, color);

            // Create a text symbol
            String text            = "ID";
            String fontHeight      = "12";
            String foregroundColor = "FF000000";
            String textSymbol      = factory.CreateTextSymbol(text, fontHeight, foregroundColor);

            // Create a point rule.
            String ruleLegendLabel = "trees";
            String filter          = "";
            String pointRule       = factory.CreatePointRule(ruleLegendLabel, filter, textSymbol, markSymbol);

            // Create a point type style.
            String pointTypeStyle = factory.CreatePointTypeStyle(pointRule);

            // Create a scale range.
            String minScale        = "0";
            String maxScale        = "1000000000000";
            String pointScaleRange = factory.CreateScaleRange(minScale, maxScale, pointTypeStyle);

            // Create the layer definiton.
            String featureName     = "PointSchema:Points";
            String geometry        = "GEOM";
            String layerDefinition = factory.CreateLayerDefinition(featureSourceName, featureName, geometry, pointScaleRange);
            //---------------------------------------------------//
            // ...

            XmlDocument domDocument = new XmlDocument();

            domDocument.LoadXml(layerDefinition);

            //Add the layer to the map
            // TODO: Should probably validate this XML content
            using (MemoryStream ms = new MemoryStream())
            {
                domDocument.Save(ms);
                ms.Position = 0L;
                //Note we do this to ensure our XML content is free of any BOM characters
                byte[]   ldfBytes    = ms.ToArray();
                Encoding utf8        = Encoding.UTF8;
                String   layerDefStr = new String(utf8.GetChars(ldfBytes));
                ldfBytes = new byte[layerDefStr.Length - 1];
                int byteCount = utf8.GetBytes(layerDefStr, 1, layerDefStr.Length - 1, ldfBytes, 0);
                // Save the new layer definition to the session repository
                MgByteSource         byteSource = new MgByteSource(ldfBytes, ldfBytes.Length);
                MgResourceIdentifier resourceID = new MgResourceIdentifier("Session:" + sessionId + "//" + layerName + ".LayerDefinition");
                resourceService.SetResource(resourceID, byteSource.GetReader(), null);

                //Insert this layer to our map
                MgdLayer newLayer = new MgdLayer(resourceID, resourceService);
                newLayer.Name            = layerName;
                newLayer.LegendLabel     = legendLabel;
                newLayer.DisplayInLegend = true;
                newLayer.SetVisible(true);
                layers.Insert(0, newLayer);

                //Create analysis group if not already created
                if (groups.IndexOf(groupName) < 0)
                {
                    MgLayerGroup group = new MgLayerGroup(groupName);
                    group.LegendLabel     = groupName;
                    group.DisplayInLegend = true;
                    groups.Add(group);
                    newLayer.Group = group;
                }

                MessageBox.Show("Layer (" + layerName + ") created");
                _viewer.RefreshMap();
                IMapLegend legend = Shell.Instance.Legend;
                if (legend != null)
                {
                    legend.RefreshLegend();
                }
            }
        }
Exemplo n.º 13
0
        private void btnShowBuildings_Click(object sender, EventArgs e)
        {
            MgMapViewerProvider provider        = _viewer.GetProvider();
            MgResourceService   resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);

            string layerName   = "RecentlyBuilt";
            string legendLabel = "Built after 1980";
            string groupName   = "Analysis";

            MgMapBase              map    = _viewer.GetMap();
            MgLayerCollection      layers = map.GetLayers();
            MgLayerGroupCollection groups = map.GetLayerGroups();

            if (layers.IndexOf(layerName) >= 0)
            {
                MessageBox.Show("Layer (" + layerName + ") already created");
                return;
            }

            //NOTE: mg-desktop has no formal concept of a session repository, but we still
            //support session-based resources as a form of temporary resource (for the duration
            //of the application). Session ids in mg-desktop can be any arbitrary string
            string sessionId = Guid.NewGuid().ToString();

            XmlDocument domDocument = new XmlDocument();

            domDocument.LoadXml(Layers.RecentlyBuilt);

            // Get a list of all the <AreaRule><Filter> elements in
            // the XML.
            XmlNodeList nodes = domDocument.SelectNodes("//AreaRule/Filter");

            // Find the correct node and change it
            foreach (XmlNode node in nodes)
            {
                if (node.InnerText == "YRBUILT > 1950")
                {
                    node.InnerText = "YRBUILT > 1980";
                }
            }

            // Get a list of all the <LegendLabel> elements in the
            // XML.
            nodes = domDocument.SelectNodes("//LegendLabel");
            // Find the correct node and change it
            foreach (XmlNode node in nodes)
            {
                if (node.InnerText == "Built after 1950")
                {
                    node.InnerText = "Built after 1980";
                }
            }

            //Add the layer to the map
            // TODO: Should probably validate this XML content
            using (MemoryStream ms = new MemoryStream())
            {
                domDocument.Save(ms);
                ms.Position = 0L;
                //Note we do this to ensure our XML content is free of any BOM characters
                byte[]   layerDefinition = ms.ToArray();
                Encoding utf8            = Encoding.UTF8;
                String   layerDefStr     = new String(utf8.GetChars(layerDefinition));
                layerDefinition = new byte[layerDefStr.Length - 1];
                int byteCount = utf8.GetBytes(layerDefStr, 1, layerDefStr.Length - 1, layerDefinition, 0);
                // Save the new layer definition to the session repository
                MgByteSource         byteSource = new MgByteSource(layerDefinition, layerDefinition.Length);
                MgResourceIdentifier resourceID = new MgResourceIdentifier("Session:" + sessionId + "//" + layerName + ".LayerDefinition");
                resourceService.SetResource(resourceID, byteSource.GetReader(), null);

                //Insert this layer to our map
                MgdLayer newLayer = new MgdLayer(resourceID, resourceService);
                newLayer.Name            = layerName;
                newLayer.LegendLabel     = legendLabel;
                newLayer.DisplayInLegend = true;
                newLayer.SetVisible(true);
                layers.Insert(0, newLayer);

                //Create analysis group if not already created
                if (groups.IndexOf(groupName) < 0)
                {
                    MgLayerGroup group = new MgLayerGroup(groupName);
                    group.LegendLabel     = groupName;
                    group.DisplayInLegend = true;
                    groups.Add(group);
                    newLayer.Group = group;
                }

                //Turn off square footage if it exists
                if (layers.IndexOf("SquareFootage") >= 0)
                {
                    MgLayerBase layer = layers.GetItem("SquareFootage");
                    layer.SetVisible(false);
                }

                MessageBox.Show("Layer (" + layerName + ") created");
                _viewer.RefreshMap();
                IMapLegend legend = Shell.Instance.Legend;
                if (legend != null)
                {
                    legend.RefreshLegend();
                }
            }
        }
Exemplo n.º 14
0
        private void btnCreateHydroLine_Click(object sender, EventArgs e)
        {
            string layerName   = "Hydro";
            string legendLabel = "Hydro";
            string groupName   = "Analysis";

            MgMapViewerProvider provider        = _viewer.GetProvider();
            MgResourceService   resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);

            MgMapBase              map    = _viewer.GetMap();
            MgLayerCollection      layers = map.GetLayers();
            MgLayerGroupCollection groups = map.GetLayerGroups();

            //NOTE: mg-desktop has no formal concept of a session repository, but we still
            //support session-based resources as a form of temporary resource (for the duration
            //of the application). Session ids in mg-desktop can be any arbitrary string
            string sessionId = Guid.NewGuid().ToString();

            if (layers.IndexOf(layerName) >= 0)
            {
                MessageBox.Show("Layer (" + layerName + ") already created");
                return;
            }

            //---------------------------------------------------//
            // Create a new layer

            LayerDefinitionFactory factory = new LayerDefinitionFactory();

            // Create a line rule.
            String ruleLegendLabel = "";
            String filter          = "";
            String color           = "FF0000FF";
            String lineRule        = factory.CreateLineRule(ruleLegendLabel, filter, color);

            // Create a line type style.
            String lineTypeStyle = factory.CreateLineTypeStyle(lineRule);

            // Create a scale range.
            String minScale       = "0";
            String maxScale       = "1000000000000";
            String lineScaleRange = factory.CreateScaleRange(minScale, maxScale, lineTypeStyle);

            // Create the layer definiton.
            String featureClass    = "Library://Samples/Sheboygan/Data/HydrographicLines.FeatureSource";
            String featureName     = "SHP_Schema:HydrographicLines";
            String geometry        = "SHPGEOM";
            String layerDefinition = factory.CreateLayerDefinition(featureClass, featureName, geometry, lineScaleRange);

            //---------------------------------------------------//
            // ...

            XmlDocument domDocument = new XmlDocument();

            domDocument.LoadXml(layerDefinition);

            //Add the layer to the map
            // TODO: Should probably validate this XML content
            using (MemoryStream ms = new MemoryStream())
            {
                domDocument.Save(ms);
                ms.Position = 0L;
                //Note we do this to ensure our XML content is free of any BOM characters
                byte[]   ldfBytes    = ms.ToArray();
                Encoding utf8        = Encoding.UTF8;
                String   layerDefStr = new String(utf8.GetChars(ldfBytes));
                ldfBytes = new byte[layerDefStr.Length - 1];
                int byteCount = utf8.GetBytes(layerDefStr, 1, layerDefStr.Length - 1, ldfBytes, 0);
                // Save the new layer definition to the session repository
                MgByteSource         byteSource = new MgByteSource(ldfBytes, ldfBytes.Length);
                MgResourceIdentifier resourceID = new MgResourceIdentifier("Session:" + sessionId + "//" + layerName + ".LayerDefinition");
                resourceService.SetResource(resourceID, byteSource.GetReader(), null);

                //Insert this layer to our map
                MgdLayer newLayer = new MgdLayer(resourceID, resourceService);
                newLayer.Name            = layerName;
                newLayer.LegendLabel     = legendLabel;
                newLayer.DisplayInLegend = true;
                newLayer.SetVisible(true);
                layers.Insert(0, newLayer);

                //Create analysis group if not already created
                if (groups.IndexOf(groupName) < 0)
                {
                    MgLayerGroup group = new MgLayerGroup(groupName);
                    group.LegendLabel     = groupName;
                    group.DisplayInLegend = true;
                    groups.Add(group);
                    newLayer.Group = group;
                }

                MessageBox.Show("Layer (" + layerName + ") created");
                _viewer.RefreshMap();
                IMapLegend legend = Shell.Instance.Legend;
                if (legend != null)
                {
                    legend.RefreshLegend();
                }
            }
        }
Exemplo n.º 15
0
        private void CheckRedlineLayer()
        {
            if (_redlineLayer == null)
            {
                MgdMap map = (MgdMap)_viewer.GetMap();
                MgMapViewerProvider provider = _viewer.GetProvider();
                MgdFeatureService   featSvc  = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService);
                MgResourceService   resSvc   = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);

                string sessionId           = Guid.NewGuid().ToString();
                MgResourceIdentifier fsId  = new MgResourceIdentifier("Session:" + sessionId + "//Redline.FeatureSource");
                MgResourceIdentifier ldfId = new MgResourceIdentifier("Session:" + sessionId + "//Redline.LayerDefinition");
                string featureClass        = "Default:Redline";
                string geometry            = "Geometry";
                string xml = string.Format(Layers.Redline, fsId.ToString(), featureClass, geometry);

                //Construct our schema for the redline data store
                MgFeatureSchema   schema = new MgFeatureSchema("Default", "Redline schema");
                MgClassDefinition cls    = new MgClassDefinition();
                cls.Name = "Redline";

                MgDataPropertyDefinition id = new MgDataPropertyDefinition("ID");
                id.DataType = MgPropertyType.Int32;
                id.SetAutoGeneration(true);

                MgGeometricPropertyDefinition geom = new MgGeometricPropertyDefinition(geometry);
                geom.SpatialContextAssociation = "Default";
                geom.GeometryTypes             = MgFeatureGeometricType.Curve | MgFeatureGeometricType.Point | MgFeatureGeometricType.Solid | MgFeatureGeometricType.Surface;

                MgPropertyDefinitionCollection clsProps = cls.GetProperties();
                clsProps.Add(id);
                clsProps.Add(geom);

                MgPropertyDefinitionCollection idProps = cls.GetIdentityProperties();
                idProps.Add(id);

                cls.DefaultGeometryPropertyName = geometry;
                MgClassDefinitionCollection classes = schema.GetClasses();
                classes.Add(cls);

                //Create the feature source
                MgFileFeatureSourceParams create = new MgFileFeatureSourceParams("OSGeo.SDF", "Default", map.GetMapSRS(), schema);
                featSvc.CreateFeatureSource(fsId, create);

                //Then the layer definition
                byte[]       bytes  = Encoding.UTF8.GetBytes(xml);
                MgByteSource source = new MgByteSource(bytes, bytes.Length);
                resSvc.SetResource(ldfId, source.GetReader(), null);

                //Now create the runtime layer and add to map
                _redlineLayer                 = new MgdLayer(ldfId, resSvc);
                _redlineLayer.LegendLabel     = "Redlining";
                _redlineLayer.Name            = "Redline";
                _redlineLayer.Visible         = true;
                _redlineLayer.Selectable      = true;
                _redlineLayer.DisplayInLegend = true;

                MgLayerCollection layers = map.GetLayers();
                layers.Insert(0, _redlineLayer);
            }
        }