void DrawComplete(object sender, client.DrawEventArgs e)
        {
            // Deactivate the draw object for now.
            if (_drawObject != null)
            {
                _drawObject.IsEnabled     = false;
                _drawObject.DrawComplete -= DrawComplete;
                _mapWidget.Map.KeyDown   -= Map_KeyDown;
            }

            // Remove the cancelation toolbar
            _mapWidget.SetToolbar(null);

            // Get the tracked shape passed in as an argument.
            client.Geometry.Envelope env = e.Geometry as client.Geometry.Envelope;
            if (env != null)
            {
                _mapWidget.Map.Extent = env;

                if (isZoomout == false)
                {
                    // If zoom in, set the Map Extent to be the extent of the drawn geometry.
                    _mapWidget.Map.Extent = env;
                }
                else
                {
                    //Zoom out based on the shorter dimension of the drawm rectangle
                    double shorterRectangleDimension  = env.Height > env.Width ? env.Width : env.Height;
                    double selectedMapExtentDimension = shorterRectangleDimension == env.Width ? _mapWidget.Map.Extent.Width : _mapWidget.Map.Extent.Height;

                    _mapWidget.Map.Zoom(shorterRectangleDimension / selectedMapExtentDimension);
                }
            }
        }
Example #2
0
        /// <summary>
        /// Get items in frame and select them.
        /// </summary>
        private void _SelectInFrame()
        {
            Debug.Assert(SelectedItems != null);
            Debug.Assert(_selectionFrame != null);
            Debug.Assert(_clustering != null);

            ESRI.ArcGIS.Client.Geometry.Envelope frame = _selectionFrame.Geometry.Extent;

            if (Keyboard.Modifiers != ModifierKeys.Shift && Keyboard.Modifiers != ModifierKeys.Control)
            {
                SelectedItems.Clear();
            }

            for (int index = _objectLayers.Count - 1; index >= 0; index--)
            {
                ObjectLayer objectLayer = _objectLayers[index];
                if (objectLayer == _clustering.ClusteringLayer)
                {
                    continue;
                }

                if (objectLayer.Selectable && !objectLayer.SingleSelection)
                {
                    //Get elements in selection frame
                    List <object> elementsInFrame = _GetElementsInSelectionFrame(objectLayer, frame);
                    _ProcessSelectionChanges(elementsInFrame, objectLayer);
                }
            }
        }
Example #3
0
        public Mapper()
        {
            InitializeComponent();
            _map.IsLogoVisible         = false;
            this.scaleLine1.Visibility = System.Windows.Visibility.Visible;



            // extent (qq - think!)
            //var pt1 = MapUtil.ProjectPoint(new Point(0, -90));
            //var pt2 = MapUtil.ProjectPoint(new Point(360, 90));
            var pt1 = MapUtil.ProjectPoint(new Point(0, -40));
            var pt2 = MapUtil.ProjectPoint(new Point(360, 40));

            var extent = new ESRI.ArcGIS.Client.Geometry.Envelope(
                new ESRI.ArcGIS.Client.Geometry.MapPoint(pt1.X, pt1.Y),
                new ESRI.ArcGIS.Client.Geometry.MapPoint(pt2.X, pt2.Y));

            _map.Extent       = extent;
            _map.ZoomDuration = TimeSpan.Zero;//qqq

            _l1 = new ESRI.ArcGIS.Client.GraphicsLayer();
            this._map.Layers.Add(_l1);
            _l1.Initialize();//qq
            _l1.Visible = true;

            //this.legend1.LayerItems.Add(new ESRI.ArcGIS.Client.Toolkit.Primitives.LayerItemViewModel(_l1)); //qq

            this._map.Progress += new EventHandler <ESRI.ArcGIS.Client.ProgressEventArgs>(_map_Progress);

            //
            IsDirty = true;
        }
Example #4
0
        /// <summary>
        /// Get elements in frame.
        /// </summary>
        /// <param name="objectLayer">Layer to find elements.</param>
        /// <param name="frame">Frame.</param>
        /// <returns>Elements in frame.</returns>
        private List <object> _GetElementsInSelectionFrame(ObjectLayer objectLayer,
                                                           ESRI.ArcGIS.Client.Geometry.Envelope frame)
        {
            Debug.Assert(SelectedItems != null);
            Debug.Assert(_selectionFrame != null);
            Debug.Assert(_clustering != null);

            List <object> elementsInFrame = new List <object>();

            foreach (DataGraphicObject graphic in objectLayer.MapLayer.Graphics)
            {
                // Null extent in case of empty polyline.
                if (graphic.Geometry != null && graphic.Geometry.Extent != null &&
                    graphic.Data.GetType() == objectLayer.LayerType)
                {
                    // If graphic in frame, data type is equals to objectLayer data type and data contains in objectayercollection.
                    if (MapHelpers.IsIntersects(frame, graphic.Geometry) && graphic.Data.GetType() == objectLayer.LayerType &&
                        MapHelpers.CollectionContainsData(objectLayer.Collection, graphic.Data))
                    {
                        elementsInFrame.Add(graphic.Data);
                    }
                }
            }

            _clustering.AddElementsFromClusterAndNotInFrame(objectLayer, frame, elementsInFrame);

            return(elementsInFrame);
        }
Example #5
0
 private void setExtentText(ESRI.ArcGIS.Client.Geometry.Envelope newExtent)
 {
     ExtentTextBlock.Text = string.Format("MinX: {0}\nMinY: {1}\nMaxX: {2}\nMaxY: {3}",
                                          newExtent.XMin, newExtent.YMin, newExtent.XMax, newExtent.YMax);
     ExtentGrid.Visibility = Visibility.Visible;
     ExtentTextBox.Text    = string.Format("{0},{1},{2},{3}", newExtent.XMin.ToString("#0.000"), newExtent.YMin.ToString("#0.000"),
                                           newExtent.XMax.ToString("#0.000"), newExtent.YMax.ToString("#0.000"));
 }
Example #6
0
        public MainPage()
        {
            InitializeComponent();

            ESRI.ArcGIS.Client.Geometry.Envelope initialExtent =
                new ESRI.ArcGIS.Client.Geometry.Envelope(-13205480.536, 4077189.785, -13176602.592, 4090421.641);

            Map.Extent = initialExtent;
        }
        public MainPage()
        {
            InitializeComponent();

            ESRI.ArcGIS.Client.Geometry.Envelope initialExtent =
             new ESRI.ArcGIS.Client.Geometry.Envelope(-13205480.536, 4077189.785, -13176602.592, 4090421.641);

            MyMap.Extent = initialExtent;
        }
Example #8
0
        /// <summary>
        /// Get point-rectangle relative code by cohen-sutherland algorithm.
        /// </summary>
        /// <param name="rect">Rectangle.</param>
        /// <param name="point">Point.</param>
        /// <returns>Point-rectangle relative code.</returns>
        private static int _GetPointCode(ESRI.ArcGIS.Client.Geometry.Envelope rect, ESRI.ArcGIS.Client.Geometry.MapPoint point)
        {
            int code = 0;

            code += point.X < rect.XMin ? LEFT_CODE : 0;
            code += point.X > rect.XMax ? RIGHT_CODE : 0;
            code += point.Y < rect.YMin ? BOTTOM_CODE : 0;
            code += point.Y > rect.YMax ? TOP_CODE : 0;

            return(code);
        }
        /// <summary>
        /// Set map extent on point collection.
        /// </summary>
        /// <param name="mapCtrl">Map control.</param>
        /// <param name="points">Points collection.</param>
        public static void SetExtentOnCollection(MapControl mapCtrl, IList <ESRI.ArcLogistics.Geometry.Point> points)
        {
            ESRI.ArcLogistics.Geometry.Envelope?rect = GetCollectionExtent(points);

            if (rect.HasValue)
            {
                ESRI.ArcGIS.Client.Geometry.Envelope extent = GeometryHelper.CreateExtent(rect.Value,
                                                                                          mapCtrl.Map.SpatialReferenceID);
                mapCtrl.ZoomTo(extent);
            }
        }
