Exemplo n.º 1
0
        public AreasAndLengths()
        {
            InitializeComponent();

            ESRI.ArcGIS.Client.Geometry.Envelope initialExtent =
                new ESRI.ArcGIS.Client.Geometry.Envelope(
                    mercator.FromGeographic(
                        new ESRI.ArcGIS.Client.Geometry.MapPoint(-130, 20)) as MapPoint,
                    mercator.FromGeographic(
                        new ESRI.ArcGIS.Client.Geometry.MapPoint(-65, 55)) as MapPoint);

            initialExtent.SpatialReference = new SpatialReference(102100);

            MyMap.Extent = initialExtent;

            MyDrawObject = new Draw(MyMap)
            {
                DrawMode   = DrawMode.Polygon,
                IsEnabled  = true,
                FillSymbol = LayoutRoot.Resources["DefaultFillSymbol"] as ESRI.ArcGIS.Client.Symbols.FillSymbol
            };
            MyDrawObject.DrawComplete += MyDrawObject_DrawComplete;
            MyDrawObject.DrawBegin    += MyDrawObject_DrawBegin;

            calculationTypeCombo.ItemsSource   = Enum.GetValues(typeof(CalculationType));
            calculationTypeCombo.SelectedIndex = 0;
        }
Exemplo n.º 2
0
        public ToolkitEditorWidget()
        {
            InitializeComponent();

            ESRI.ArcGIS.Client.Geometry.Envelope initialExtent =
                new ESRI.ArcGIS.Client.Geometry.Envelope(
                    _mercator.FromGeographic(
                        new ESRI.ArcGIS.Client.Geometry.MapPoint(-117.6690936441, 34.19871558256)) as MapPoint,
                    _mercator.FromGeographic(
                        new ESRI.ArcGIS.Client.Geometry.MapPoint(-117.411944901, 34.37896002836)) as MapPoint);

            initialExtent.SpatialReference = new SpatialReference(102100);

            MyMap.Extent = initialExtent;
        }
        public ToolkitAttachmentEditor()
        {
            InitializeComponent();

            ESRI.ArcGIS.Client.Geometry.Envelope initialExtent =
                new ESRI.ArcGIS.Client.Geometry.Envelope(
                    _mercator.FromGeographic(
                        new ESRI.ArcGIS.Client.Geometry.MapPoint(-122.4306073721, 37.7666097907)) as MapPoint,
                    _mercator.FromGeographic(
                        new ESRI.ArcGIS.Client.Geometry.MapPoint(-122.4230971868, 37.77197420877)) as MapPoint);

            initialExtent.SpatialReference = new SpatialReference(102100);

            MyMap.Extent = initialExtent;
        }
        public SDSMap()
        {
            InitializeComponent();

            ESRI.ArcGIS.Client.Geometry.Envelope initialExtent =
                new ESRI.ArcGIS.Client.Geometry.Envelope(
                    mercator.FromGeographic(
                        new ESRI.ArcGIS.Client.Geometry.MapPoint(-130, 20)) as MapPoint,
                    mercator.FromGeographic(
                        new ESRI.ArcGIS.Client.Geometry.MapPoint(-65, 55)) as MapPoint);

            initialExtent.SpatialReference = new SpatialReference(102100);

            MyMap.Extent = initialExtent;
        }
        public ToolkitFeatureDataForm()
        {
            InitializeComponent();

            ESRI.ArcGIS.Client.Geometry.Envelope initialExtent =
                new ESRI.ArcGIS.Client.Geometry.Envelope(
                    _mercator.FromGeographic(
                        new ESRI.ArcGIS.Client.Geometry.MapPoint(-122.4545596, 37.783443296)) as MapPoint,
                    _mercator.FromGeographic(
                        new ESRI.ArcGIS.Client.Geometry.MapPoint(-122.4449924, 37.786447331)) as MapPoint);

            initialExtent.SpatialReference = new SpatialReference(102100);

            MyMap.Extent = initialExtent;
        }
        public AddressToLocation()
        {
            InitializeComponent();
            ESRI.ArcGIS.Client.Geometry.Envelope initialExtent =
                new ESRI.ArcGIS.Client.Geometry.Envelope(
                    _mercator.FromGeographic(
                        new ESRI.ArcGIS.Client.Geometry.MapPoint(-122.554, 37.615)) as MapPoint,
                    _mercator.FromGeographic(
                        new ESRI.ArcGIS.Client.Geometry.MapPoint(-122.245, 37.884)) as MapPoint);

            initialExtent.SpatialReference = new SpatialReference(102100);

            MyMap.Extent = initialExtent;

            _candidateGraphicsLayer = MyMap.Layers["CandidateGraphicsLayer"] as GraphicsLayer;
        }
        public GraphicMapPoint(LocationTask task)
        {
            var merc = new ESRI.ArcGIS.Client.Projection.WebMercator();
            //for esri Lat = Y Long = X
            var extent = merc.FromGeographic(new MapPoint(task.Location.Longtitude, task.Location.Latitude, new SpatialReference(4326)));


            //mapPoint = new MapPoint(extent.Extent.XMax, extent.Extent.YMax, new SpatialReference(102100));
            this.Geometry            = extent;
            simpleMarkerSymbol       = new SimpleMarkerSymbol();
            simpleMarkerSymbol.Color = ShapeColor;
            simpleMarkerSymbol.Size  = ShapeSize;
            simpleMarkerSymbol.Style = ShapeStyle;
            this.Symbol = simpleMarkerSymbol;
            this.Attributes.Add("MapPointContent", MapPointContent);

            this.MapPointContent               = new MapPointContent(extent.Extent.XMax, extent.Extent.YMax);
            this.MapPointContent.Address       = task.Location.Address;
            this.MapPointContent.Id            = task.DatabaseId;
            this.MapPointContent.Latitude      = task.Location.Latitude;
            this.MapPointContent.Longtitude    = task.Location.Longtitude;
            this.MapPointContent.Name          = task.Name;
            this.MapPointContent.UserName      = task.UserEmail;
            this.MapPointContent.PublishedDate = task.LastTimeModified;
            this.MapPointContent.Info          = task.Info;
            this.MapPointContent.Info          = task.Info;
            this.MapPointContent.Label         = task.Label;

            if (string.IsNullOrWhiteSpace(MapPointContent.Address))
            {
                ReverseGeocode();
            }
        }
