private Dictionary <MapPoint, int> GetWayPointId(ESRI.ArcGIS.Client.Geometry.Geometry geometry) { int id = SatrtWayPointId; var polyline = geometry as Polyline; foreach (Shape dynamicShape in ItemsSource) { var wayPointIdMap = new Dictionary <MapPoint, int>(); var foundPolyline = dynamicShape.Geometry as Polyline; if (dynamicShape.ID != Const.ConstConnectionLine && dynamicShape.ID != Const.ConstWayPoint && foundPolyline != null) { if (dynamicShape.Geometry == ShapeSelected.Geometry) { foundPolyline = polyline; } foreach (MapPoint item in foundPolyline.Paths.FirstOrDefault()) { wayPointIdMap.Add(item, id++); } } if (dynamicShape.Geometry == ShapeSelected.Geometry) { return(wayPointIdMap); } } return(null); }
// *********************************************************************************** // * ...Find the nearest Weather Station // *********************************************************************************** private void btnLookupWindDirection_Click(object sender, RoutedEventArgs e) { try { if (_spillLocationGraphicsLayer.Graphics.Count > 0) { List <GPParameter> parameters = new List <GPParameter>(); client.Projection.WebMercator wm = new client.Projection.WebMercator(); ESRI.ArcGIS.Client.Geometry.Geometry geoPoint = wm.ToGeographic(_spillLocationGraphicsLayer.Graphics[0].Geometry); parameters.Add(new GPFeatureRecordSetLayer("Feature_Set", geoPoint)); Geoprocessor findNearestWSGPTask = new Geoprocessor(_findNearestWSURL); findNearestWSGPTask.OutputSpatialReference = _mapWidget.Map.SpatialReference; findNearestWSGPTask.ExecuteCompleted += findNearestWSGPTask_ExecuteCompleted; findNearestWSGPTask.Failed += GeoprocessorTask_Failed; findNearestWSGPTask.ExecuteAsync(parameters); } else { MessageBox.Show("Please add the incident location on the map first!", "Warning"); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); MessageBox.Show("Could not get wind direction!", "Error"); return; } }
} // private void setFormMarkType() private void showMarkForm() { // call from 'editMarker' // fill form from mark, open form log("showMarkForm"); if (currMark == null) { log("currMark is null"); return; } frmAttribs.IsEnabled = false; var mark = currMark; currMark = null; frmAttribs.tbID.Text = mark.Attributes["aID"] as string; frmAttribs.tbName.Text = mark.Attributes["aName"] as string; frmAttribs.tbDescr.Text = mark.Attributes["aDescr"] as string; markType = mark.Attributes["aType"] as string; currGeom = mark.Geometry; setFormMarkType(); currMark = mark; frmAttribs.IsEnabled = true; MapApplication.Current.ShowWindow("Атрибуты пометки", frmAttribs, false, evtBeforeHideAttrForm, evtAfterHideAttrForm, WindowType.Floating); } // private void showMarkForm()
public static Symbol GetDefaultSymbol(this ESRI.ArcGIS.Client.Geometry.Geometry geometry) { if (geometry == null) { return(null); } Type t = geometry.GetType(); if (t == typeof(MapPoint)) { return(DEFAULT_MARKER_SYMBOL); } else if (t == typeof(MultiPoint)) { return(DEFAULT_MARKER_SYMBOL); } else if (t == typeof(Polyline)) { return(DEFAULT_LINE_SYMBOL); } else if (t == typeof(Polygon)) { return(DEFAULT_FILL_SYMBOL); } else if (t == typeof(Envelope)) { return(DEFAULT_FILL_SYMBOL); } return(null); }
private void OnComplete(ESRI.ArcGIS.Client.Geometry.Geometry geometry) { var shapeId = ServiceLocator.Current.GetInstance <IMissionSource>().GenerateTaskId(); if (ItemsSource != null && DrawMode != DrawMode.None) { geometry.SpatialReference = new SpatialReference(Esri.GCS_WGS_1984); ItemsSource.Add(new Shape { Geometry = geometry, ID = shapeId }); var geo = geometry as Polyline; if (geo != null) { var points = geo.Paths.ToList()[0]; var pointList = points.Select(point => new Point(point.X, point.Y)).ToList(); Messenger.Default.Send(new MapWaypointMessenger { Points = pointList, TaskId = shapeId }); } } }
private void AddVertexLabel(ESRI.ArcGIS.Client.Geometry.Geometry geometry) { int index = SatrtWayPointId; var polyline = geometry as Polyline; if (polyline != null) { Dictionary <MapPoint, int> wayPointIdMap = GetWayPointId(geometry); foreach (MapPoint item in polyline.Paths.FirstOrDefault()) { Shape dynamicShape = new Shape(Const.ConstWayPoint); var textSymbol = new TextSymbol() { OffsetX = DefaultWayPointOffsetX, OffsetY = DefaultWayPointOffsetY, FontSize = DefaultWayPointFontSize, Foreground = DefaultWayPointForeground }; if (wayPointIdMap.ContainsKey(item)) { index = wayPointIdMap[item]; } else { index++; } textSymbol.Text = DefaultWayPointPrefix + index.ToString(); dynamicShape.Geometry = item; dynamicShape.Symbol = textSymbol; _vertexGraphicList.Add(dynamicShape); ItemsSource.Add(dynamicShape); } } }
} // public static GraphicsLayer reloadRLData(Map map, string layerID, string layerName) /// <summary> /// Create graphics from xml and restore Symbol for each Graphic in layer /// </summary> /// <param name="gl">redline layer</param> /// <param name="xmlContent">symbols parameters</param> public static void restoreRLGraphics(GraphicsLayer gl, string xmlContent) { // set Graphics symbols gl = VLayer.setContent(gl, xmlContent); foreach (var gr in gl.Graphics) { var t = gr.Attributes["aType"] as string; ESRI.ArcGIS.Client.Geometry.Geometry g = gr.Geometry; if (isText(g, t)) { gr.Symbol = remakeTextSymbol(gr); } else if (isPoint(g)) { gr.Symbol = dicSymbols[t]; } else if (isLine(g)) { gr.Symbol = dicLineSymbols[t]; } else if (isArea(g)) { gr.Symbol = dicAreaSymbols[t]; } else { (string.Format("restoreRLGraphics, unknown Geom type [{0}]", g.GetType())).clog(); continue; } } } // public static void restoreRLGraphics(GraphicsLayer gl, string xmlContent)
} // private void askGeoprocessor(ESRI.ArcGIS.Client.Geometry.Geometry geom) /// <summary> /// Plone service would asked /// </summary> /// <param name="geom"></param> private void sendRequest(ESRI.ArcGIS.Client.Geometry.Geometry geom) { var map = MapApplication.Current.Map; log(string.Format("sendRequest, map spatialReference wkid '{0}', map wkt '{1}'", map.SpatialReference.WKID, map.SpatialReference.WKT)); // prepare url //http://site/rngis/mapsupport/seismicdensity?calcsrid=32&mapsrid=32&coords=1319562.926966302 5039833.556576901,1485013.350625462 5145120.189814549,1485013.350625462 4934546.923339254,1319562.926966302 5039833.556576901 string shape = ""; var poly = (ESRI.ArcGIS.Client.Geometry.Polygon)geom; var rings = poly.Rings; foreach (var pc in rings) { foreach (var mp in pc) { if (shape == "") { ; } else { shape += ", "; } shape += String.Format(new System.Globalization.CultureInfo("en-US"), "{0} {1}", mp.X, mp.Y); } } // config contains http://vdesk.algis.com:8088/rngis/mapsupport/seismicdensity?calcsrid=32&mapsrid=32 string reqUrl = string.Format("{0}&coords={1}", baseUrl, shape); log(string.Format("sendRequest, url '{0}'", reqUrl)); // send request WebClient wc = new WebClient(); Uri u = new Uri(reqUrl, UriKind.RelativeOrAbsolute); wc.OpenReadCompleted += (sender, args) => { if (args.Error != null) { log(String.Format("wc_OpenReadCompleted, error in reading answer, msg [{0}], trace [{1}]", args.Error.Message, args.Error.StackTrace)); MessageBox.Show("Сбой сервиса, подробности см.в отладочной консоли браузера"); return; } try { StreamReader reader = new StreamReader(args.Result); string text = reader.ReadToEnd(); log(string.Format("wc_OpenReadCompleted, resp '{0}'", text)); // [0.032,734.497,22623.010] // Фактически строка формата [сейсмоплотность км/км2,суммарная длина профилей км,очерченная площадь км2] где значения через запятую. var msg = this.parseResponse(text); MessageBox.Show(msg); } catch (Exception ex) { log(String.Format("wc_OpenReadCompleted, parsing failed {0}, {1}", ex.Message, ex.StackTrace)); MessageBox.Show("Сервер вернул неформатный ответ, подробности см.в отладочной консоли браузера"); } }; // wc.OpenReadCompleted wc.OpenReadAsync(u); } // private void sendRequest(ESRI.ArcGIS.Client.Geometry.Geometry geom)
public static bool isArea(ESRI.ArcGIS.Client.Geometry.Geometry g) { if (g.GetType() == typeof(ESRI.ArcGIS.Client.Geometry.Polygon)) { return(true); } return(false); }
public static bool isPoint(ESRI.ArcGIS.Client.Geometry.Geometry g) { if (g.GetType() == typeof(ESRI.ArcGIS.Client.Geometry.MapPoint)) { return(true); } return(false); }
public static bool isText(ESRI.ArcGIS.Client.Geometry.Geometry g, string type) { // markType contains 'текст' and currGeom is point if (isPoint(g)) { if (type.ToUpper().Contains("Текст".ToUpper())) { return(true); } } return(false); }
} // void gl_MouseLeftButtonDown(object sender, GraphicMouseButtonEventArgs e) private void editMarker(Graphic gr) { // call from 'gl_MouseLeftButtonDown' //log(string.Format("editMarker")); var aType = gr.Attributes["aType"]; var aID = gr.Attributes["aID"]; log(string.Format("editMarker, type=[{0}], id=[{1}]", aType, aID)); currGeom = gr.Geometry; currMark = gr; markState = VFlags.Saved; showMarkForm(); } // private void editMarker(Graphic gr)
/// <summary> /// Zoom to resolution extent. /// </summary> /// <param name="extent">New extent.</param> public void ZoomTo(ESRI.ArcGIS.Client.Geometry.Geometry extent) { Debug.Assert(_mapControl != null); // Catching exception from map. try { if (_mapControl.Map.SpatialReferenceID.HasValue) { extent.SpatialReference = new SpatialReference(_mapControl.Map.SpatialReferenceID.Value); } _mapControl.map.ZoomTo(extent); } catch { } }
private void doQuery(ESRI.ArcGIS.Client.Geometry.Geometry geometry) { QueryTask queryTask = new QueryTask("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/BloomfieldHillsMichigan/Parcels/MapServer/2"); queryTask.ExecuteCompleted += QueryTask_ExecuteCompleted; queryTask.Failed += QueryTask_Failed; ESRI.ArcGIS.Client.Tasks.Query query = new ESRI.ArcGIS.Client.Tasks.Query() { Geometry = geometry, SpatialRelationship = SpatialRelationship.esriSpatialRelContains, OutSpatialReference = MyMap.SpatialReference, ReturnGeometry = true }; query.OutFields.Add("*"); queryTask.ExecuteAsync(query); }
/// <summary> /// Do a spatial and where clause combination query /// </summary> /// <param name="where">The where clause used to filter the results</param> /// <param name="geometry">A spatial geometry used to filter the results</param> /// <param name="extraOutFields">List fields with ',' as a separator, which are not included in the QueryLayer.OutputFields, but must be output for other uses.</param> /// <param name="outSRWKID">The Spatial Reference WKID in which the results will be output</param> public void Search(ESRI.ArcGIS.Client.Geometry.Geometry geometry, string where, string extraOutFields, int outSRWKID) { Query filter = new Query(); filter.Where = where; filter.Geometry = geometry; filter.ReturnGeometry = true; filter.OutSpatialReference = new SpatialReference(outSRWKID); filter.SpatialRelationship = SpatialRelationship.esriSpatialRelIntersects; string[] outFields = this.QueryLayer.OutputFields.Split(','); for (int i = 0; i < outFields.Length; i++) { filter.OutFields.Add(outFields[i]); } if (this.LayerInfo != null && !filter.OutFields.Contains(this.LayerInfo.DisplayField)) { filter.OutFields.Add(this.LayerInfo.DisplayField); } if (!string.IsNullOrEmpty(extraOutFields)) { string[] extraFields = extraOutFields.Split(','); for (int i = 0; i < extraFields.Length; i++) { if (!filter.OutFields.Contains(extraFields[i])) { filter.OutFields.Add(extraFields[i]); } } } QueryTask queryTask = new QueryTask(); queryTask.Url = this.QueryLayer.RESTURL; queryTask.Failed += new EventHandler <TaskFailedEventArgs>(QueryTask_Failed); queryTask.ExecuteCompleted += new EventHandler <QueryEventArgs>(QueryTask_ExecuteCompleted); queryTask.ProxyURL = this.QueryLayer.ProxyUrl; queryTask.Token = this.QueryLayer.Token; queryTask.ExecuteAsync(filter); }
private ESRI.ArcGIS.Client.Geometry.Geometry _CreateFrameGeometry() { ESRI.ArcGIS.Client.Geometry.Geometry geometry = null; _end = new ESRI.ArcLogistics.Geometry.Point(_start.Value.X, _start.Value.Y); if (_start.HasValue && _end.HasValue) { ESRI.ArcGIS.Client.Geometry.PointCollection pointCollection = new ESRI.ArcGIS.Client.Geometry.PointCollection(); pointCollection.Add(new MapPoint(_start.Value.X, _start.Value.Y)); pointCollection.Add(new MapPoint(_start.Value.X, _end.Value.Y)); pointCollection.Add(new MapPoint(_end.Value.X, _end.Value.Y)); pointCollection.Add(new MapPoint(_end.Value.X, _start.Value.Y)); pointCollection.Add(new MapPoint(_start.Value.X, _start.Value.Y)); ESRI.ArcGIS.Client.Geometry.Polygon polygon = new ESRI.ArcGIS.Client.Geometry.Polygon(); polygon.Rings.Add(pointCollection); geometry = (ESRI.ArcGIS.Client.Geometry.Geometry)polygon; } return(geometry); }
/// <summary> /// 根据几何要素取得对应的渲染符号 /// </summary> /// <param name="ge"></param> /// <returns></returns> public static ESRI.ArcGIS.Client.Symbols.Symbol GetSymbol(ESRI.ArcGIS.Client.Geometry.Geometry ge, System.Windows.Media.Color color) { if (ge is MapPoint) { return new SimpleMarkerSymbol() { Color = new System.Windows.Media.SolidColorBrush(color), Size = 10, Style = SimpleMarkerSymbol.SimpleMarkerStyle.Circle } } ; else if (ge is ESRI.ArcGIS.Client.Geometry.Polyline) { return new LineSymbol() { Color = new System.Windows.Media.SolidColorBrush(color), Width = 3 } } ; else if (ge is ESRI.ArcGIS.Client.Geometry.Polygon || ge is ESRI.ArcGIS.Client.Geometry.Envelope) { Symbol MySm = new SimpleFillSymbol() { BorderBrush = new System.Windows.Media.SolidColorBrush(color) { }, BorderThickness = 1, Fill = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.White) { Opacity = 0.4 } }; return(MySm); } return(null); }
private void FindWebMapsButton_Click(object sender, RoutedEventArgs e) { webmapGraphicsLayer.Graphics.Clear(); // Search envelope must be in geographic (WGS84). Convert the current map extent from Web Mercator // to geographic. ESRI.ArcGIS.Client.Geometry.Geometry geom = mercator.ToGeographic(MyMap.Extent); SpatialSearchParameters parameters = new SpatialSearchParameters { Limit = String.IsNullOrEmpty(resultLimit.Text) == true ? 15 : Convert.ToInt32(resultLimit.Text), SearchExtent = geom.Extent, QueryString = String.Format("{0} And type:Web Map", searchText.Text) }; arcgisPortal.SearchItemsAsync(parameters, (result, error) => { if (error == null) { // Set the ItemsSource for the Listbox to an IEnumerable of ArcGISPortalItems. // Bindings setup in the Listbox item template in XAML will enable the discovery and // display individual result items. WebMapsListBox.ItemsSource = result.Results; // For each web map returned, add the center (point) of the web map extent as a graphic. // Add the ArcGISPortalItem instance as an attribute. This will be used to select graphics // in the map. foreach (var item in result.Results) { Graphic graphic = new Graphic(); graphic.Attributes.Add("PortalItem", item); MapPoint extentCenter = item.Extent.GetCenter(); graphic.Geometry = new MapPoint(extentCenter.X, extentCenter.Y, new SpatialReference(4326)); webmapGraphicsLayer.Graphics.Add(graphic); } } }); }
} // private void editMarker(Graphic gr) private void restoreRLLayer(GraphicsLayer gl, string xmlContent) { // set Graphics symbols log("restoreRLLayer, ..."); gl = VLayer.setContent(gl, xmlContent); foreach (var g in gl.Graphics) { var typ = g.Attributes["aType"] as string; currGeom = g.Geometry; markType = typ; if (isText()) { g.Symbol = remakeTextSymbol(g); } else if (isPoint(g.Geometry)) { g.Symbol = dicSymbols[typ]; } else if (isLine(g.Geometry)) { g.Symbol = dicLineSymbols[typ]; } else if (isArea(g.Geometry)) { g.Symbol = dicAreaSymbols[typ]; } else { log(string.Format("unknown Geom type [{0}]", g.Geometry.GetType())); continue; } currGeom = null; markType = null; } } // private void restoreRLLayer(GraphicsLayer gl, string xmlContent)
} // evtOnDrawEnabledChanged /// <summary> /// Call from Map when user stop draw current mark. /// Example says: /// ESRI.ArcGIS.Client.Graphic graphic = new ESRI.ArcGIS.Client.Graphic() /// { Geometry = args.Geometry, Symbol = _activeSymbol }; /// graphicsLayer.Graphics.Add(graphic); /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void evtDrawComplete(object sender, DrawEventArgs e) { log(string.Format("VRedlineImpl.evtDrawComplete, SR={0}", e.Geometry.SpatialReference.WKID)); currGeom = e.Geometry; markState = VFlags.New; frmElement.disabledDrawInternally = true; draw.DrawMode = DrawMode.None; draw.IsEnabled = false; try { //init form currMark = null; frmAttribs.IsEnabled = false; frmAttribs.tbID.Text = Guid.NewGuid().ToString(); frmAttribs.tbName.Text = "Название"; frmAttribs.tbDescr.Text = "Описание"; // symbols setFormMarkType(); frmAttribs.IsEnabled = true; // new mark from form data currMark = newMark(); // add mark to layer setSelectedSymbol(); //showMarkForm MapApplication.Current.ShowWindow("Атрибуты пометки", frmAttribs, false, evtBeforeHideAttrForm, evtAfterHideAttrForm, WindowType.Floating); } catch (Exception ex) { string msg = string.Format("Сбой создания маркера: \n [{0}]", ex.Message); MessageBox.Show(msg); log(msg); } } // private void evtDrawComplete(object sender, DrawEventArgs e)
/// <summary> /// Initializes a <see cref="Map"/> object based on a web map /// </summary> /// <param name="map">The map to initialize</param> /// <param name="e">The <see cref="GetMapCompletedEventArgs"/> object containing the web map's information. /// This is the event args type returned to the <see cref="Document.GetMapCompleted"/> event.</param> public static void InitializeFromWebMap(this Map map, GetMapCompletedEventArgs e, EventHandler <EventArgs> onLayerInitFailed = null) { map.Layers.Clear(); if (e.Map.Extent != null && e.Map.Extent.SpatialReference != null && e.Map.Extent.SpatialReference.IsWebMercator() && double.IsNegativeInfinity(e.Map.Extent.YMin) && double.IsPositiveInfinity(e.Map.Extent.YMax)) { e.Map.Extent.YMin = double.NaN; e.Map.Extent.YMax = double.NaN; } map.Extent = e.Map.Extent; List <Layer> layers = new List <Layer>(); List <Layer> basemapLayers = new List <Layer>(); IEnumerable <Layer> allLayers = e.Map.Layers.FlattenLayers(); List <string> featureCollectionLayerNames = new List <string>(); // Create collection of layers to add to the map based on the layers in the web map foreach (Layer layer in allLayers) { // Set ShowLegend to true for each layer. The framework handles layer visibility // in MapContents otherwise. layer.ShowLegend = true; if (layer is ESRI.ArcGIS.Client.Bing.TileLayer) { ESRI.ArcGIS.Mapping.Core.LayerExtensions.SetUsesBingAppID((ESRI.ArcGIS.Client.Bing.TileLayer)layer, true); } layer.ProcessWebMapProperties(e.DocumentValues); // Check whether any layers flagged for adding to the map have the same ID as the current one. Layers // with the same ID represent feature collections that show up as part of the same layer in the online // viewers, but are actually serialized as separate layers. if (!(layer is GraphicsLayer) || !layers.Any(l => l.ID == layer.ID || l.DisplayName == layer.DisplayName || featureCollectionLayerNames.Contains(layer.DisplayName))) { if ((bool)(layer.GetValue(ESRI.ArcGIS.Client.WebMap.Document.IsBaseMapProperty))) { basemapLayers.Add(layer); } layers.Add(layer); } else // Layer belongs to a multi-layer feature collection. Combine with layer already included in the list. { GraphicsLayer currentLayer = layers.First(l => l.ID == layer.ID || l.DisplayName == layer.DisplayName || featureCollectionLayerNames.Contains(layer.DisplayName)) as GraphicsLayer; GraphicsLayer newLayer = layer as GraphicsLayer; if (newLayer != null && newLayer.Graphics.Count > 0) { if (currentLayer != null && LayerExtensions.GetGeometryType(currentLayer) == LayerExtensions.GetGeometryType(newLayer)) { // Layers have the same geometry type - just copy the features from one to the other newLayer.Graphics.MoveTo(currentLayer.Graphics); } else if (currentLayer != null && currentLayer.Graphics.Count == 0) { // Geometry types don't match, but the layer already added to the list doesn't have any // features graphics. Override the renderer from the added layer with that from the current // one and copy over the features in the currently layer. currentLayer.Renderer = newLayer.Renderer; newLayer.Graphics.MoveTo(currentLayer.Graphics); } else { // Geometry types don't match, but both layers have features. We don't want to put the // features in the same layer because that eliminates the ability to configure the layer's // renderer. So create separate layers. // The layers will have the same name by default. To avoid having multiple layers with the // same name, append a suffix that indicates the geometry type, i.e. points, lines, or areas. if (currentLayer != null) { currentLayer.AppendGeometryToLayerName(); featureCollectionLayerNames.Add(layer.DisplayName); } newLayer.AppendGeometryToLayerName(); // The layers will have the same ID by default, which can cause unexpected behavior. // So give one of them a new ID. newLayer.ID = Guid.NewGuid().ToString("N"); layers.Add(newLayer); // Look in the web map's layers for other layers that have the same geometry type as the new // layer. Since the new layer has a new ID, and the logic here relies on ID to determine // whether to merge with another layer, we need to update the IDs of the layers yet to be // processed to match the new ID. IEnumerable <Layer> others = allLayers.Where( l => (l.ID == layer.ID) && LayerExtensions.GetGeometryType((GraphicsLayer)l) == LayerExtensions.GetGeometryType((GraphicsLayer)layer)); foreach (GraphicsLayer gLayer in others) { gLayer.ID = newLayer.ID; } } } } } #region Get Basemap Title if (basemapLayers.Count > 0 && e.DocumentValues.ContainsKey("baseMap")) { IDictionary <string, object> dict = e.DocumentValues["baseMap"] as IDictionary <string, object>; if (dict != null) { string baseMapTitle = "Basemap"; if (dict.ContainsKey("title")) { baseMapTitle = dict["title"] as string; if (!string.IsNullOrWhiteSpace(baseMapTitle)) { LayerExtensions.SetLayerName(basemapLayers[0], baseMapTitle); } } //Mark reference layers if (basemapLayers.Count > 1) { for (int i = 1; i < basemapLayers.Count; i++) { LayerExtensions.SetIsReferenceLayer(basemapLayers[i], true); //Do not show in map contents ESRI.ArcGIS.Client.Extensibility.LayerProperties.SetIsVisibleInMapContents(basemapLayers[i], false); } } } } #endregion e.Map.Layers.Clear(); foreach (Layer layer in layers) { if (onLayerInitFailed != null) { layer.InitializationFailed += onLayerInitFailed; } map.Layers.Add(layer); } #region Get map items and add any notes if (e.DocumentValues != null) { foreach (KeyValuePair <string, object> pair in e.DocumentValues) { if (pair.Key == "MapItems") { List <GraphicsLayer> noteLayers = new List <GraphicsLayer>(); #region Get note layers List <object> items = pair.Value as List <object>; if (items == null) { continue; } foreach (var item in items) { IDictionary <string, object> dict = item as IDictionary <string, object>; if (dict != null) { #region If note, add to notelayers if (dict.ContainsKey("__type") && dict["__type"].ToString() == "Note:#ESRI.ArcGIS.Mapping.Controls.ArcGISOnline") { if (dict.ContainsKey("Geometry") && dict.ContainsKey("Name")) { string name = dict["Name"] as string; IDictionary <string, object> gDict = dict["Geometry"] as IDictionary <string, object>; if (gDict == null) { continue; } ESRI.ArcGIS.Client.Geometry.Geometry geometry = null; if (gDict.ContainsKey("__type") && gDict["__type"] is string) { if (gDict["__type"].ToString() == "point:#ESRI.ArcGIS.Client.Geometry") { geometry = CreatePoint(gDict); } else if (gDict["__type"].ToString() == "Polyline:#ESRI.ArcGIS.Client.Geometry") { if (gDict.ContainsKey("paths") && gDict["paths"] is List <object> ) { List <object> paths = gDict["paths"] as List <object>; Polyline line = new Polyline(); if (paths != null) { foreach (object path in paths) { List <object> points = path as List <object>; ESRI.ArcGIS.Client.Geometry.PointCollection pts = new ESRI.ArcGIS.Client.Geometry.PointCollection(); foreach (object point in points) { if (point is IDictionary <string, object> ) { pts.Add(CreatePoint(point as IDictionary <string, object>)); } } line.Paths.Add(pts); } geometry = line; } } } else if (gDict["__type"].ToString() == "Polygon:#ESRI.ArcGIS.Client.Geometry") { if (gDict.ContainsKey("rings") && gDict["rings"] is List <object> ) { List <object> rings = gDict["rings"] as List <object>; Polygon gon = new Polygon(); if (rings != null) { foreach (object ring in rings) { List <object> points = ring as List <object>; ESRI.ArcGIS.Client.Geometry.PointCollection pts = new ESRI.ArcGIS.Client.Geometry.PointCollection(); foreach (object point in points) { if (point is IDictionary <string, object> ) { pts.Add(CreatePoint(point as IDictionary <string, object>)); } } gon.Rings.Add(pts); } geometry = gon; } } } } if (geometry != null && gDict.ContainsKey("spatialReference")) { IDictionary <string, object> srDict = gDict["spatialReference"] as IDictionary <string, object>; if (srDict != null) { if (srDict.ContainsKey("wkid")) { geometry.SpatialReference = new SpatialReference() { WKID = Int32.Parse(srDict["wkid"].ToString()) } } ; else if (srDict.ContainsKey("wkt")) { geometry.SpatialReference = new SpatialReference() { WKT = srDict["wkt"].ToString() } } ; } } if (geometry != null) { GraphicsLayer glayer = ESRI.ArcGIS.Mapping.Controls.ArcGISOnline.Note.CreateGraphicsLayer(name, new Graphic() { Geometry = geometry }, map); if (dict.ContainsKey("Visible")) { bool visible = true; try { visible = (bool)(dict["Visible"]); } catch { } glayer.Visible = visible; } noteLayers.Add(glayer); } } } #endregion } } if (noteLayers.Count > 0) { for (int i = noteLayers.Count - 1; i >= 0; i--) { if (noteLayers[i] != null) { map.Layers.Add(noteLayers[i]); } } } #endregion } } } #endregion }
public void SetGeometry(Geometry g) { try { BaseGeometry = g; Geometry = g; } catch (Exception e) { // FIXME TODO Deal with exception! } }
/// <summary> /// Clones a given <see cref="ESRI.ArcGIS.Client.Geometry"/> /// </summary> internal static ESRI.ArcGIS.Client.Geometry.Geometry Clone(this ESRI.ArcGIS.Client.Geometry.Geometry geometry) { return(((dynamic)geometry).Clone()); }
private void ShowInfoWinByClickOrTouch(Point screenPnt) { GeneralTransform generalTransform = mainMap.TransformToVisual(Application.Current.MainWindow); Point transformScreenPnt = generalTransform.Transform(screenPnt); foreach (FeatureLayer featureLayer in PublicParams.listFLayer) { if (featureLayer != null && featureLayer.Visible == true) { IEnumerable <Graphic> selectedFLayer = featureLayer.FindGraphicsInHostCoordinates(transformScreenPnt); foreach (Graphic graphic in selectedFLayer) { //mainInfoWindow.Anchor = e.MapPoint; mainInfoWindow.Anchor = graphic.Geometry as MapPoint; mainInfoWindow.IsOpen = true; mainInfoWindow.ContentTemplate = this.FindResource("DT" + graphic.Attributes["Class"].ToString()) as DataTemplate; mainInfoWindow.Content = graphic.Attributes; MapMethods.SendOpenInfoWindow(graphic); return; } } } GraphicsLayer graphicsLayerPoliceCar = MapLayers.GetGraphicsLayerByID(PublicParams.gLayerPoliceCarGPS); if (graphicsLayerPoliceCar != null && graphicsLayerPoliceCar.Visible != false) { IEnumerable <Graphic> selectedGraphics = graphicsLayerPoliceCar.FindGraphicsInHostCoordinates(transformScreenPnt); foreach (Graphic graphic in selectedGraphics) { mainInfoWindow.Anchor = graphic.Geometry as MapPoint; mainInfoWindow.IsOpen = true; mainInfoWindow.ContentTemplate = this.FindResource("DTPoliceCar") as DataTemplate; mainInfoWindow.Content = graphic.Attributes; MapMethods.SendOpenInfoWindow(graphic); return; } } GraphicsLayer graphicsLayerCase = MapLayers.GetGraphicsLayerByID(PublicParams.gLayerCase); if (graphicsLayerCase != null && graphicsLayerCase.Visible == true) { IEnumerable <Graphic> selectedGraphics = graphicsLayerCase.FindGraphicsInHostCoordinates(transformScreenPnt); foreach (Graphic graphic in selectedGraphics) { //LPY 2016-4-14 添加 新案件点周围视频点自动查找和播放 MapLayers.ClearGLayerByID(PublicParams.gLayerSearchCamerasNearCrime);//清空图层 MapMethods.SendClearGraphicsLayerByID(PublicParams.gLayerSearchCamerasNearCrime); ESRI.ArcGIS.Client.Geometry.Geometry geoSearch = MapMethods.GetEllipseGeometry(PublicParams.SearchRadius / (106 * 1000), graphic.Geometry as MapPoint); GeoServHelper gsh = new GeoServHelper(); gsh.ExecuteAsyncQueryForCasePoint(geoSearch, PublicParams.urlCamerasLayer); PublicParams.pubCanvasChild1.BeginStoryboard(App.Current.FindResource("StoryboardForPadCamerasOpen") as System.Windows.Media.Animation.Storyboard); MapMethods.SendOpenPadVideos();//打开视频背景板 Graphic gSearch = new Graphic() { Symbol = PublicParams.symbolSearchCameras, Geometry = geoSearch }; MapLayers.AddGraphicToGLayerByLayerID(gSearch, PublicParams.gLayerSearchCamerasNearCrime); MapMethods.SendGraphicSearchCameras(gSearch); } } }
/// <summary> /// Do a spatial query /// </summary> /// <param name="where">The where clause used to filter the results</param> /// <param name="geometry">A spatial geometry used to filter the results</param> /// <param name="extraOutFields">List fields with ',' as a separator, which are not included in the QueryLayer.OutputFields, but must be output for other uses.</param> /// <param name="outSRWKID">The Spatial Reference WKID in which the results will be output</param> public void Search(ESRI.ArcGIS.Client.Geometry.Geometry geometry, string extraOutFields, int outSRWKID) { Search(geometry, "", extraOutFields, outSRWKID); }
/// <summary> /// Do a spatial query /// </summary> /// <param name="geometry">A spatial geometry used to filter the results</param> /// <param name="outSRWKID">The Spatial Reference WKID in which the results will be output</param> public void Search(ESRI.ArcGIS.Client.Geometry.Geometry geometry, int outSRWKID) { Search(geometry, "", "", outSRWKID); }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { FeatureLayer featureLayer = value as FeatureLayer; if (featureLayer != null) { if (featureLayer.IsReadOnly) { if (featureLayer.Graphics.Count == 0) { return(new BitmapImage(new Uri("/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/layer.png", UriKind.Relative))); } else { ESRI.ArcGIS.Client.Geometry.Geometry g = featureLayer.Graphics[0].Geometry; if (g == null) { return(new BitmapImage(new Uri("/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/layer.png", UriKind.Relative))); } if (g is MapPoint) { return(new BitmapImage(new Uri("/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/point.png", UriKind.Relative))); } else if (g is ESRI.ArcGIS.Client.Geometry.Polyline) { return(new BitmapImage(new Uri("/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/line.png", UriKind.Relative))); } else if (g is ESRI.ArcGIS.Client.Geometry.Polygon) { return(new BitmapImage(new Uri("/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/poly.png", UriKind.Relative))); } else { return(new BitmapImage(new Uri("/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/layer.png", UriKind.Relative))); } } } else { return(new BitmapImage(new Uri("/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/editableLayer.png", UriKind.Relative))); } } if (value is GeoRssLayer || value is CustomGeoRssLayer) { return(new BitmapImage(new Uri("/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/geoRssFeed.png", UriKind.Relative))); } if (value is HeatMapLayer) { return(new BitmapImage(new Uri("/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/heatMap.png", UriKind.Relative))); } if (value is CustomGraphicsLayer) // This would be the case for SharePoint layer { return(new BitmapImage(new Uri("/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/view.png", UriKind.Relative))); } if (value is WmsLayer) { return(new BitmapImage(new Uri("/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/wms.png", UriKind.Relative))); } if (value is ArcGISDynamicMapServiceLayer || value is ArcGISTiledMapServiceLayer) { return(new BitmapImage(new Uri("/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/mapService.png", UriKind.Relative))); } if (value is TileLayer) { return(new BitmapImage(new Uri("/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/bing16.png", UriKind.Relative))); } if (value is OpenStreetMapLayer) { return(new BitmapImage(new Uri("/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/OpenStreetMap16.png", UriKind.Relative))); } if (value is ArcGISImageServiceLayer) { return(new BitmapImage(new Uri("/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/imageService.png", UriKind.Relative))); } GraphicsLayer graphicsLayer = value as GraphicsLayer; if (graphicsLayer != null) // Generic graphics layer { if (graphicsLayer.Graphics.Count == 0) { return(new BitmapImage(new Uri("/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/layer.png", UriKind.Relative))); } else { ESRI.ArcGIS.Client.Geometry.Geometry g = graphicsLayer.Graphics[0].Geometry; if (g == null) { return(new BitmapImage(new Uri("/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/layer.png", UriKind.Relative))); } if (g is MapPoint) { return(new BitmapImage(new Uri("/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/point.png", UriKind.Relative))); } else if (g is ESRI.ArcGIS.Client.Geometry.Polyline) { return(new BitmapImage(new Uri("/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/line.png", UriKind.Relative))); } else if (g is ESRI.ArcGIS.Client.Geometry.Polygon) { return(new BitmapImage(new Uri("/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/poly.png", UriKind.Relative))); } else { return(new BitmapImage(new Uri("/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/layer.png", UriKind.Relative))); } } } return(value); }
private void ShowMeasurementResult(bool showLabel, ScaleLine.ScaleLineUnit outUnits) { showLabel = showLabel && CheckResultOnMap.IsChecked.Value; if (outUnits != ScaleLine.ScaleLineUnit.Undefined) { resultUnits = outUnits; } if (measurementMode == MODE_LENGTH && geometryService.LengthsLastResult != null) { // Length in meters double length = geometryService.LengthsLastResult[0] * UnitsHelper.GetConversionToMeter(resultUnits); // Length in selected units MeasurementUnits lenUnits = (ListLengthUnits.SelectedItem as ComboBoxItem).Tag as MeasurementUnits; TextLengthResult.Text = string.Format("{0}", Math.Round(length * lenUnits.Conversion, 3)); if (showLabel && this.GraphicsLayer.Graphics.Count > 0) { int k = this.GraphicsLayer.Graphics.Count - 1; ESRI.ArcGIS.Client.Geometry.Geometry geometry = this.GraphicsLayer.Graphics[k].Geometry; string label = string.Format("Length: {0} {1}", TextLengthResult.Text, lenUnits.Abbreviation); Graphic lblGraphic = new Graphic() { Geometry = geometry.Extent.GetCenter(), Symbol = new TextSymbol() { Text = label, OffsetX = 30, OffsetY = 15, FontSize = 12.0, FontFamily = new FontFamily("Arial Black"), Foreground = new SolidColorBrush(Color.FromArgb(0xFF, 0x00, 0x00, 0xFF)) } }; AddGraphic(lblGraphic); } } else if (measurementMode == MODE_AREA && geometryService.AreasAndLengthsLastResult != null) { // Length in meters double length = geometryService.AreasAndLengthsLastResult.Lengths[0] * UnitsHelper.GetConversionToMeter(resultUnits); // Area in square meters double area = Math.Abs(geometryService.AreasAndLengthsLastResult.Areas[0]) * Math.Pow(UnitsHelper.GetConversionToMeter(resultUnits), 2); // Length in selected units MeasurementUnits lenUnits = (ListLengthUnits.SelectedItem as ComboBoxItem).Tag as MeasurementUnits; TextLengthResult.Text = string.Format("{0}", Math.Round(length * lenUnits.Conversion, 3)); // Area in selected units MeasurementUnits areaUnits = (ListAreaUnits.SelectedItem as ComboBoxItem).Tag as MeasurementUnits; TextAreaResult.Text = string.Format("{0}", Math.Round(area * areaUnits.Conversion, 3)); if (showLabel && this.GraphicsLayer.Graphics.Count > 0) { int k = this.GraphicsLayer.Graphics.Count - 1; ESRI.ArcGIS.Client.Geometry.Geometry geometry = this.GraphicsLayer.Graphics[k].Geometry; string label = string.Format("Parimeter: {0} {1}\nArea: {2} {3}", TextLengthResult.Text, lenUnits.Abbreviation, TextAreaResult.Text, areaUnits.Abbreviation); Graphic lblGraphic = new Graphic() { Geometry = geometry.Extent.GetCenter(), Symbol = new TextSymbol() { Text = label, OffsetX = 50, OffsetY = 15, FontSize = 12.0, FontFamily = new FontFamily("Arial Black"), Foreground = new SolidColorBrush(Color.FromArgb(0xFF, 0x00, 0x00, 0x99)) } }; AddGraphic(lblGraphic); } } this.IsBusy = false; }
/// <summary> /// Zoom to resolution extent. /// </summary> /// <param name="extent">New extent.</param> public void ZoomTo(ESRI.ArcGIS.Client.Geometry.Geometry extent) { _mapExtentManager.ZoomTo(extent); }
void addInput(ESRI.ArcGIS.Client.Geometry.Geometry geometry) { GraphicsLayer layer = getLayer(); #region Create layer if not already there and add to map if (layer == null) { InputLayerID = Guid.NewGuid().ToString("N"); layer = new GraphicsLayer(); if (config.Layer != null) { layer.Renderer = config.Layer.Renderer; Core.LayerExtensions.SetFields(layer, Core.LayerExtensions.GetFields(config.Layer)); Core.LayerExtensions.SetGeometryType(layer, Core.LayerExtensions.GetGeometryType(config.Layer)); Core.LayerExtensions.SetDisplayField(layer, Core.LayerExtensions.GetDisplayField(config.Layer)); Core.LayerExtensions.SetPopUpsOnClick(layer, Core.LayerExtensions.GetPopUpsOnClick(config.Layer)); LayerProperties.SetIsPopupEnabled(layer, LayerProperties.GetIsPopupEnabled(config.Layer)); } layer.ID = InputLayerID; layer.SetValue(MapApplication.LayerNameProperty, string.IsNullOrEmpty(config.LayerName) ? string.IsNullOrEmpty(config.Label) ? config.Name : config.Label : config.LayerName); layer.Opacity = config.Opacity; Map.Layers.Add(layer); } #endregion #region Add geometry to layer if (config.GeometryType == Core.GeometryType.MultiPoint) // Special handling for MultiPoint geometry { if (layer.Graphics.Count == 0) { // Create a new MultiPoint geometry and add the passed-in point to it var multipoint = new MultiPoint() { SpatialReference = geometry.SpatialReference }; multipoint.Points.Add((MapPoint)geometry); var g = new Graphic() { Geometry = multipoint }; layer.Graphics.Add(g); } else { // Get the sketch graphic's MultiPoint geometry and add the passed-in point to it var multipoint = (MultiPoint)layer.Graphics[0].Geometry; multipoint.Points.Add((MapPoint)geometry); layer.Refresh(); } } else { Graphic g = new Graphic() { Geometry = geometry }; layer.Graphics.Add(g); } #endregion }
void GeometryService_BufferCompleted(object sender, GraphicsEventArgs args) { IList <Graphic> results = args.Results; if (results == null || results.Count < 1) { return; } FindNearbyEventArgs eventArgs = args.UserState as FindNearbyEventArgs; if (eventArgs == null) { return; } GraphicsLayer targetGraphicsLayer = eventArgs.SelectedLayer; if (targetGraphicsLayer == null) { return; } #region Draw the buffer graphics layer GraphicsLayer bufferGraphicsLayer = new GraphicsLayer() { ID = eventArgs.EventId }; // Add the circle graphic Graphic circleGraphic = results[0]; circleGraphic.Attributes.Add(Resources.Strings.BufferDistance, string.Format("{0} {1}", eventArgs.Distance, eventArgs.LinearUnit.ToString())); SimpleFillSymbol defaultBufferSymbol = new SimpleFillSymbol() { BorderBrush = new SolidColorBrush(Colors.Blue), BorderThickness = 1, Fill = new SolidColorBrush(new Color() { A = (byte)102, R = (byte)255, G = (byte)0, B = (byte)0 }) }; SimpleRenderer simpleRenderer = new SimpleRenderer() { Symbol = defaultBufferSymbol, }; bufferGraphicsLayer.Renderer = simpleRenderer; Collection <FieldInfo> layerFields = Core.LayerExtensions.GetFields(bufferGraphicsLayer); if (layerFields != null) { layerFields.Add(new FieldInfo() { DisplayName = Resources.Strings.BufferDistance, Name = Resources.Strings.BufferDistance, FieldType = FieldType.Text }); } bufferGraphicsLayer.Graphics.Add(circleGraphic); #endregion Graphic graphicCircle = results[0]; if (graphicCircle != null) { ESRI.ArcGIS.Client.Geometry.Geometry graphicCircleGeometry = graphicCircle.Geometry; if (graphicCircleGeometry != null) { // Ensure that atleast the first graphic of the graphics layer has a spatial reference set // because ESRI.ArcGIS.Client.Tasks checks it if (targetGraphicsLayer.Graphics.Count > 0) { if (targetGraphicsLayer.Graphics[0].Geometry != null && targetGraphicsLayer.Graphics[0].Geometry.SpatialReference == null && Map != null) { targetGraphicsLayer.Graphics[0].Geometry.SpatialReference = Map.SpatialReference; } } // The extent of the result layer should be the extent of the circle if (Map != null) { Map.ZoomTo(expandExtent(graphicCircleGeometry.Extent)); } relationAsync(GeometryServiceUrl, targetGraphicsLayer.Graphics.ToList(), results, new object[] { eventArgs, bufferGraphicsLayer }); } } }