Example #10
0
        }         // void pingsrv_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) {

        /// <summary>
        /// If layers in config: clear map.layers; attach mapprogress event; add layers from config to map;
        /// set extent; set selected layer
        /// </summary>
        /// <param name="cfg"></param>
        /// <param name="map"></param>
        /// <param name="lyrInitFail"></param>
        /// <param name="mapProgress"></param>
        public static VLayer loadMapCfg(string cfg, ESRI.ArcGIS.Client.Map map,
                                        EventHandler <EventArgs> lyrInitFail, EventHandler <ProgressEventArgs> mapProgress)
        {
            // if LayersList: clean map; add layers from LayersList to map
            ESRI.ArcGIS.Client.Geometry.Envelope ext = VRestore.mapExtentFromConfig(cfg);
            var layersList = VRestore.lyrsListFromConfig(cfg);

            if (layersList.Count <= 0)
            {
                throw new Exception("VRestore.loadMapCfg: список слоев пуст, видимо была сохранена пустая карта");
            }

            ESRI.ArcGIS.Client.LayerCollection lyrs = map.Layers;
            // clear map
            lyrs.Clear();
            VLayer sl = null;

            if (mapProgress != null && layersList.Count > 0)
            {
                map.Progress -= mapProgress;
                map.Progress += mapProgress;
            }

            // add layers to map
            foreach (var x in layersList)
            {
                //string.Format("loadMapCfg, add layer {0}", x.lyrUrl).clog();
                string.Format("VRestore.loadMapCfg, add layer '{0}' '{1}' '{2}'", x.ID, x.lyrName, x.lyrType).clog();
                if (lyrInitFail != null)
                {
                    x.lyr.InitializationFailed += new EventHandler <EventArgs>(lyrInitFail);
                }
                //x.lyr.SetValue(MapApplication.LayerNameProperty, x.lyrName);
                //x.lyr.Initialize();
                lyrs.Add(x.lyr);
                MapApplication.SetLayerName(x.lyr, x.lyrName);
                if (x.selected)
                {
                    sl = x;
                }
            }
            if (ext != null)
            {
                map.Extent = ext;
            }

            // select selected layer
            if (sl != null)
            {
                string.Format("VRestore.loadMapCfg, selected layer '{0}' '{1}'", sl.ID, sl.lyrName).clog();
                MapApplication.Current.SelectedLayer = sl.lyr;
            }
            return(sl);
        }         // public static VLayer loadMapCfg(string cfg, ESRI.ArcGIS.Client.Map map)
Example #11
0
        void drawObject_DrawComplete(object sender, DrawEventArgs e)
        {
            myDrawObject.IsEnabled = false;

            ESRI.ArcGIS.Client.Geometry.Envelope aoiEnvelope = e.Geometry as ESRI.ArcGIS.Client.Geometry.Envelope;

            string SOEurl = "http://sampleserver4.arcgisonline.com/ArcGIS/rest/services/Elevation/ESRI_Elevation_World/MapServer/exts/ElevationsSOE/ElevationLayers/1/GetElevationData?";

            SOEurl += string.Format(CultureInfo.InvariantCulture, "Extent={{\"xmin\" : {0}, \"ymin\" : {1}, \"xmax\" : {2}, \"ymax\" :{3},\"spatialReference\" : {{\"wkid\" : {4}}}}}&Rows={5}&Columns={6}&f=json",
                                    aoiEnvelope.XMin, aoiEnvelope.YMin, aoiEnvelope.XMax, aoiEnvelope.YMax,
                                    MyMap.SpatialReference.WKID, HeightTextBox.Text, WidthTextBox.Text);

            webClient.OpenReadAsync(new Uri(SOEurl), aoiEnvelope);
        }
        /// <summary>
        /// Zoom to candidate depends on locator type.
        /// </summary>
        /// <param name="mapCtrl">Map control.</param>
        /// <param name="addressCandidate">Candidate to zoom.</param>
        /// <param name="locatorType">Type of locator, which return this candidate.</param>
        private static void _ZoomToCandidate(MapControl mapCtrl, AddressCandidate addressCandidate, LocatorType locatorType)
        {
            Debug.Assert(mapCtrl != null);
            Debug.Assert(addressCandidate != null);

            double extentInc = 0;

            // Get extent size.
            switch (locatorType)
            {
            case LocatorType.CityState:
            {
                extentInc = ZOOM_ON_CITY_STATE_CANDIDATE;
                break;
            }

            case LocatorType.Zip:
            {
                extentInc = ZOOM_ON_ZIP_CANDIDATE;
                break;
            }

            case LocatorType.Street:
            {
                extentInc = ZOOM_ON_STREET_CANDIDATE;
                break;
            }

            default:
            {
                Debug.Assert(false);
                break;
            }
            }

            // Make extent rectangle.
            ESRI.ArcLogistics.Geometry.Envelope rect = new ESRI.ArcLogistics.Geometry.Envelope();
            rect.SetEmpty();
            rect.Union(addressCandidate.GeoLocation);

            rect.left   -= extentInc;
            rect.right  += extentInc;
            rect.top    += extentInc;
            rect.bottom -= extentInc;

            ESRI.ArcGIS.Client.Geometry.Envelope extent = GeometryHelper.CreateExtent(rect,
                                                                                      mapCtrl.Map.SpatialReferenceID);
            mapCtrl.ZoomTo(extent);
        }
Example #13
0
        public void SetExtent(double lonMin, double lonMax, double latMin, double latMax)
        {
            var pt1 = MapUtil.ProjectPoint(new Point(lonMin, latMin));
            var pt2 = MapUtil.ProjectPoint(new Point(lonMax, latMax));

            var extent = new ESRI.ArcGIS.Client.Geometry.Envelope(
                new ESRI.ArcGIS.Client.Geometry.MapPoint(pt1.X, pt1.Y),
                new ESRI.ArcGIS.Client.Geometry.MapPoint(pt2.X, pt2.Y));

            if (_map.Extent != extent) // qq??
            {
                _progress   = -1;      //qqq
                _map.Extent = extent;
                IsDirty     = true;
            }
        }