Exemplo n.º 8
0
 void webMapDocument_GetMapCompleted(object sender, GetMapCompletedEventArgs e)
 {
     if (e.Error == null)
     {
         e.Map.Extent = mercator.FromGeographic(new Envelope(-139.4916, 20.7191, -52.392, 59.5199)) as Envelope;
         MyMapGrid.Children.Add(e.Map);
     }
 }
Exemplo n.º 9
0
        Envelope ConvertPointToEnvelop(MapPoint point)
        {


            ESRI.ArcGIS.Client.Projection.WebMercator wm = new ESRI.ArcGIS.Client.Projection.WebMercator();
            //return wm.FromGeographic(new ESRI.ArcGIS.Client.Geometry.Envelope(point, point) { SpatialReference = new SpatialReference(org_wkid) }).Extent;
            return wm.FromGeographic(point).Extent;
        }
        void AddMarkerGraphics()
        {
            string jsonCoordinateString         = "{'Coordinates':[{'X':13,'Y':55.59},{'X':72.83,'Y':18.97},{'X':55.43,'Y':34.3}]}";
            CustomCoordinateList coordinateList = DeserializeJson <CustomCoordinateList>(jsonCoordinateString);

            GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer;

            for (int i = 0; i < coordinateList.Coordinates.Count; i++)
            {
                Graphic graphic = new Graphic()
                {
                    Geometry = mercator.FromGeographic(new MapPoint(coordinateList.Coordinates[i].X, coordinateList.Coordinates[i].Y)),
                    Symbol   = i > 0 ? LayoutRoot.Resources["RedMarkerSymbol"] as Symbol : LayoutRoot.Resources["BlackMarkerSymbol"] as Symbol
                };
                graphicsLayer.Graphics.Add(graphic);
            }
        }
        public LocationToAddress()
        {
            InitializeComponent();

            ESRI.ArcGIS.Client.Geometry.Envelope initialExtent =
                new ESRI.ArcGIS.Client.Geometry.Envelope(
                    _mercator.FromGeographic(
                        new ESRI.ArcGIS.Client.Geometry.MapPoint(-117.387, 33.97)) as MapPoint,
                    _mercator.FromGeographic(
                        new ESRI.ArcGIS.Client.Geometry.MapPoint(-117.355, 33.988)) as MapPoint);

            initialExtent.SpatialReference = new SpatialReference(102100);

            MyMap.Extent = initialExtent;

            _locationGraphicsLayer = MyMap.Layers["LocationGraphicsLayer"] as GraphicsLayer;
        }
        private void GraphicsLayer_Initialized(object sender, EventArgs e)
        {
            GraphicsLayer graphicsLayer = sender as GraphicsLayer;

            foreach (Graphic g in graphicsLayer.Graphics)
            {
                g.Geometry = _mercator.FromGeographic(g.Geometry);
            }
        }
Exemplo n.º 13
0
        public static void ConvertPoints()
        {
            MapPoint mp = new MapPoint();
            mp.Y = -28.487006;
            mp.X = 139.537485;
            mp.SpatialReference = new SpatialReference(4326);

            MapPoint mp2 = new MapPoint();
            mp2.Y = -28.314113;
            mp2.X = 139.437479;
            mp2.SpatialReference = new SpatialReference(4326);

            ESRI.ArcGIS.Client.Projection.WebMercator converter = new ESRI.ArcGIS.Client.Projection.WebMercator();

            ESRI.ArcGIS.Client.Geometry.Geometry convertedMapEndPoint = converter.FromGeographic(mp);
            ESRI.ArcGIS.Client.Geometry.Geometry convertedMapStartPoint = converter.FromGeographic(mp2);

            Console.WriteLine("Start Point:" + convertedMapStartPoint);
            Console.WriteLine("End Point" + convertedMapEndPoint);
        }