Example #14
0
        }         // private List<VLayer> lyrsListFromConfig(string cfg)

        public static ESRI.ArcGIS.Client.Geometry.Envelope mapExtentFromConfig(string cfg)
        {
            ESRI.ArcGIS.Client.Geometry.Envelope res = null;
            var ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(cfg));
            var js = JsonObject.Load(ms);

            // "MapExtent":{"xmin":14863613.810013881,"xmax":7260708.5358984508,"ymin":6355694.1210022084,"ymax":7260708.5358984508,"sridWKID":102100}
            if (js.ContainsKey("MapExtent"))
            {
                var jsExt = js["MapExtent"];
                res = new ESRI.ArcGIS.Client.Geometry.Envelope(
                    x1: jsExt["xmin"],
                    y1: jsExt["ymin"],
                    x2: jsExt["xmax"],
                    y2: jsExt["ymax"]
                    );
                res.SpatialReference = new ESRI.ArcGIS.Client.Geometry.SpatialReference(WKID: jsExt["sridWKID"]);
                //res.SpatialReference = new ESRI.ArcGIS.Client.Geometry.SpatialReference(wkt : jsExt["sridWKT"]);
            }
            return(res);
        }         // public static ESRI.ArcGIS.Client.Geometry.Envelope mapExtentFromConfig(string cfg)
        private void QueryTask_ExecuteCompleted(object sender, ESRI.ArcGIS.Client.Tasks.QueryEventArgs args)
        {
            FeatureSet featureSet = args.FeatureSet;

            // If initial query to populate states combo box
            if ((args.UserState as string) == "initial")
            {
                // Just show on initial load
                QueryComboBox.Items.Add("Select...");

                foreach (Graphic graphic in args.FeatureSet.Features)
                {
                    QueryComboBox.Items.Add(graphic.Attributes["STATE_NAME"].ToString());
                }

                QueryComboBox.SelectedIndex = 0;
                return;
            }

            // Remove the first entry if "Select..."
            if (QueryComboBox.Items[0].ToString().Contains("Select..."))
                QueryComboBox.Items.RemoveAt(0);

            // If an item has been selected
            GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer;
            graphicsLayer.Graphics.Clear();

            if (featureSet != null && featureSet.Features.Count > 0)
            {
                // Show selected feature attributes in DataGrid
                Graphic selectedFeature = featureSet.Features[0];

                QueryDetailsDataGrid.ItemsSource = selectedFeature.Attributes;

                // Highlight selected feature
                selectedFeature.Symbol = LayoutRoot.Resources["DefaultFillSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol;
                graphicsLayer.Graphics.Add(selectedFeature);

                // Zoom to selected feature (define expand percentage)
                ESRI.ArcGIS.Client.Geometry.Envelope selectedFeatureExtent = selectedFeature.Geometry.Extent;

                double expandPercentage = 30;

                double widthExpand = selectedFeatureExtent.Width * (expandPercentage / 100);
                double heightExpand = selectedFeatureExtent.Height * (expandPercentage / 100);

                ESRI.ArcGIS.Client.Geometry.Envelope displayExtent = new ESRI.ArcGIS.Client.Geometry.Envelope(
                selectedFeatureExtent.XMin - (widthExpand / 2),
                selectedFeatureExtent.YMin - (heightExpand / 2),
                selectedFeatureExtent.XMax + (widthExpand / 2),
                selectedFeatureExtent.YMax + (heightExpand / 2));

                MyMap.ZoomTo(displayExtent);

                // If DataGrid not visible (initial load), show it
                if (DataGridScrollViewer.Visibility == Visibility.Collapsed)
                {
                    DataGridScrollViewer.Visibility = Visibility.Visible;
                    QueryGrid.Height = Double.NaN;
                    QueryGrid.UpdateLayout();
                }
            }
            else
            {
                QueryDetailsDataGrid.ItemsSource = null;
                DataGridScrollViewer.Visibility = Visibility.Collapsed;
                QueryGrid.Height = Double.NaN;
                QueryGrid.UpdateLayout();
            }
        }
Example #16
0
        protected void ChoroplethProperties_RenderMap(ChoroplethLayerProvider provider)
        {
            dynamic layerPropertiesControl = this;

            EpiDashboard.Controls.ChoroplethProperties choroplethprop = new Controls.ChoroplethProperties(mapControl as StandaloneMapControl, myMap);

            if (provider is ChoroplethShapeLayerProvider)
            {
                choroplethprop.txtShapePath.Text = boundryFilePath;
            }
            else if (provider is ChoroplethKmlLayerProvider)
            {
                choroplethprop.txtKMLpath.Text = boundryFilePath;
            }
            else if (provider is ChoroplethServerLayerProvider)
            {
                choroplethprop.txtMapSeverpath.Text = boundryFilePath;
            }
            choroplethprop.LayerProvider       = provider;
            choroplethprop.txtProjectPath.Text = dashboardHelper.Database.DataSource;
            choroplethprop.SetDashboardHelper(dashboardHelper);
            choroplethprop.cmbClasses.Text = layerPropertiesControl.cbxClasses.Text;

            foreach (string str in layerPropertiesControl.cbxShapeKey.Items)
            {
                choroplethprop.cmbShapeKey.Items.Add(str);
            }

            foreach (string str in layerPropertiesControl.cbxDataKey.Items)
            {
                choroplethprop.cmbDataKey.Items.Add(str);
            }

            foreach (string str in layerPropertiesControl.cbxValue.Items)
            {
                choroplethprop.cmbValue.Items.Add(str);
            }

            choroplethprop.cmbShapeKey.SelectedItem = layerPropertiesControl.cbxShapeKey.Text;
            choroplethprop.cmbDataKey.SelectedItem  = layerPropertiesControl.cbxDataKey.Text;

            choroplethprop.cmbValue.SelectionChanged -= new System.Windows.Controls.SelectionChangedEventHandler(choroplethprop.cmbValue_SelectionChanged);
            choroplethprop.cmbValue.SelectedItem      = layerPropertiesControl.cbxValue.Text;
            choroplethprop.cmbValue.SelectionChanged += new System.Windows.Controls.SelectionChangedEventHandler(choroplethprop.cmbValue_SelectionChanged);

            choroplethprop.rctHighColor.Fill    = layerPropertiesControl.rctHighColor.Fill;
            choroplethprop.rctLowColor.Fill     = layerPropertiesControl.rctLowColor.Fill;
            choroplethprop.rctMissingColor.Fill = layerPropertiesControl.rctMissingColor.Fill;

            if (provider is ChoroplethShapeLayerProvider)
            {
                choroplethprop.radShapeFile.IsChecked       = true;
                choroplethprop.choroplethShapeLayerProvider = (ChoroplethShapeLayerProvider)provider;
            }
            else if (provider is ChoroplethKmlLayerProvider)
            {
                choroplethprop.radKML.IsChecked           = true;
                choroplethprop.choroplethKmlLayerProvider = (ChoroplethKmlLayerProvider)provider;
            }
            else if (provider is ChoroplethServerLayerProvider)
            {
                choroplethprop.radMapServer.IsChecked        = true;
                choroplethprop.choroplethServerLayerProvider = (ChoroplethServerLayerProvider)provider;
            }

            choroplethprop.legTitle.Text            = provider.LegendText;
            choroplethprop.showPolyLabels.IsChecked = provider.ShowPolyLabels;
            choroplethprop.ListLegendText           = provider.ListLegendText;

            choroplethprop.SetProperties();

            if (provider._resolution != 0)
            {
                choroplethprop.RenderMap();
            }

            {
                if (provider._mapIsNew)
                {
                    // Define extent from map7 file
                    ESRI.ArcGIS.Client.Geometry.Envelope myExtent = new ESRI.ArcGIS.Client.Geometry.Envelope(provider._envMinX, provider._envMinY, provider._envMaxX, provider._envMaxY);

                    // Zoom to location
                    provider.ArcGIS_Map.ZoomTo(myExtent);
                }
            }
        }
Example #17
0
        private void ParcelMap_MouseMove(object sender, MouseEventArgs e)
        {
            if (ParcelLineInfoWindow.IsOpen == true &&
                ParcelLineInfoWindow.Visibility == System.Windows.Visibility.Visible)
            {
                const double hideDistance = 25;
                double       width        = ParcelLineInfoWindow.ActualWidth;
                double       height       = ParcelLineInfoWindow.ActualHeight;

                var    anchorScreenPoint = ParcelMap.MapToScreen(ParcelLineInfoWindow.Anchor);
                double x1       = anchorScreenPoint.X - width / 2 - hideDistance;
                double y1       = anchorScreenPoint.Y - height - hideDistance - 10; // -ve for info indicator
                double x2       = anchorScreenPoint.X + width / 2 + hideDistance;
                double y2       = anchorScreenPoint.Y + hideDistance;
                var    envelope = new ESRI.ArcGIS.Client.Geometry.Envelope(x1, y1, x2, y2);

                Point pointLoc = e.GetPosition(this);
                if (!envelope.Intersects(new ESRI.ArcGIS.Client.Geometry.Envelope(pointLoc.X, pointLoc.Y, pointLoc.X, pointLoc.Y)))
                {
                    ParcelLineInfoWindow.IsOpen = false;
                    ParcelMap.Focus(); // Cause any non-committed cell in the popup window to lose its focus. This will commit the cell.
                }
            }

            if ((_srPoint == null) || !PDE_Tools.IsExpanded)
            {
                return;
            }

            ParcelData parcelData = ParcelGridContainer.DataContext as ParcelData;

            ESRI.ArcGIS.Client.Geometry.MapPoint currentPoint = ParcelMap.ScreenToMap(e.GetPosition(this));

            if (RotationButton.IsChecked == true)
            {
                double rotation = GeometryUtil.Angle(_srPoint, currentPoint, _originPoint) + _oldRotation;
                while (rotation < -Math.PI)
                {
                    rotation += Math.PI * 2;
                }
                while (rotation > Math.PI)
                {
                    rotation -= Math.PI * 2;
                }

                parcelData.RotationValue = rotation;
            }
            else if (ScaleButton.IsChecked == true)
            {
                parcelData.ScaleValue = GeometryUtil.Scale(_srPoint, currentPoint, _originPoint) * _oldScale;
            }

            // If we have a snap point, adjust scale/rotation if we can snap point.
            if (_srSnapPointId != -1)
            {
                bool isRotating = RotationButton.IsChecked.GetValueOrDefault(false);
                bool isScaling  = ScaleButton.IsChecked.GetValueOrDefault(false);

                double distanceToPoint = _srDistanceToPoint * parcelData.ScaleValue;
                double bearingToPoint  = _srBearingToPoint - parcelData.RotationValue;
                if (bearingToPoint >= 2 * Math.PI)
                {
                    bearingToPoint -= 2 * Math.PI;
                }

                ESRI.ArcGIS.Client.Geometry.MapPoint snapPointSR = GeometryUtil.ConstructPoint(_originPoint, bearingToPoint, distanceToPoint);
                if (snapPointSR != null)
                {
                    ESRI.ArcGIS.Client.Geometry.Polyline snapLine;
                    SnapPointToCacheObjects(snapPointSR, isScaling, out snapLine); // if scaling, skip zero distance so
                    if (snapLine != null)                                          // we don't snap to origin point.
                    {
                        bool ok = false;
                        ESRI.ArcGIS.Client.Geometry.MapPoint intersectPoint = null;
                        if (isRotating)
                        {
                            ok = GeometryUtil.ConstructPointLineCurveIntersection(snapLine, _originPoint, bearingToPoint, distanceToPoint, out intersectPoint); // distanceToPoint is radius here
                            if (ok)                                                                                                                             // Only snap if the mouse location is within snap solution
                            {
                                ok = GeometryUtil.LineLength(intersectPoint, currentPoint) <= _xmlConfiguation.SnapTolerance;
                            }
                            if (ok)
                            {
                                parcelData.RotationValue = GeometryUtil.Angle(_srSnapPoint, intersectPoint, _originPoint);
                            }
                        }
                        else if (isScaling)
                        {
                            ESRI.ArcGIS.Client.Geometry.MapPoint endPoint   = GeometryUtil.ConstructPoint(_originPoint, bearingToPoint, distanceToPoint + _xmlConfiguation.SnapTolerance);
                            ESRI.ArcGIS.Client.Geometry.Polyline sourceLine = GeometryUtil.Line(_originPoint, endPoint);
                            ok = GeometryUtil.ConstructPointLineLineIntersection(snapLine, sourceLine, out intersectPoint);
                            if (ok) // Only snap if the mouse location is within snap solution
                            {
                                ok = GeometryUtil.LineLength(intersectPoint, currentPoint) <= _xmlConfiguation.SnapTolerance;
                            }
                            if (ok)
                            {
                                double scale = GeometryUtil.Scale(_srSnapPoint, intersectPoint, _originPoint);
                                if (scale > 0.0)
                                {
                                    parcelData.ScaleValue = scale;
                                }
                            }
                        }

                        // Test code for debugging.
                        //
                        //GraphicsLayer testGraphicsLayer = ParcelMap.Layers["TestGraphicLayer"] as GraphicsLayer;
                        //testGraphicsLayer.ClearGraphics();
                        //if (intersectPoint != null)
                        //{
                        //  ESRI.ArcGIS.Client.Graphic graphic = new ESRI.ArcGIS.Client.Graphic()
                        //  {
                        //    Geometry = intersectPoint,
                        //    Symbol = LayoutRoot.Resources["TestMarkerSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol
                        //  };
                        //  testGraphicsLayer.Graphics.Add(graphic);
                        //}
                    }
                }
            }

            // Only redraw if there have been an update;
            // Otherwise runtime does not process mouse up and over flashes.
            if ((parcelData.ScaleValue != _moveScale) || (parcelData.RotationValue != _moveRotation))
            {
                CalculateAndAddLineGraphics();
                _moveScale    = parcelData.ScaleValue;
                _moveRotation = parcelData.RotationValue;
            }
        }
Example #18
0
        private void ParcelMap_MouseMove(object sender, MouseEventArgs e)
        {
            if (ParcelLineInfoWindow.IsOpen == true &&
              ParcelLineInfoWindow.Visibility == System.Windows.Visibility.Visible)
              {
            const double hideDistance = 25;
            double width = ParcelLineInfoWindow.ActualWidth;
            double height = ParcelLineInfoWindow.ActualHeight;

            var anchorScreenPoint = ParcelMap.MapToScreen(ParcelLineInfoWindow.Anchor);
            double x1 = anchorScreenPoint.X - width/2 - hideDistance;
            double y1 = anchorScreenPoint.Y - height - hideDistance - 10; // -ve for info indicator
            double x2 = anchorScreenPoint.X + width/2 + hideDistance;
            double y2 = anchorScreenPoint.Y + hideDistance;
            var envelope = new ESRI.ArcGIS.Client.Geometry.Envelope(x1, y1, x2, y2);

            Point pointLoc = e.GetPosition(this);
            if (!envelope.Intersects(new ESRI.ArcGIS.Client.Geometry.Envelope(pointLoc.X, pointLoc.Y, pointLoc.X, pointLoc.Y)))
            {
              ParcelLineInfoWindow.IsOpen = false;
              ParcelMap.Focus();  // Cause any non-committed cell in the popup window to lose its focus. This will commit the cell.

            }
              }

              if ((_srPoint == null) || !PDE_Tools.IsExpanded)
            return;

              ParcelData parcelData = ParcelGridContainer.DataContext as ParcelData;

              ESRI.ArcGIS.Client.Geometry.MapPoint currentPoint = ParcelMap.ScreenToMap(e.GetPosition(this));

              if (RotationButton.IsChecked == true)
              {
            double rotation = GeometryUtil.Angle(_srPoint, currentPoint, _originPoint) + _oldRotation;
            while (rotation < -Math.PI)
              rotation += Math.PI * 2;
            while (rotation > Math.PI)
              rotation -= Math.PI * 2;

            parcelData.RotationValue = rotation;
              }
              else if (ScaleButton.IsChecked == true)
              {
            parcelData.ScaleValue = GeometryUtil.Scale(_srPoint, currentPoint, _originPoint) * _oldScale;
              }

              // If we have a snap point, adjust scale/rotation if we can snap point.
              if (_srSnapPointId != -1)
              {
            bool isRotating = RotationButton.IsChecked.GetValueOrDefault(false);
            bool isScaling = ScaleButton.IsChecked.GetValueOrDefault(false);

            double distanceToPoint = _srDistanceToPoint * parcelData.ScaleValue;
            double bearingToPoint = _srBearingToPoint - parcelData.RotationValue;
            if (bearingToPoint >= 2 * Math.PI)
              bearingToPoint -= 2 * Math.PI;

            ESRI.ArcGIS.Client.Geometry.MapPoint snapPointSR = GeometryUtil.ConstructPoint(_originPoint, bearingToPoint, distanceToPoint);
            if (snapPointSR != null)
            {
              ESRI.ArcGIS.Client.Geometry.Polyline snapLine;
              SnapPointToCacheObjects(snapPointSR, isScaling, out snapLine);  // if scaling, skip zero distance so
              if (snapLine != null)                                           // we don't snap to origin point.
              {
            bool ok = false;
            ESRI.ArcGIS.Client.Geometry.MapPoint intersectPoint = null;
            if (isRotating)
            {
              ok = GeometryUtil.ConstructPointLineCurveIntersection(snapLine, _originPoint, bearingToPoint, distanceToPoint, out intersectPoint);  // distanceToPoint is radius here
              if (ok) // Only snap if the mouse location is within snap solution
                ok = GeometryUtil.LineLength(intersectPoint, currentPoint) <= _xmlConfiguation.SnapTolerance;
              if (ok)
                parcelData.RotationValue = GeometryUtil.Angle(_srSnapPoint, intersectPoint, _originPoint);
            }
            else if (isScaling)
            {
              ESRI.ArcGIS.Client.Geometry.MapPoint endPoint = GeometryUtil.ConstructPoint(_originPoint, bearingToPoint, distanceToPoint + _xmlConfiguation.SnapTolerance);
              ESRI.ArcGIS.Client.Geometry.Polyline sourceLine = GeometryUtil.Line(_originPoint, endPoint);
              ok = GeometryUtil.ConstructPointLineLineIntersection(snapLine, sourceLine, out intersectPoint);
              if (ok) // Only snap if the mouse location is within snap solution
                ok = GeometryUtil.LineLength(intersectPoint, currentPoint) <= _xmlConfiguation.SnapTolerance;
              if (ok)
              {
                double scale = GeometryUtil.Scale(_srSnapPoint, intersectPoint, _originPoint);
                if (scale > 0.0)
                  parcelData.ScaleValue = scale;
              }
            }

            // Test code for debugging.
            //
            //GraphicsLayer testGraphicsLayer = ParcelMap.Layers["TestGraphicLayer"] as GraphicsLayer;
            //testGraphicsLayer.ClearGraphics();
            //if (intersectPoint != null)
            //{
            //  ESRI.ArcGIS.Client.Graphic graphic = new ESRI.ArcGIS.Client.Graphic()
            //  {
            //    Geometry = intersectPoint,
            //    Symbol = LayoutRoot.Resources["TestMarkerSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol
            //  };
            //  testGraphicsLayer.Graphics.Add(graphic);
            //}
              }
            }
              }

              // Only redraw if there have been an update;
              // Otherwise runtime does not process mouse up and over flashes.
              if ((parcelData.ScaleValue != _moveScale) || (parcelData.RotationValue != _moveRotation))
              {
            CalculateAndAddLineGraphics();
            _moveScale = parcelData.ScaleValue;
            _moveRotation = parcelData.RotationValue;
              }
        }
 private void ControlsBasicsWindow_Loaded(object sender, RoutedEventArgs e)
 {
     initialResolution = MyMap.Resolution;
     initialExtent     = MyMap.Extent;
     currentExtent     = MyMap.Extent;
 }
        private void QueryTask_ExecuteCompleted(object sender, ESRI.ArcGIS.Client.Tasks.QueryEventArgs args)
        {
            FeatureSet featureSet = args.FeatureSet;

            // If initial query to populate states list box
            if ((args.UserState as string) == "initial")
            {
                // Just show on initial load
                QueryListBox.Items.Add("Select...");

                foreach (Graphic graphic in args.FeatureSet.Features)
                {
                    QueryListBox.Items.Add(graphic.Attributes["STATE_NAME"].ToString());
                }

                QueryListBox.SelectedIndex = 0;
                return;
            }

            // Remove the first entry if "Select..."
            if (QueryListBox.Items[0].ToString().Contains("Select..."))
                QueryListBox.Items.RemoveAt(0);

            // If an item has been selected
            GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer;
            graphicsLayer.ClearGraphics();

            if (featureSet != null && featureSet.Features.Count > 0)
            {
                // Show selected feature attributes in DataGrid
                Graphic selectedFeature = featureSet.Features[0];

                ResultsListBox.Items.Clear();
                //QueryDetailsDataGrid.ItemsSource = selectedFeature.Attributes;
                foreach (KeyValuePair<string, object> pair in selectedFeature.Attributes)
                {
                    TextBlock tb1 = new TextBlock()
                    {
                        FontSize = 30,
                        FontWeight = FontWeights.Bold,
                        Text = string.Format("{0}: ", pair.Key)
                    };
                    TextBlock tb2 = new TextBlock()
                    {
                        FontSize = 30,
                        Text = string.Format(" {0}", pair.Value)
                    };
                    StackPanel sp = new StackPanel() { Orientation = System.Windows.Controls.Orientation.Vertical };
                    sp.Children.Add(tb1);
                    sp.Children.Add(tb2);
                    ListBoxItem item = new ListBoxItem();
                    item.Content = sp;
                    ResultsListBox.Items.Add(item);
                }

                // Highlight selected feature
                selectedFeature.Symbol = DefaultFillSymbol;
                graphicsLayer.Graphics.Add(selectedFeature);

                // Zoom to selected feature (define expand percentage)
                ESRI.ArcGIS.Client.Geometry.Envelope selectedFeatureExtent = selectedFeature.Geometry.Extent;

                double expandPercentage = 30;

                double widthExpand = selectedFeatureExtent.Width * (expandPercentage / 100);
                double heightExpand = selectedFeatureExtent.Height * (expandPercentage / 100);

                ESRI.ArcGIS.Client.Geometry.Envelope displayExtent = new ESRI.ArcGIS.Client.Geometry.Envelope(
                selectedFeatureExtent.XMin - (widthExpand / 2),
                selectedFeatureExtent.YMin - (heightExpand / 2),
                selectedFeatureExtent.XMax + (widthExpand / 2),
                selectedFeatureExtent.YMax + (heightExpand / 2));

                MyMap.ZoomTo(displayExtent);

                // If DataGrid not visible (initial load), show it
                if (ResultsListBox.Visibility == Visibility.Collapsed)
                {
                    ResultsListBox.Visibility = Visibility.Visible;
                    QueryGrid.Height = Double.NaN;
                    QueryGrid.UpdateLayout();
                }
            }
            else
            {
                //QueryDetailsDataGrid.ItemsSource = null;
                ResultsListBox.Visibility = Visibility.Collapsed;
                QueryGrid.Height = Double.NaN;
                QueryGrid.UpdateLayout();
            }
        }
Example #21
0
        /// <summary>
        /// Is line intersects with extent.
        /// Implementation of Cohen-Sutherland algorithm.
        /// </summary>
        /// <param name="extent">Extent.</param>
        /// <param name="startPoint">Line start.</param>
        /// <param name="endPoint">Line end.</param>
        /// <returns>Is line intersects with extent.</returns>
        public static bool _IsLineIntersectsWithRect(Envelope extent, Point startPoint, Point endPoint)
        {
            ESRI.ArcGIS.Client.Geometry.MapPoint start = new ESRI.ArcGIS.Client.Geometry.MapPoint(startPoint.X, startPoint.Y);
            ESRI.ArcGIS.Client.Geometry.MapPoint end = new ESRI.ArcGIS.Client.Geometry.MapPoint(endPoint.X, endPoint.Y);

            ESRI.ArcGIS.Client.Geometry.Envelope rect = new ESRI.ArcGIS.Client.Geometry.Envelope(
                extent.left, extent.top, extent.right, extent.bottom);

            int code_a, code_b, code;
            ESRI.ArcGIS.Client.Geometry.MapPoint temp;

            code_a = _GetPointCode(rect, start);
            code_b = _GetPointCode(rect, end);

            while (code_a > 0 || code_b > 0)
            {
                // If both points on one side, than line does not intersects extent.
                if ((code_a & code_b) > 0)
                    return false;

                if (code_a > 0)
                {
                    code = code_a;
                    temp = start;
                }
                else
                {
                    code = code_b;
                    temp = end;
                }

                if ((code & LEFT_CODE) > 0)
                {
                    temp.Y = temp.Y + (start.Y - end.Y) * (rect.XMin - temp.X) / (start.X - end.X);
                    temp.X = rect.XMin;
                }
                else if ((code & RIGHT_CODE) > 0)
                {
                    temp.Y += (start.Y - end.Y) * (rect.XMax - temp.X) / (start.X - end.X);
                    temp.X = rect.XMax;
                }

                if ((code & BOTTOM_CODE) > 0)
                {
                    temp.X += (start.X - end.X) * (rect.YMin - temp.Y) / (start.Y - end.Y);
                    temp.Y = rect.YMin;
                }
                else if ((code & TOP_CODE) > 0)
                {
                    temp.X += (start.X - end.X) * (rect.YMax - temp.Y) / (start.Y - end.Y);
                    temp.Y = rect.YMax;
                }

                if (code == code_a)
                    code_a = _GetPointCode(rect, start);
                else
                    code_b = _GetPointCode(rect, end);
            }

            return true;
        }
        void reader_MultiSourceFrameArrived(object sender, MultiSourceFrameArrivedEventArgs e)
        {
            // Get a reference to the multi-frame
            var reference = e.FrameReference.AcquireFrame();

            // Open color frame
            using (var frame = reference.ColorFrameReference.AcquireFrame())
            {
                if (frame != null)
                {
                    ColorImage.Source = ToBitmap(frame);
                }
            }

            // Open depth frame
            using (var frame = reference.DepthFrameReference.AcquireFrame())
            {
                if (frame != null)
                {
                    // Do something with the frame...
                }
            }

            // Open body frame
            using (var frame = reference.BodyFrameReference.AcquireFrame())
            {
                if (frame != null)
                {
                    bodies = new Body[frame.BodyCount];
                    frame.GetAndRefreshBodyData(bodies);
                }

                Body trackedBody = FirstTrackedBody(bodies);
                currentBodies.Add(trackedBody);

                // Animation stuff - Implement this later
                if (trackedBody == null)
                {
                    // Implement this later
                }

                else
                {
                    // Implement this later
                    ableToControl = true;
                }


                // COntrol of map Implementation

                if (ableToControl == true)
                {
                    if (handPointer == null || handPointer.Properties.BodyTrackingId != trackedBody.TrackingId)
                    {
                        return;
                    }

                    JointType currentHand = 0;

                    try
                    {
                        if (handPointer.Properties.HandType == HandType.LEFT)
                        {
                            currentHand = JointType.HandLeft;
                        }
                        else if (handPointer.Properties.HandType == HandType.RIGHT)
                        {
                            currentHand = JointType.HandRight;
                        }
                    }
                    catch (Exception ex1)
                    {
                    }

                    // And FINALLY perform the action on the map
                    if (handPointer != null && trackedBody.Joints.Where(j => j.Key == currentHand).FirstOrDefault().Value.TrackingState == TrackingState.Tracked)
                    {
                        ESRI.ArcGIS.Client.Geometry.Envelope newEx = new ESRI.ArcGIS.Client.Geometry.Envelope();

                        /*newEx = MyMap.Extent;
                        *  if (MyMap.Extent.YMax >= 88)
                        *  {
                        *   newEx.YMax = 85;
                        *   newEx.YMin = MyMap.Extent.YMin + 1;
                        *   newEx.XMax = MyMap.Extent.XMax;
                        *   newEx.XMin = MyMap.Extent.XMin;
                        *  }
                        *  else if (MyMap.Extent.YMin <= -88)
                        *  {
                        *   newEx.YMin = -85;
                        *   newEx.YMax = MyMap.Extent.YMax - 1;
                        *   newEx.XMin = MyMap.Extent.XMin;
                        *   newEx.XMax = MyMap.Extent.XMax;
                        *  }
                        *  MyMap.Extent = newEx;*/

                        // Track the right amount of tracked data

                        /* if (actions.Count > 11)
                         *   actions.RemoveAt(0);
                         *
                         * if (zooms.Count > 10)
                         *   zooms.RemoveAt(0);
                         *
                         * if (handPointerX.Count > 3 && handPointerY.Count > 3)
                         * {
                         *   handPointerX.RemoveAt(0);
                         *   handPointerY.RemoveAt(0);
                         * }
                         */
                        MoveTheMapPointer(handPointer, 5, trackedBody);
                    }
                }
            }
        }
Example #23
0
        protected override void StartButtonClicked(object parameters)
        {
            if (!PBS.Util.Utility.IsValidFilename(Output))
            {
                MessageBox.Show(App.Current.FindResource("msgOutputPathError").ToString(), App.Current.FindResource("msgError").ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (File.Exists(Output))
            {
                if (MessageBox.Show(App.Current.FindResource("msgOverwrite").ToString(), App.Current.FindResource("msgWarning").ToString(), MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                {
                    return;
                }
                else
                {
                    try
                    {
                        File.Delete(Output);
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message, App.Current.FindResource("msgError").ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
            }
            try
            {
                string version = null;
                if (SelectedDatasourceType == "BaiduSate" || SelectedDatasourceType == "BaiduBase")
                {
                    version = "009";
                }
                else if (SelectedDatasourceType == "BaiduPanoMark")
                {
                    version = BaiDuMapManager.inst.streetudt;
                }
                else
                {
                    version = BaiDuMapManager.inst.cp.getLastVersion();
                }
                Datasource = new DataSourceBaiduOnlineMap(SelectedDatasourceType)
                {
                    OutputFileName = Output, Version = version, autoCorrectCoord = true
                };

                (Datasource as DataSourceBaiduOnlineMap).ConvertCompleted += (s, a) =>
                {
                    if (a.Successful)
                    {
                        if (!AutoConfirm)
                        {
                            string str = App.Current.FindResource("msgConvertComplete").ToString();
                            if (DoCompact)
                            {
                                str += "\r\n" + App.Current.FindResource("msgCompactResult").ToString() + (Datasource.ConvertingStatus.SizeBeforeCompact / 1024).ToString("N0") + "KB --> " + (Datasource.ConvertingStatus.SizeAfterCompact / 1024).ToString("N0") + "KB";
                            }
                            MessageBox.Show(str, "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }


                        DataSourceAdjustCoord transferSource = new DataSourceAdjustCoord(Output);
                        Datasource = transferSource;
                        (transferSource as DataSourceAdjustCoord).ConvertCompleted += (s1, a1) =>
                        {
                            string str1 = App.Current.FindResource("msgAdjustComplete").ToString();
                            MessageBox.Show(str1, "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        };
                        transferSource.ConvertToMBTiles(Output, "", "", "", Levels, null, false);
                    }
                };
                Datasource.ConvertCancelled += (s, a) =>
                {
                };
                BackgroundWorker bw = new BackgroundWorker();
                bw.DoWork += (s, a) =>
                {
                    IsIdle = false;
                    App.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        (CMDClickStartButton as DelegateCommand).RaiseCanExecuteChanged();
                    }));
                    ESRI.ArcGIS.Client.Geometry.Envelope extent = (ESRI.ArcGIS.Client.Geometry.Envelope)_webMercator.FromGeographic(DownloadExtent);
                    try
                    {
                        PBS.Util.Geometry g = _downloadPolygon == null ? (PBS.Util.Geometry) new PBS.Util.Envelope(DownloadExtent.XMin, DownloadExtent.YMin, DownloadExtent.XMax, DownloadExtent.YMax) : _downloadPolygon;
                        if (_downloadPolygon != null)
                        {
                            MessageBox.Show(App.Current.FindResource("msgDownloadByPolygonIntro").ToString(), "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        Datasource.ConvertToMBTiles(Output, Name, Description, Attribution, Levels, g, DoCompact);
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message, App.Current.FindResource("msgError").ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    IsIdle = true;
                    App.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        (CMDClickStartButton as DelegateCommand).RaiseCanExecuteChanged();
                    }));
                };
                bw.RunWorkerAsync();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
Example #24
0
        /// <summary>
        /// Check rectangle intersects with geometry.
        /// </summary>
        /// <param name="frame">Rectangle.</param>
        /// <param name="geometry">Geometry to check.</param>
        /// <returns>True if intersects</returns>
        public static bool IsIntersects(ESRI.ArcGIS.Client.Geometry.Envelope frame, ESRI.ArcGIS.Client.Geometry.Geometry geometry)
        {
            bool isIntersects = false;

            if (geometry is ESRI.ArcGIS.Client.Geometry.MapPoint)
            {
                ESRI.ArcGIS.Client.Geometry.MapPoint point = (ESRI.ArcGIS.Client.Geometry.MapPoint)geometry;
                if (frame.Extent.Intersects(point.Extent))
                {
                    isIntersects = true;
                }
            }
            else if (geometry is ESRI.ArcGIS.Client.Geometry.Polyline)
            {
                ESRI.ArcGIS.Client.Geometry.Polyline polyline = (ESRI.ArcGIS.Client.Geometry.Polyline)geometry;
                if (frame.Extent.Intersects(polyline.Extent))
                {
                    foreach (ESRI.ArcGIS.Client.Geometry.PointCollection points in polyline.Paths)
                    {
                        ESRI.ArcGIS.Client.Geometry.MapPoint prevPoint = null;
                        foreach (ESRI.ArcGIS.Client.Geometry.MapPoint point in points)
                        {
                            if (prevPoint != null)
                            {
                                if (_IsSegmentIntersectRectangle(frame.XMin, frame.YMin, frame.XMax, frame.YMax,
                                                                 point.X, point.Y, prevPoint.X, prevPoint.Y))
                                {
                                    isIntersects = true;
                                    break;
                                }
                            }

                            prevPoint = point;
                        }

                        if (isIntersects)
                        {
                            break;
                        }
                    }
                }
            }
            else if (geometry is ESRI.ArcGIS.Client.Geometry.Polygon)
            {
                ESRI.ArcGIS.Client.Geometry.Polygon polygon = (ESRI.ArcGIS.Client.Geometry.Polygon)geometry;
                if (frame.Extent.Intersects(polygon.Extent))
                {
                    foreach (ESRI.ArcGIS.Client.Geometry.PointCollection points in polygon.Rings)
                    {
                        ESRI.ArcGIS.Client.Geometry.MapPoint prevPoint = null;
                        foreach (ESRI.ArcGIS.Client.Geometry.MapPoint point in points)
                        {
                            if (prevPoint != null)
                            {
                                if (_IsSegmentIntersectRectangle(frame.XMin, frame.YMin, frame.XMax, frame.YMax,
                                                                 point.X, point.Y, prevPoint.X, prevPoint.Y))
                                {
                                    isIntersects = true;
                                    break;
                                }
                            }

                            prevPoint = point;
                        }

                        if (isIntersects)
                        {
                            break;
                        }
                    }
                }
            }
            else
            {
                Debug.Assert(false);
            }

            return(isIntersects);
        }
Example #25
0
        /// <summary>
        /// Is line intersects with extent.
        /// Implementation of Cohen-Sutherland algorithm.
        /// </summary>
        /// <param name="extent">Extent.</param>
        /// <param name="startPoint">Line start.</param>
        /// <param name="endPoint">Line end.</param>
        /// <returns>Is line intersects with extent.</returns>
        public static bool _IsLineIntersectsWithRect(Envelope extent, Point startPoint, Point endPoint)
        {
            ESRI.ArcGIS.Client.Geometry.MapPoint start = new ESRI.ArcGIS.Client.Geometry.MapPoint(startPoint.X, startPoint.Y);
            ESRI.ArcGIS.Client.Geometry.MapPoint end   = new ESRI.ArcGIS.Client.Geometry.MapPoint(endPoint.X, endPoint.Y);

            ESRI.ArcGIS.Client.Geometry.Envelope rect = new ESRI.ArcGIS.Client.Geometry.Envelope(
                extent.left, extent.top, extent.right, extent.bottom);

            int code_a, code_b, code;

            ESRI.ArcGIS.Client.Geometry.MapPoint temp;

            code_a = _GetPointCode(rect, start);
            code_b = _GetPointCode(rect, end);

            while (code_a > 0 || code_b > 0)
            {
                // If both points on one side, than line does not intersects extent.
                if ((code_a & code_b) > 0)
                {
                    return(false);
                }

                if (code_a > 0)
                {
                    code = code_a;
                    temp = start;
                }
                else
                {
                    code = code_b;
                    temp = end;
                }

                if ((code & LEFT_CODE) > 0)
                {
                    temp.Y = temp.Y + (start.Y - end.Y) * (rect.XMin - temp.X) / (start.X - end.X);
                    temp.X = rect.XMin;
                }
                else if ((code & RIGHT_CODE) > 0)
                {
                    temp.Y += (start.Y - end.Y) * (rect.XMax - temp.X) / (start.X - end.X);
                    temp.X  = rect.XMax;
                }

                if ((code & BOTTOM_CODE) > 0)
                {
                    temp.X += (start.X - end.X) * (rect.YMin - temp.Y) / (start.Y - end.Y);
                    temp.Y  = rect.YMin;
                }
                else if ((code & TOP_CODE) > 0)
                {
                    temp.X += (start.X - end.X) * (rect.YMax - temp.Y) / (start.Y - end.Y);
                    temp.Y  = rect.YMax;
                }

                if (code == code_a)
                {
                    code_a = _GetPointCode(rect, start);
                }
                else
                {
                    code_b = _GetPointCode(rect, end);
                }
            }

            return(true);
        }
        private void QueryTask_ExecuteCompleted(object sender, ESRI.ArcGIS.Client.Tasks.QueryEventArgs args)
        {
            FeatureSet featureSet = args.FeatureSet;

            // If initial query to populate states combo box
            if ((args.UserState as string) == "initial")
            {
                // Just show on initial load
                QueryComboBox.Items.Add("Select...");

                foreach (Graphic graphic in args.FeatureSet.Features)
                {
                    QueryComboBox.Items.Add(graphic.Attributes["STATE_NAME"].ToString());
                }

                QueryComboBox.SelectedIndex = 0;
                return;
            }

            // Remove the first entry if "Select..."
            if (QueryComboBox.Items[0].ToString().Contains("Select..."))
            {
                QueryComboBox.Items.RemoveAt(0);
            }

            // If an item has been selected
            GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer;

            graphicsLayer.ClearGraphics();

            if (featureSet != null && featureSet.Features.Count > 0)
            {
                // Show selected feature attributes in DataGrid
                Graphic selectedFeature = featureSet.Features[0];

                QueryDetailsDataGrid.ItemsSource = selectedFeature.Attributes;

                // Highlight selected feature
                selectedFeature.Symbol = LayoutRoot.Resources["DefaultFillSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol;
                graphicsLayer.Graphics.Add(selectedFeature);

                // Zoom to selected feature (define expand percentage)
                ESRI.ArcGIS.Client.Geometry.Envelope selectedFeatureExtent = selectedFeature.Geometry.Extent;

                double expandPercentage = 30;

                double widthExpand  = selectedFeatureExtent.Width * (expandPercentage / 100);
                double heightExpand = selectedFeatureExtent.Height * (expandPercentage / 100);

                ESRI.ArcGIS.Client.Geometry.Envelope displayExtent = new ESRI.ArcGIS.Client.Geometry.Envelope(
                    selectedFeatureExtent.XMin - (widthExpand / 2),
                    selectedFeatureExtent.YMin - (heightExpand / 2),
                    selectedFeatureExtent.XMax + (widthExpand / 2),
                    selectedFeatureExtent.YMax + (heightExpand / 2));

                MyMap.ZoomTo(displayExtent);

                // If DataGrid not visible (initial load), show it
                if (DataGridScrollViewer.Visibility == Visibility.Collapsed)
                {
                    DataGridScrollViewer.Visibility = Visibility.Visible;
                    QueryGrid.Height = Double.NaN;
                    QueryGrid.UpdateLayout();
                }
            }
            else
            {
                QueryDetailsDataGrid.ItemsSource = null;
                DataGridScrollViewer.Visibility  = Visibility.Collapsed;
                QueryGrid.Height = Double.NaN;
                QueryGrid.UpdateLayout();
            }
        }
        private void QueryTask_ExecuteCompleted(object sender, ESRI.ArcGIS.Client.Tasks.QueryEventArgs args)
        {
            FeatureSet featureSet = args.FeatureSet;

            // If initial query to populate states list box
            if ((args.UserState as string) == "initial")
            {
                // Just show on initial load
                QueryListBox.Items.Add("Select...");

                foreach (Graphic graphic in args.FeatureSet.Features)
                {
                    QueryListBox.Items.Add(graphic.Attributes["STATE_NAME"].ToString());
                }

                QueryListBox.SelectedIndex = 0;
                return;
            }

            // Remove the first entry if "Select..."
            if (QueryListBox.Items[0].ToString().Contains("Select..."))
            {
                QueryListBox.Items.RemoveAt(0);
            }

            // If an item has been selected
            GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer;

            graphicsLayer.ClearGraphics();

            if (featureSet != null && featureSet.Features.Count > 0)
            {
                // Show selected feature attributes in DataGrid
                Graphic selectedFeature = featureSet.Features[0];

                ResultsListBox.Items.Clear();
                //QueryDetailsDataGrid.ItemsSource = selectedFeature.Attributes;
                foreach (KeyValuePair <string, object> pair in selectedFeature.Attributes)
                {
                    TextBlock tb1 = new TextBlock()
                    {
                        FontSize   = 30,
                        FontWeight = FontWeights.Bold,
                        Text       = string.Format("{0}: ", pair.Key)
                    };
                    TextBlock tb2 = new TextBlock()
                    {
                        FontSize = 30,
                        Text     = string.Format(" {0}", pair.Value)
                    };
                    StackPanel sp = new StackPanel()
                    {
                        Orientation = System.Windows.Controls.Orientation.Vertical
                    };
                    sp.Children.Add(tb1);
                    sp.Children.Add(tb2);
                    ListBoxItem item = new ListBoxItem();
                    item.Content = sp;
                    ResultsListBox.Items.Add(item);
                }

                // Highlight selected feature
                selectedFeature.Symbol = DefaultFillSymbol;
                graphicsLayer.Graphics.Add(selectedFeature);

                // Zoom to selected feature (define expand percentage)
                ESRI.ArcGIS.Client.Geometry.Envelope selectedFeatureExtent = selectedFeature.Geometry.Extent;

                double expandPercentage = 30;

                double widthExpand  = selectedFeatureExtent.Width * (expandPercentage / 100);
                double heightExpand = selectedFeatureExtent.Height * (expandPercentage / 100);

                ESRI.ArcGIS.Client.Geometry.Envelope displayExtent = new ESRI.ArcGIS.Client.Geometry.Envelope(
                    selectedFeatureExtent.XMin - (widthExpand / 2),
                    selectedFeatureExtent.YMin - (heightExpand / 2),
                    selectedFeatureExtent.XMax + (widthExpand / 2),
                    selectedFeatureExtent.YMax + (heightExpand / 2));

                MyMap.ZoomTo(displayExtent);

                // If DataGrid not visible (initial load), show it
                if (ResultsListBox.Visibility == Visibility.Collapsed)
                {
                    ResultsListBox.Visibility = Visibility.Visible;
                    QueryGrid.Height          = Double.NaN;
                    QueryGrid.UpdateLayout();
                }
            }
            else
            {
                //QueryDetailsDataGrid.ItemsSource = null;
                ResultsListBox.Visibility = Visibility.Collapsed;
                QueryGrid.Height          = Double.NaN;
                QueryGrid.UpdateLayout();
            }
        }