Exemplo n.º 14
0
        private void AddPictureMarkerAndTextGraphics()
        {
            string gpsNMEASentences = "$GPGGA, 92204.9, -35.6334, N, -60.2343, W, 1, 04, 2.4, 25.7, M,,,,*75\r\n" +
                                      "$GPGGA, 92510.5, -49.9334, N, -65.2131, W, 1, 04, 2.6, 1.7, M,,,,*75\r\n";

            string[] gpsNMEASentenceArray = gpsNMEASentences.Split('\n');

            GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer;

            for (int i = 0; i < gpsNMEASentenceArray.Length - 1; i++)
            {
                string[] gpsNMEASentence = gpsNMEASentenceArray[i].Split(',');
                MapPoint mp      = new MapPoint(Convert.ToDouble(gpsNMEASentence[4]), Convert.ToDouble(gpsNMEASentence[2]));
                MapPoint conv_mp = wm.FromGeographic(mp) as MapPoint;

                Graphic graphic = new Graphic()
                {
                    Geometry = conv_mp,
                    Symbol   = GlobePictureSymbol
                };

                graphicsLayer.Graphics.Add(graphic);


                TextSymbol textSymbol = new TextSymbol()
                {
                    FontFamily = new System.Windows.Media.FontFamily("Arial"),
                    Foreground = new System.Windows.Media.SolidColorBrush(Colors.Black),
                    FontSize   = 18,
                    Text       = gpsNMEASentence[9]
                };

                Graphic graphicText = new Graphic()
                {
                    Geometry = conv_mp,
                    Symbol   = textSymbol
                };

                graphicsLayer.Graphics.Add(graphicText);
            }
        }
        public BatchGeocoding()
        {
            InitializeComponent();

            ESRI.ArcGIS.Client.Geometry.Envelope initialExtent =
                new ESRI.ArcGIS.Client.Geometry.Envelope(
                    _mercator.FromGeographic(
                        new ESRI.ArcGIS.Client.Geometry.MapPoint(-117.387, 33.97)) as MapPoint,
                    _mercator.FromGeographic(
                        new ESRI.ArcGIS.Client.Geometry.MapPoint(-117.355, 33.988)) as MapPoint);

            initialExtent.SpatialReference = new SpatialReference(102100);

            MyMap.Extent = initialExtent;

            _locatorTask = new Locator("http://serverapps101.esri.com/arcgis/rest/services/USA_Geocode/GeocodeServer");
            _locatorTask.AddressesToLocationsCompleted += _locatorTask_AddressesToLocationsCompleted;
            _locatorTask.Failed += LocatorTask_Failed;

            geocodedResults = MyMap.Layers["LocationGraphicsLayer"] as GraphicsLayer;

            //List of addresses to geocode
            batchaddresses.Add(new Dictionary <string, string> {
                { "Street", "4409 Redwood Dr" }, { "Zip", "92501" }
            });
            batchaddresses.Add(new Dictionary <string, string> {
                { "Street", "3758 Cedar St" }, { "Zip", "92501" }
            });
            batchaddresses.Add(new Dictionary <string, string> {
                { "Street", "3486 Orange St" }, { "Zip", "92501" }
            });
            batchaddresses.Add(new Dictionary <string, string> {
                { "Street", "2999 4th St" }, { "Zip", "92507" }
            });
            batchaddresses.Add(new Dictionary <string, string> {
                { "Street", "3685 10th St" }, { "Zip", "92501" }
            });

            AddressListbox.ItemsSource = batchaddresses;
        }
        void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs <GeoCoordinate> e)
        {
            _graphicLocation.Geometry = mercator.FromGeographic(new MapPoint(e.Position.Location.Longitude, e.Position.Location.Latitude));

            // Use horizontal accuracy (returned in meters) to zoom to the location
            if (initialLoad)
            {
                Envelope rect = new Envelope(
                    (_graphicLocation.Geometry as MapPoint).X - (e.Position.Location.HorizontalAccuracy / 2),
                    (_graphicLocation.Geometry as MapPoint).Y - (e.Position.Location.HorizontalAccuracy / 2),
                    (_graphicLocation.Geometry as MapPoint).X + (e.Position.Location.HorizontalAccuracy / 2),
                    (_graphicLocation.Geometry as MapPoint).Y + (e.Position.Location.HorizontalAccuracy / 2));

                MyMap.ZoomTo(rect.Expand(20));

                initialLoad = false;
            }
            else
            {
                MyMap.PanTo(_graphicLocation.Geometry);
            }
        }
Exemplo n.º 17
0
        void timer_Tick(object sender, EventArgs e)
        {
            ClearItems();

            random = new Random();

            for (int i = 0; i < 10; i++)
            {
                Graphic g = new Graphic()
                {
                    Geometry = mercator.FromGeographic(new MapPoint(random.Next(-180, 180), random.Next(-90, 90)))
                };

                g.Symbol = new SimpleMarkerSymbol()
                {
                    Color = new SolidColorBrush(Color.FromArgb(255, (byte)random.Next(0, 255), (byte)random.Next(0, 255), (byte)random.Next(0, 255))),
                    Size  = 24
                };

                Add(g);
            }
        }
Exemplo n.º 18
0
        // Click on a web map item in the Listbox, zoom to and select the respective graphic in the map.
        private void Image_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            webmapGraphicsLayer.ClearSelection();
            ArcGISPortalItem portalItem = (sender as Image).DataContext as ArcGISPortalItem;

            if (portalItem.Extent != null)
            {
                MyMap.ZoomTo(mercator.FromGeographic(portalItem.Extent));
            }

            // Use LINQ to select the graphic where the portal item attribute equals the portal item instance
            // in the Listbox.
            var queryPortalItemGraphics = from g in webmapGraphicsLayer.Graphics
                                          where g.Attributes["PortalItem"] == portalItem
                                          select g;

            // Get the first graphic in the IEnumerable of graphics and set it selected.
            foreach (var graphic in queryPortalItemGraphics)
            {
                graphic.Selected = true;
                return;
            }
        }
        private void GraphicsLayer_Initialized(object sender, EventArgs e)
        {
            GraphicsLayer graphicsLayer = sender as GraphicsLayer;

            foreach (Graphic g in graphicsLayer.Graphics)
            {
                g.Geometry = _mercator.FromGeographic(g.Geometry);

                if (g.Geometry is Polygon || g.Geometry is Envelope)
                {
                    JsonTextBoxFillCurrent.Text = (g.Symbol as IJsonSerializable).ToJson();
                }
                else if (g.Geometry is Polyline)
                {
                    JsonTextBoxLineCurrent.Text = (g.Symbol as IJsonSerializable).ToJson();
                }
                else
                {
                    JsonTextBoxMarkerCurrent.Text = (g.Symbol as IJsonSerializable).ToJson();
                }

                g.PropertyChanged += g_PropertyChanged;
            }
        }
Exemplo n.º 20
0
        public static ESRI.ArcGIS.Client.Geometry.Geometry GetLocationCoord(string address)
        {
            ESRI.ArcGIS.Client.Geometry.MapPoint _mp = null;
            string url=string.Format("http://maps.google.com/maps/api/geocode/json?address={0}ka&sensor=false",address);
            HttpWebRequest hwr = WebRequest.Create(url) as HttpWebRequest;
            hwr.Method = "GET";
            HttpWebResponse httpResponse;
            StringBuilder stringBuffer = new StringBuilder();
            try
            {
                httpResponse = hwr.GetResponse() as HttpWebResponse;
                if (httpResponse.GetResponseStream().CanRead)
                {
                    StreamReader sr = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8);
                    string s = sr.ReadToEnd();
                    JObject jObject = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(s);
                    string lon= ((((jObject["results"] as JArray)[0] as JObject)["geometry"] as JObject)["location"] as JObject)["lng"].ToString();
                    string lat = ((((jObject["results"] as JArray)[0] as JObject)["geometry"] as JObject)["location"] as JObject)["lat"].ToString();

                    ESRI.ArcGIS.Client.Geometry.MapPoint mp = new ESRI.ArcGIS.Client.Geometry.MapPoint()
                    {
                        X=double.Parse(lon),
                        Y=double.Parse(lat),
                        SpatialReference = new ESRI.ArcGIS.Client.Geometry.SpatialReference(4326)
                    };
                    ESRI.ArcGIS.Client.Projection.WebMercator w = new ESRI.ArcGIS.Client.Projection.WebMercator();
                    _mp = w.FromGeographic(mp) as ESRI.ArcGIS.Client.Geometry.MapPoint;
                }
            }
            catch (Exception e)
            {
            }
            return _mp;
        }
Exemplo n.º 21
0
        }         // public void userGiveCSVLayerParams(string url, string lyrname, string proxy)

        /// <summary>
        /// Call from form, add to map graphicslayer from json
        /// </summary>
        /// <param name="url"></param>
        /// <param name="lyrname"></param>
        /// <param name="proxy"></param>
        public void userGiveJSONLayerParams(string url, string lyrname, string proxy)
        {
            log(string.Format("userGiveJSONLayerParams, name '{2}', url '{0}', proxy '{1}'", url, proxy, lyrname));
            MapApplication.Current.HideWindow(jsonParamsForm);

            var requrl = string.IsNullOrEmpty(proxy) ? url : string.Format("{0}?{1}", proxy, url);

            // get json text
            WebClient wc  = new WebClient();
            Uri       uri = new Uri(requrl, UriKind.RelativeOrAbsolute);

            wc.OpenReadCompleted += (sender, args) => {
                if (args.Error != null)
                {
                    log(String.Format("userGiveJSONLayerParams wc_OpenReadCompleted, error in reading answer, msg [{0}], trace [{1}]",
                                      args.Error.Message, args.Error.StackTrace));
                }
                else
                {
                    try {
                        StreamReader reader = new StreamReader(args.Result);
                        string       text   = reader.ReadToEnd();
                        log(string.Format("userGiveJSONLayerParams wc_OpenReadCompleted, resp '{0}'", text));

                        // got layer content, make layer
                        var featureSet    = FeatureSet.FromJson(text);
                        var graphicsLayer = new GraphicsLayer()
                        {
                            Graphics = new GraphicCollection(featureSet)
                        };
                        // set layer params
                        graphicsLayer.Opacity      = 1;
                        graphicsLayer.ID           = VExtClass.computeSHA1Hash(string.Format("{0}", text));
                        graphicsLayer.Initialized += (osender, eargs) => {
                            log(string.Format("userGiveJSONLayerParams.Initialized, {0}-{1}", lyrname, graphicsLayer.ID));
                        };

                        // projection
                        var MyMap    = MapApplication.Current.Map;
                        var mercator = new ESRI.ArcGIS.Client.Projection.WebMercator();
                        if (!featureSet.SpatialReference.Equals(MyMap.SpatialReference))
                        {
                            if (MyMap.SpatialReference.Equals(new SpatialReference(102100)) &&
                                featureSet.SpatialReference.Equals(new SpatialReference(4326)))
                            {
                                foreach (Graphic g in graphicsLayer.Graphics)
                                {
                                    g.Geometry = mercator.FromGeographic(g.Geometry);
                                }
                            }

                            else if (MyMap.SpatialReference.Equals(new SpatialReference(4326)) &&
                                     featureSet.SpatialReference.Equals(new SpatialReference(102100)))
                            {
                                foreach (Graphic g in graphicsLayer.Graphics)
                                {
                                    g.Geometry = mercator.ToGeographic(g.Geometry);
                                }
                            }

                            else
                            {
                                var geometryService = new GeometryService(
                                    "http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");

                                geometryService.ProjectCompleted += (s, a) => {
                                    for (int i = 0; i < a.Results.Count; i++)
                                    {
                                        graphicsLayer.Graphics[i].Geometry = a.Results[i].Geometry;
                                    }
                                };

                                geometryService.Failed += (s, a) => {
                                    MessageBox.Show("Ошибка проецирования: " + a.Error.Message);
                                };

                                geometryService.ProjectAsync(graphicsLayer.Graphics, MyMap.SpatialReference);
                            }
                        }                         // if map.SR != featureset.SR

                        // add layer to map
                        graphicsLayer.Initialize();
                        MapApplication.SetLayerName(graphicsLayer, lyrname);
                        ESRI.ArcGIS.Client.Extensibility.LayerProperties.SetIsVisibleInMapContents(graphicsLayer, true);
                        MapApplication.Current.Map.Layers.Add(graphicsLayer);
                    }                     // got json text
                    catch (Exception ex) {
                        log(String.Format("userGiveJSONLayerParams wc_OpenReadCompleted, make layer failed {0}, {1}", ex.Message, ex.StackTrace));
                    }
                }
            };             // wc.OpenReadCompleted
            wc.OpenReadAsync(uri);

            log(string.Format("userGiveJSONLayerParams, done for name '{2}', url '{0}', proxy '{1}'", url, proxy, lyrname));
        }         // public void userGiveJSONLayerParams(string url, string lyrname, string proxy)
        void projectGraphicsAsync(string geometryServiceUrl, IList <Graphic> graphics, SpatialReference outputSpatialReference,
                                  ProjectCompleteDelegate onProjectGeometryComplete, object userState)
        {
            if (graphics == null)
            {
                throw new ArgumentNullException("graphics");
            }
            if (graphics.Count < 1)
            {
                OnProjectExtentComplete(new ProjectGraphicsCompletedEventArgs()
                {
                    Graphics = graphics
                });
                return;
            }

            if (outputSpatialReference.WKID == 4326 && graphics.All(g => g.Geometry != null &&
                                                                    g.Geometry.SpatialReference != null && isWebMercator(g.Geometry.SpatialReference)))
            {
                // Project from web mercator to GCS client-side
                var            wm          = new ESRI.ArcGIS.Client.Projection.WebMercator();
                List <Graphic> outGraphics = new List <Graphic>();
                foreach (var g in graphics)
                {
                    var outGraphic = cloneGraphic(g);
                    outGraphic.Geometry = wm.ToGeographic(g.Geometry);
                    outGraphics.Add(outGraphic);
                }
                OnProjectExtentComplete(new ProjectGraphicsCompletedEventArgs()
                {
                    Graphics = outGraphics
                });
            }
            else if (isWebMercator(outputSpatialReference) && graphics.All(g => g.Geometry != null &&
                                                                           g.Geometry.SpatialReference != null && g.Geometry.SpatialReference.WKID == 4326))
            {
                // Project from GCS to web mercator client-side
                var            wm          = new ESRI.ArcGIS.Client.Projection.WebMercator();
                List <Graphic> outGraphics = new List <Graphic>();
                foreach (var g in graphics)
                {
                    var outGraphic = cloneGraphic(g);
                    outGraphic.Geometry = wm.FromGeographic(g.Geometry);
                    outGraphics.Add(outGraphic);
                }
                OnProjectExtentComplete(new ProjectGraphicsCompletedEventArgs()
                {
                    Graphics = outGraphics
                });
            }
            else
            {
                GeometryService geomService = new GeometryService(geometryServiceUrl)
                {
                    ProxyURL = this.ProxyUrl
                };
                geomService.ProjectCompleted += (o, e) =>
                {
                    int len1 = graphics.Count;
                    int len2 = e.Results.Count;
                    System.Diagnostics.Debug.Assert(len1 == len2, Resources.Strings.ExceptionNumberofGraphicsBeforeAndAfterProjectionAreNotEqual);
                    for (int i = 0; i < len1 && i < len2; i++)
                    {
                        var targetGraphic = cloneGraphic(graphics[i]);
                        targetGraphic.Geometry = e.Results[i].Geometry;
                        e.Results[i]           = targetGraphic;
                    }
                    onProjectGeometryComplete(o, e);
                };
                geomService.Failed += (o, e) =>
                {
                    if ((e.Error is ESRI.ArcGIS.Client.Tasks.ServiceException || e.Error is System.Net.WebException) && geometryServiceUrl != FallbackGeometryServer)
                    {
                        projectGraphicsAsync(FallbackGeometryServer, graphics, outputSpatialReference, onProjectGeometryComplete, e.UserState);
                    }
                    else
                    {
                        OnGeometryServiceOperationFailed(new ExceptionEventArgs(new Exception(e.Error == null ? e.Error.Message : ""), e.UserState));
                    }
                };
                geomService.ProjectAsync(graphics, outputSpatialReference, userState);
            }
        }
Exemplo n.º 23
0
 MapPoint ConvertMapPointTo102100(MapPoint mp)
 {
     ESRI.ArcGIS.Client.Projection.WebMercator wm = new ESRI.ArcGIS.Client.Projection.WebMercator();
        return  wm.FromGeographic(mp) as MapPoint;
 }
Exemplo n.º 24
0
        private void MyDrawObject_DrawComplete(object sender, ESRI.ArcGIS.Client.DrawEventArgs args)
        {
            Type     geometryType              = args.Geometry.GetType();
            Geometry wgs84Geometry             = _mercator.ToGeographic(args.Geometry);
            Geometry mercatorDensifiedGeometry = null;
            Geometry densifiedGeometry         = null;
            int      originalVerticeCount      = 0;
            int      densifiedVerticeCount     = 0;

            if (geometryType == typeof(Polygon))
            {
                // Values returned in meters
                if (RadioButtonGeodesic.IsChecked.Value)
                {
                    TextBlockLength.Text = (ESRI.ArcGIS.Client.Geometry.Geodesic.Length(wgs84Geometry as Polygon)
                                            * 0.000621371192).ToString("#0.000") + " mi";
                    TextBlockArea.Text = (Math.Abs(ESRI.ArcGIS.Client.Geometry.Geodesic.Area(wgs84Geometry as Polygon))
                                          * 3.86102159e-7).ToString("#0.000") + " sq mi";
                }
                else
                {
                    TextBlockLength.Text = (ESRI.ArcGIS.Client.Geometry.Euclidian.Length(args.Geometry as Polygon)
                                            * 0.000621371192).ToString("#0.000") + " mi";
                    TextBlockArea.Text = (Math.Abs(ESRI.ArcGIS.Client.Geometry.Euclidian.Area(args.Geometry as Polygon))
                                          * 3.86102159e-7).ToString("#0.000") + " sq mi";
                }

                foreach (PointCollection ring in (args.Geometry as Polygon).Rings)
                {
                    foreach (MapPoint mp in ring)
                    {
                        originalVerticeCount++;
                        verticesGraphicsLayer.Graphics.Add(new ESRI.ArcGIS.Client.Graphic()
                        {
                            Geometry = mp,
                            Symbol   = LayoutRoot.Resources["OriginalMarkerSymbol"] as Symbol
                        });
                    }
                }

                if (RadioButtonGeodesic.IsChecked.Value)
                {
                    densifiedGeometry =
                        ESRI.ArcGIS.Client.Geometry.Geodesic.Densify(wgs84Geometry, MyMap.Resolution * 10);
                    mercatorDensifiedGeometry = _mercator.FromGeographic(densifiedGeometry);
                }
                else
                {
                    mercatorDensifiedGeometry =
                        ESRI.ArcGIS.Client.Geometry.Euclidian.Densify(args.Geometry, MyMap.Resolution * 10);
                }

                foreach (PointCollection ring in (mercatorDensifiedGeometry as Polygon).Rings)
                {
                    foreach (MapPoint mp in ring)
                    {
                        densifiedVerticeCount++;
                        verticesGraphicsLayer.Graphics.Add(new ESRI.ArcGIS.Client.Graphic()
                        {
                            Geometry = mp,
                            Symbol   = LayoutRoot.Resources["NewMarkerSymbol"] as Symbol
                        });
                    }
                }
            }
            else // Polyline
            {
                // Value returned in meters
                if (RadioButtonGeodesic.IsChecked.Value)
                {
                    TextBlockLength.Text = (ESRI.ArcGIS.Client.Geometry.Geodesic.Length(wgs84Geometry as Polyline)
                                            * 0.000621371192).ToString("#0.000") + " mi";
                }
                else
                {
                    TextBlockLength.Text = (ESRI.ArcGIS.Client.Geometry.Euclidian.Length(args.Geometry as Polyline)
                                            * 0.000621371192).ToString("#0.000") + " mi";
                }

                TextBlockArea.Text = "NA";

                foreach (PointCollection path in (args.Geometry as Polyline).Paths)
                {
                    foreach (MapPoint mp in path)
                    {
                        originalVerticeCount++;
                        verticesGraphicsLayer.Graphics.Add(new ESRI.ArcGIS.Client.Graphic()
                        {
                            Geometry = mp,
                            Symbol   = LayoutRoot.Resources["OriginalMarkerSymbol"] as Symbol
                        });
                    }
                }

                if (RadioButtonGeodesic.IsChecked.Value)
                {
                    densifiedGeometry =
                        ESRI.ArcGIS.Client.Geometry.Geodesic.Densify(wgs84Geometry, MyMap.Resolution * 10);
                    mercatorDensifiedGeometry = _mercator.FromGeographic(densifiedGeometry);
                }
                else
                {
                    mercatorDensifiedGeometry =
                        ESRI.ArcGIS.Client.Geometry.Euclidian.Densify(args.Geometry, MyMap.Resolution * 10);
                }

                foreach (PointCollection path in (mercatorDensifiedGeometry as Polyline).Paths)
                {
                    foreach (MapPoint mp in path)
                    {
                        densifiedVerticeCount++;
                        verticesGraphicsLayer.Graphics.Add(new ESRI.ArcGIS.Client.Graphic()
                        {
                            Geometry = mp,
                            Symbol   = LayoutRoot.Resources["NewMarkerSymbol"] as Symbol
                        });
                    }
                }
            }

            featureGraphicsLayer.Graphics.Add(new ESRI.ArcGIS.Client.Graphic()
            {
                Geometry = mercatorDensifiedGeometry,
                Symbol   = geometryType == typeof(Polygon) ?
                           LayoutRoot.Resources["ResultFillSymbol"] as Symbol :
                           LayoutRoot.Resources["ResultLineSymbol"] as Symbol
            });

            TextBlockVerticesBefore.Text = originalVerticeCount.ToString();
            TextBlockVerticesAfter.Text  = densifiedVerticeCount.ToString();
        }
        private void Button_Load(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                FeatureSet featureSet = FeatureSet.FromJson(JsonTextBox.Text);

                GraphicsLayer graphicsLayerFromFeatureSet = new GraphicsLayer()
                {
                    Graphics = new GraphicCollection(featureSet)
                };

                if (!featureSet.SpatialReference.Equals(MyMap.SpatialReference))
                {
                    if (MyMap.SpatialReference.Equals(new SpatialReference(102100)) &&
                        featureSet.SpatialReference.Equals(new SpatialReference(4326)))
                    {
                        foreach (Graphic g in graphicsLayerFromFeatureSet.Graphics)
                        {
                            g.Geometry = _mercator.FromGeographic(g.Geometry);
                        }
                    }

                    else if (MyMap.SpatialReference.Equals(new SpatialReference(4326)) &&
                             featureSet.SpatialReference.Equals(new SpatialReference(102100)))
                    {
                        foreach (Graphic g in graphicsLayerFromFeatureSet.Graphics)
                        {
                            g.Geometry = _mercator.ToGeographic(g.Geometry);
                        }
                    }

                    else
                    {
                        GeometryService geometryService =
                            new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");

                        geometryService.ProjectCompleted += (s, a) =>
                        {
                            for (int i = 0; i < a.Results.Count; i++)
                            {
                                graphicsLayerFromFeatureSet.Graphics[i].Geometry = a.Results[i].Geometry;
                            }
                        };

                        geometryService.Failed += (s, a) =>
                        {
                            MessageBox.Show("Projection error: " + a.Error.Message);
                        };

                        geometryService.ProjectAsync(graphicsLayerFromFeatureSet.Graphics, MyMap.SpatialReference);
                    }
                }

                SimpleRenderer  simpleRenderer = new SimpleRenderer();
                SolidColorBrush symbolColor    = new SolidColorBrush(Colors.Blue);
                graphicsLayerFromFeatureSet.Renderer = simpleRenderer;

                if (featureSet.GeometryType == GeometryType.Polygon || featureSet.GeometryType == GeometryType.Polygon)
                {
                    simpleRenderer.Symbol = new SimpleFillSymbol()
                    {
                        Fill = symbolColor
                    };
                }
                else if (featureSet.GeometryType == GeometryType.Polyline)
                {
                    simpleRenderer.Symbol = new SimpleLineSymbol()
                    {
                        Color = symbolColor
                    };
                }
                else // Point
                {
                    simpleRenderer.Symbol = new SimpleMarkerSymbol()
                    {
                        Color = symbolColor,
                        Size  = 12
                    };
                }

                myInfoWindow = new InfoWindow()
                {
                    Background      = new SolidColorBrush(Colors.Black),
                    BorderBrush     = new SolidColorBrush(Colors.White),
                    BorderThickness = new Thickness(1),
                    CornerRadius    = 10,
                    Map             = MyMap,
                };
                myInfoWindow.MouseLeftButtonDown += myInfoWindow_MouseLeftButtonDown;

                StackPanel stackPanelParent = new StackPanel()
                {
                    Orientation = System.Windows.Controls.Orientation.Vertical,
                    Margin      = new Thickness(12)
                };

                foreach (KeyValuePair <string, string> keyvalue in featureSet.FieldAliases)
                {
                    StackPanel stackPanelChild = new StackPanel()
                    {
                        Orientation = System.Windows.Controls.Orientation.Horizontal,
                        Margin      = new Thickness(0, 0, 0, 6)
                    };
                    TextBlock textValue = new TextBlock()
                    {
                        Text = keyvalue.Value + ": "
                    };

                    TextBlock textKey    = new TextBlock();
                    Binding   keyBinding = new Binding(string.Format("[{0}]", keyvalue.Key));
                    textKey.SetBinding(TextBlock.TextProperty, keyBinding);

                    stackPanelChild.Children.Add(textValue);
                    stackPanelChild.Children.Add(textKey);

                    if (keyvalue.Key == featureSet.DisplayFieldName)
                    {
                        textKey.FontWeight = textValue.FontWeight = FontWeights.Bold;
                        stackPanelParent.Children.Insert(0, stackPanelChild);
                    }
                    else
                    {
                        stackPanelParent.Children.Add(stackPanelChild);
                    }
                }

                myInfoWindow.Content = stackPanelParent;
                ContentPanel.Children.Add(myInfoWindow);

                MyMap.Layers.Add(graphicsLayerFromFeatureSet);
                graphicsLayerFromFeatureSet.MouseLeftButtonDown += graphicsLayerFromFeatureSet_MouseLeftButtonDown;
                JsonPivot.Visibility = Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "GraphicsLayer creation failed", MessageBoxButton.OK);
            }
        }
        void projectGraphicsAsync(string geometryServiceUrl, IList<Graphic> graphics, SpatialReference outputSpatialReference,
            ProjectCompleteDelegate onProjectGeometryComplete, object userState)
        {
            if (graphics == null)
                throw new ArgumentNullException("graphics");
            if (graphics.Count < 1)
            {
                OnProjectExtentComplete(new ProjectGraphicsCompletedEventArgs() { Graphics = graphics });
                return;
            }

            if (outputSpatialReference.WKID == 4326 && graphics.All(g => g.Geometry != null 
                && g.Geometry.SpatialReference != null && isWebMercator(g.Geometry.SpatialReference)))
            {
                // Project from web mercator to GCS client-side
                var wm = new ESRI.ArcGIS.Client.Projection.WebMercator();
                List<Graphic> outGraphics = new List<Graphic>();
                foreach (var g in graphics)
                {
                    var outGraphic = cloneGraphic(g);
                    outGraphic.Geometry = wm.ToGeographic(g.Geometry);
                    outGraphics.Add(outGraphic);
                }
                OnProjectExtentComplete(new ProjectGraphicsCompletedEventArgs() { Graphics = outGraphics });
            }
            else if (isWebMercator(outputSpatialReference) && graphics.All(g => g.Geometry != null
                && g.Geometry.SpatialReference != null && g.Geometry.SpatialReference.WKID == 4326))
            {
                // Project from GCS to web mercator client-side
                var wm = new ESRI.ArcGIS.Client.Projection.WebMercator();
                List<Graphic> outGraphics = new List<Graphic>();
                foreach (var g in graphics)
                {
                    var outGraphic = cloneGraphic(g);
                    outGraphic.Geometry = wm.FromGeographic(g.Geometry);
                    outGraphics.Add(outGraphic);
                }
                OnProjectExtentComplete(new ProjectGraphicsCompletedEventArgs() { Graphics = outGraphics });
            }
            else
            {
                GeometryService geomService = new GeometryService(geometryServiceUrl) { ProxyURL = this.ProxyUrl };
                geomService.ProjectCompleted += (o, e) =>
                {
                    int len1 = graphics.Count;
                    int len2 = e.Results.Count;
                    System.Diagnostics.Debug.Assert(len1 == len2, Resources.Strings.ExceptionNumberofGraphicsBeforeAndAfterProjectionAreNotEqual);
                    for (int i = 0; i < len1 && i < len2; i++)
                    {
                        var targetGraphic = cloneGraphic(graphics[i]);
                        targetGraphic.Geometry = e.Results[i].Geometry;
                        e.Results[i] = targetGraphic;                        
                    }
                    onProjectGeometryComplete(o, e);
                };
                geomService.Failed += (o, e) =>
                {
                    if ((e.Error is ESRI.ArcGIS.Client.Tasks.ServiceException || e.Error is System.Net.WebException) && geometryServiceUrl != FallbackGeometryServer)
                    {
                        projectGraphicsAsync(FallbackGeometryServer, graphics, outputSpatialReference, onProjectGeometryComplete, e.UserState);
                    }
                    else
                    {
                        OnGeometryServiceOperationFailed(new ExceptionEventArgs(new Exception(e.Error == null ? e.Error.Message : ""), e.UserState));
                    }
                };
                geomService.ProjectAsync(graphics, outputSpatialReference, userState);
            }
        }
Exemplo n.º 27
0
 private void buttonSearchAddress_Click(object sender, RoutedEventArgs e)
 {
     string[] coords = this.textBoxCoord.Text.Trim().Replace(',', ',').Split(',');
     if (coords==null||coords.Length<2)
     {
         MessageBox.Show("Wrong Coords Format,Check it out");
         return;
     }
     double lon = double.Parse(coords[0]);
     double lat = double.Parse(coords[1]);
     if (lat>90.0||lat<-90.0||lon>180.0||lon<-180.0)
     {
         MessageBox.Show("Wrong Coords Format,Check it out");
         return;
     }
     string result= GetLocationAddress(this.textBoxCoord.Text);
     if (this.map1.Layers.Contains(this.map1.Layers["SearchLyr"]))
     {
         this.map1.Layers.Remove(this.map1.Layers["SearchLyr"]);
     }
     ESRI.ArcGIS.Client.Geometry.MapPoint mp = new ESRI.ArcGIS.Client.Geometry.MapPoint()
     {
         X=lon,
         Y=lat,
         SpatialReference = new ESRI.ArcGIS.Client.Geometry.SpatialReference(4326)
     };
     ESRI.ArcGIS.Client.Projection.WebMercator wm = new ESRI.ArcGIS.Client.Projection.WebMercator();
     mp= wm.FromGeographic(mp) as ESRI.ArcGIS.Client.Geometry.MapPoint;
     ESRI.ArcGIS.Client.Geometry.Polyline pl = CreateGeoForZoom(mp);
     ESRI.ArcGIS.Client.GraphicsLayer gl = CreateSearchLyr(mp);
     this.textBoxResult.Text = this.textBoxCoord.Text + ":" +result;
     this.map1.ZoomTo(pl as ESRI.ArcGIS.Client.Geometry.Geometry);
     this.map1.Layers.Add(gl as ESRI.ArcGIS.Client.Layer);
 }
Exemplo n.º 28
0
        private void LocatorTask_AddressToLocationsCompleted(object sender, ESRI.ArcGIS.Client.Tasks.AddressToLocationsEventArgs args)
        {
            _candidateGraphicsLayer.ClearGraphics();
            CandidateListBox.Items.Clear();

            List <AddressCandidate> returnedCandidates = args.Results;

            foreach (AddressCandidate candidate in returnedCandidates)
            {
                if (candidate.Score >= 80)
                {
                    CandidateListBox.Items.Add(candidate.Address);

                    Graphic graphic = new Graphic()
                    {
                        Symbol   = LayoutRoot.Resources["DefaultMarkerSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol,
                        Geometry = candidate.Location
                    };

                    graphic.Attributes.Add("Address", candidate.Address);

                    string latlon = String.Format("{0}, {1}", candidate.Location.X, candidate.Location.Y);
                    graphic.Attributes.Add("LatLon", latlon);

                    if (candidate.Location.SpatialReference == null)
                    {
                        candidate.Location.SpatialReference = new SpatialReference(4326);
                    }

                    if (!candidate.Location.SpatialReference.Equals(MyMap.SpatialReference))
                    {
                        if (MyMap.SpatialReference.Equals(new SpatialReference(102100)) && candidate.Location.SpatialReference.Equals(new SpatialReference(4326)))
                        {
                            graphic.Geometry = _mercator.FromGeographic(graphic.Geometry);
                        }
                        else if (MyMap.SpatialReference.Equals(new SpatialReference(4326)) && candidate.Location.SpatialReference.Equals(new SpatialReference(102100)))
                        {
                            graphic.Geometry = _mercator.ToGeographic(graphic.Geometry);
                        }
                        else if (MyMap.SpatialReference != new SpatialReference(4326))
                        {
                            GeometryService geometryService =
                                new GeometryService("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");

                            geometryService.ProjectCompleted += (s, a) =>
                            {
                                graphic.Geometry = a.Results[0].Geometry;
                            };

                            geometryService.Failed += (s, a) =>
                            {
                                MessageBox.Show("Projection error: " + a.Error.Message);
                            };

                            geometryService.ProjectAsync(new List <Graphic> {
                                graphic
                            }, MyMap.SpatialReference);
                        }
                    }

                    _candidateGraphicsLayer.Graphics.Add(graphic);
                }
            }

            if (_candidateGraphicsLayer.Graphics.Count > 0)
            {
                CandidatePanelGrid.Visibility  = Visibility.Visible;
                CandidateListBox.SelectedIndex = 0;
            }
        }
        private void LoadMapButton_Click(object sender, RoutedEventArgs e)
        {
            WebClient webClient = new WebClient();
            string    uri       = string.Format("http://dev.virtualearth.net/REST/v1/Imagery/Metadata/Aerial?supressStatus=true&key={0}", BingKeyTextBox.Text);

            webClient.OpenReadCompleted += (s, a) =>
            {
                if (a.Error == null)
                {
                    DataContractJsonSerializer serializer         = new DataContractJsonSerializer(typeof(BingAuthentication));
                    BingAuthentication         bingAuthentication = serializer.ReadObject(a.Result) as BingAuthentication;
                    a.Result.Close();
                    string authenticationResult = bingAuthentication.AuthenticationResultCode.ToString();

                    if (authenticationResult == "ValidCredentials")
                    {
                        ESRI.ArcGIS.Client.Bing.TileLayer tileLayer = new TileLayer()
                        {
                            ID         = "BingLayer",
                            LayerStyle = TileLayer.LayerType.Road,
                            ServerType = ServerType.Production,
                            Token      = BingKeyTextBox.Text
                        };

                        MyMap.Layers.Insert(0, tileLayer);

                        // Add your Bing Maps key in the constructor for the Routing class. Use http://www.bingmapsportal.com to generate a key.
                        routing            = new ESRI.ArcGIS.Client.Bing.Routing(BingKeyTextBox.Text);
                        routing.ServerType = ServerType.Production;

                        myDrawObject = new Draw(MyMap)
                        {
                            DrawMode  = DrawMode.Point,
                            IsEnabled = true
                        };

                        myDrawObject.DrawComplete += MyDrawObject_DrawComplete;
                        waypointGraphicsLayer      = MyMap.Layers["WaypointGraphicsLayer"] as GraphicsLayer;
                        routeResultsGraphicsLayer  = MyMap.Layers["RouteResultsGraphicsLayer"] as GraphicsLayer;

                        ESRI.ArcGIS.Client.Geometry.Envelope initialExtent =
                            new ESRI.ArcGIS.Client.Geometry.Envelope(
                                mercator.FromGeographic(
                                    new ESRI.ArcGIS.Client.Geometry.MapPoint(-130, 20)) as MapPoint,
                                mercator.FromGeographic(
                                    new ESRI.ArcGIS.Client.Geometry.MapPoint(-65, 55)) as MapPoint);

                        initialExtent.SpatialReference = new SpatialReference(102100);

                        MyMap.Extent = initialExtent;

                        BingKeyGrid.Visibility = System.Windows.Visibility.Collapsed;
                        RouteGrid.Visibility   = System.Windows.Visibility.Visible;

                        InvalidBingKeyTextBlock.Visibility = System.Windows.Visibility.Collapsed;
                    }
                    else
                    {
                        InvalidBingKeyTextBlock.Visibility = System.Windows.Visibility.Visible;
                    }
                }
                else
                {
                    InvalidBingKeyTextBlock.Visibility = System.Windows.Visibility.Visible;
                }
            };

            webClient.OpenReadAsync(new System.Uri(uri));
        }