private async void Initialize() { // Create new Map with basemap Map myMap = new Map(Basemap.CreateTopographic()); // Create a MapPoint the map should zoom to MapPoint mapPoint = new MapPoint( -13630484, 4545415, SpatialReferences.WebMercator); // Set the initial viewpoint for map myMap.InitialViewpoint = new Viewpoint(mapPoint, 90000); // Provide used Map to the MapView MyMapView.Map = myMap; // Create the uri for the feature service Uri featureServiceUri = new Uri( "https://sampleserver6.arcgisonline.com/arcgis/rest/services/SF311/FeatureServer/0"); // Initialize feature table using a url to feature server url ServiceFeatureTable featureTable = new ServiceFeatureTable(featureServiceUri); // Initialize a new feature layer based on the feature table _featureLayer = new FeatureLayer(featureTable); //Add the feature layer to the map myMap.OperationalLayers.Add(_featureLayer); // TODO: https://github.com/Esri/arcgis-runtime-samples-xamarin/issues/96 if (Device.OS == TargetPlatform.iOS || Device.OS == TargetPlatform.Other) { await _featureLayer.RetryLoadAsync(); } }
public FeatureLayerHelper(Map map, string name, FeatureLayer.QueryMode mode, bool visible) { this.FeatureLayer = (FeatureLayer)map.Layers.FirstOrDefault(layer => (layer is FeatureLayer) && ((FeatureLayer)layer).DisplayName.ToLower().Equals(name.ToLower())); if (this.FeatureLayer == null) { Log.Trace("Could not find layer with name '" + name + "'"); return; } this.FeatureLayer.Visible = visible; this.FeatureLayer.Mode = mode; this.FeatureLayer.AutoSave = false; this.Fields = QueryLayerFields(this.FeatureLayer); if (this.Fields == null) Log.Trace("Could not query layer fields '" + name + "'"); this.FeatureLayer.Initialized += FeatureLayer_Initialized; this.FeatureLayer.Initialize(); this.FeatureLayer.BeginSaveEdits += FeatureLayer_BeginSaveEdits; this.FeatureLayer.EndSaveEdits += FeatureLayer_EndSaveEdits; this.FeatureLayer.UpdateCompleted += FeatureLayer_UpdateCompleted; this.FeatureLayer.UpdateFailed += FeatureLayer_UpdateFailed; this.FeatureLayer.SaveEditsFailed += FeatureLayer_SaveEditsFailed; }
public EditingCodedValueDomains() { InitializeComponent(); editor = LayoutRoot.Resources["MyEditor"] as Editor; featureLayer = MyMap.Layers["RecreationFacilities"] as FeatureLayer; }
/// <summary> /// マップビュー初期化時のイベント ハンドラ /// </summary> private async void mapView_Initialized(object sender, EventArgs e) { try { //ローカル ジオデータベース(Runtime コンテンツ)を読み込みマップに追加 var gdb = await Geodatabase.OpenAsync(GDB_PATH); foreach (var table in gdb.FeatureTables) { var flayer = new FeatureLayer() { ID = table.Name, DisplayName = table.Name, FeatureTable = table }; //フィーチャ レイヤーのラベル プロパティを初期化し赤ラベルと青ラベルを設定 flayer.Labeling = new LabelProperties(); var redLabelClass = this.layoutRoot.Resources["redLabel"] as AttributeLabelClass; flayer.Labeling.LabelClasses.Add(redLabelClass); var blueLabelClass = this.layoutRoot.Resources["blueLabel"] as AttributeLabelClass; flayer.Labeling.LabelClasses.Add(blueLabelClass); //マップにフィーチャ レイヤーを追加 mapView.Map.Layers.Add(flayer); } //すべてのレイヤーを初期化 await mapView.LayersLoadedAsync(); } catch(Exception ex) { MessageBox.Show(string.Format("フィーチャ レイヤーの作成に失敗しました: {0}", ex.Message)); } }
protected override void OnClick() { // // TODO: Sample code showing how to access button host // ArcMap.Application.CurrentTool = null; //Create the workspace and then create the feature class. Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); IWorkspaceFactory workspaceFactory = Activator.CreateInstance(factoryType) as IWorkspaceFactory; IWorkspace workspace = workspaceFactory.OpenFromFile(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), @"Data\testData.gdb").ToString(), 0); IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace; IFeatureClass createdFeatureClass = CreateFeatureClass("Reddies", featureWorkspace); //Generate data for the feature class BoboDataGeneration(createdFeatureClass, featureWorkspace); //Create the layer and add it to the display IFeatureLayer layer = new FeatureLayer(); layer.FeatureClass = createdFeatureClass; layer.Name = createdFeatureClass.AliasName; layer.DisplayField = "HistoField"; RenderFeatures(layer); //Add the layer to the map ArcMap.Document.FocusMap.AddLayer(layer); }
private async void Initialize() { // Create new Map with basemap Map myMap = new Map(Basemap.CreateTopographic()); // Create and set initial map location MapPoint initialLocation = new MapPoint( -13630484, 4545415, SpatialReferences.WebMercator); myMap.InitialViewpoint = new Viewpoint(initialLocation, 500000); // Create uri to the used feature service var serviceUri = new Uri( "http://sampleserver6.arcgisonline.com/arcgis/rest/services/SF311/FeatureServer/0"); // Create feature table for the incident feature service _incidentsFeatureTable = new ServiceFeatureTable(serviceUri); // Define the request mode _incidentsFeatureTable.FeatureRequestMode = FeatureRequestMode.ManualCache; // When feature table is loaded, populate data _incidentsFeatureTable.LoadStatusChanged += OnLoadedPopulateData; // Create FeatureLayer that uses the created table FeatureLayer incidentsFeatureLayer = new FeatureLayer(_incidentsFeatureTable); // Add created layer to the map myMap.OperationalLayers.Add(incidentsFeatureLayer); // Assign the map to the MapView _myMapView.Map = myMap; }
private async void Initialize() { // Create new Map with basemap Map myMap = new Map(Basemap.CreateTopographic()); // Create a mappoint the map should zoom to MapPoint mapPoint = new MapPoint(-13630484, 4545415, SpatialReferences.WebMercator); // Set the initial viewpoint for map myMap.InitialViewpoint = new Viewpoint(mapPoint, 90000); // Provide used Map to the MapView _myMapView.Map = myMap; // Create the uri for the feature service Uri featureServiceUri = new Uri("http://sampleserver6.arcgisonline.com/arcgis/rest/services/SF311/FeatureServer/0"); // Initialize feature table using a url to feature server url ServiceFeatureTable featureTable = new ServiceFeatureTable(featureServiceUri); // Initialize a new feature layer based on the feature table _featureLayer = new FeatureLayer(featureTable); //Add the feature layer to the map myMap.OperationalLayers.Add(_featureLayer); }
private async void CreateFeatureLayers() { try { var gdb = await Geodatabase.OpenAsync(GDB_PATH); Envelope extent = null; foreach (var table in gdb.FeatureTables) { var flayer = new FeatureLayer() { ID = table.Name, DisplayName = table.Name, FeatureTable = table }; if (!Geometry.IsNullOrEmpty(table.ServiceInfo.Extent)) { if (Geometry.IsNullOrEmpty(extent)) extent = table.ServiceInfo.Extent; else extent = extent.Union(table.ServiceInfo.Extent); } MyMapView.Map.Layers.Add(flayer); } await MyMapView.SetViewAsync(extent.Expand(1.10)); } catch (Exception ex) { MessageBox.Show("Error creating feature layer: " + ex.Message, "Samples"); } }
private async void AddLocalToMap(object sender, RoutedEventArgs e) { try { _gdb = await Geodatabase.OpenAsync(GDB_PATH); foreach (var table in _gdb.FeatureTables) { try { var flayer = new FeatureLayer { ID = table.Name, DisplayName = table.Name, FeatureTable = table }; MyMapView.Map.Layers.Add(flayer); MyMapView.SetView(flayer.FullExtent); } catch (Exception ex) { Console.WriteLine("Error creating feature layer: " + ex.Message, "Samples"); } } } catch (Exception ex) { Console.WriteLine("Error creating feature layer: " + ex.Message, "Samples"); } }
private async void CreateFeatureLayers() { try { var geodatabase = await Geodatabase.OpenAsync(GeodatabasePath); Envelope extent = null; foreach (var table in geodatabase.FeatureTables) { var featureLayer = new FeatureLayer() { ID = table.Name, DisplayName = table.Name, FeatureTable = table }; if (!Geometry.IsNullOrEmpty(table.ServiceInfo.Extent)) { if (Geometry.IsNullOrEmpty(extent)) extent = table.ServiceInfo.Extent; else extent = extent.Union(table.ServiceInfo.Extent); } MySceneView.Scene.Layers.Add(featureLayer); } await MySceneView.SetViewAsync(new Camera(new MapPoint(-99.343, 26.143, 5881928.401), 2.377, 10.982)); } catch (Exception ex) { MessageBox.Show("Error creating feature layer: " + ex.Message, "Samples"); } }
private async Task CreateFeatureLayersAsync() { try { var gdb = await Geodatabase.OpenAsync(GDB_PATH); Envelope extent = new Envelope(); foreach (var table in gdb.FeatureTables) { var flayer = new FeatureLayer() { ID = table.Name, DisplayName = table.Name, FeatureTable = table }; if (table.Extent != null) { if (extent == null) extent = table.Extent; else extent = extent.Union(table.Extent); } mapView.Map.Layers.Add(flayer); } await mapView.SetViewAsync(extent.Expand(1.10)); } catch (Exception ex) { MessageBox.Show("Error creating feature layer: " + ex.Message, "Samples"); } }
private void Initialize() { // Create new Map Map myMap = new Map(); // Create the uri for the tiled layer Uri tiledLayerUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer"); // Create a tiled layer using url ArcGISTiledLayer tiledLayer = new ArcGISTiledLayer(tiledLayerUri); tiledLayer.Name = "Tiled Layer"; // Add the tiled layer to map myMap.OperationalLayers.Add(tiledLayer); // Create the uri for the ArcGISMapImage layer var imageLayerUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer"); // Create ArcGISMapImage layer using a url ArcGISMapImageLayer imageLayer = new ArcGISMapImageLayer(imageLayerUri); imageLayer.Name = "Image Layer"; // Set the visible scale range for the image layer imageLayer.MinScale = 40000000; imageLayer.MaxScale = 2000000; // Add the image layer to map myMap.OperationalLayers.Add(imageLayer); //Create Uri for feature layer var featureLayerUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Recreation/FeatureServer/0"); //Create a feature layer using url FeatureLayer myFeatureLayer = new FeatureLayer(featureLayerUri); myFeatureLayer.Name = "Feature Layer"; // Add the feature layer to map myMap.OperationalLayers.Add(myFeatureLayer); // Create a mappoint the map should zoom to MapPoint mapPoint = new MapPoint(-11000000, 4500000, SpatialReferences.WebMercator); // Set the initial viewpoint for map myMap.InitialViewpoint = new Viewpoint(mapPoint, 50000000); // Initialize the model list with unknown status for each layer foreach (Layer layer in myMap.OperationalLayers) { _layerStatusModels.Add(new LayerStatusModel(layer.Name, "Unknown")); } // Create the tableview source and pass the list of models to it _tableView.Source = new LayerViewStatusTableSource(_layerStatusModels); // Event for layer view state changed _myMapView.LayerViewStateChanged += OnLayerViewStateChanged; // Provide used Map to the MapView _myMapView.Map = myMap; }
public FeatureLayerChangeVersion() { InitializeComponent(); featureLayer = (MyMap.Layers["ServiceConnections"] as FeatureLayer); Geoprocessor gp_ListVersions = new Geoprocessor("http://sampleserver6.arcgisonline.com/arcgis/rest/services/GDBVersions/GPServer/ListVersions"); gp_ListVersions.Failed += (s, a) => { MessageBox.Show("Geoprocessing service failed: " + a.Error); }; gp_ListVersions.ExecuteCompleted += (c, d) => { VersionsCombo.DataContext = (d.Results.OutParameters[0] as GPRecordSet).FeatureSet; foreach (Graphic g in (d.Results.OutParameters[0] as GPRecordSet).FeatureSet.Features) { if ((g.Attributes["name"] as string) == featureLayer.GdbVersion) { VersionsCombo.SelectedValue = g; break; } } }; List<GPParameter> gpparams = new List<GPParameter>(); gpparams.Add(new GPRecordSet("Versions", new FeatureSet())); gp_ListVersions.ExecuteAsync(gpparams); }
private void ArcMap_NewDocument() { // TODO: Handle new document event IMap map = ArcMap.Document.FocusMap; Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); IWorkspaceFactory workspaceFactory = Activator.CreateInstance(factoryType) as IWorkspaceFactory; IWorkspace workspace = workspaceFactory.OpenFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ,@"Data\PointsToAdd.gdb"), 0); IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace; IFeatureClass featureClassLines = featureWorkspace.OpenFeatureClass("Lines"); IFeatureClass featureClassPoints = featureWorkspace.OpenFeatureClass("Points"); IFeatureLayer featureLayerLines = new FeatureLayer(); IFeatureLayer featureLayerPoints = new FeatureLayer(); featureLayerLines.FeatureClass = featureClassLines; featureLayerPoints.FeatureClass = featureClassPoints; featureLayerPoints.Name = "Points"; featureLayerLines.Name = "Lines"; map.AddLayer(featureLayerPoints); map.AddLayer(featureLayerLines); map.RecalcFullExtent(); }
private async void Initialize() { // Create new Map with basemap Map myMap = new Map(BasemapType.Topographic, 34.056, -117.196, 4); // Create uri to the used feature service var serviceUri = new Uri( "http://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/FeatureServer/0"); // Initialize a new feature layer ServiceFeatureTable myFeatureTable = new ServiceFeatureTable(serviceUri); FeatureLayer myFeatureLayer = new FeatureLayer(myFeatureTable); // Make sure that the feature layer gets loaded await myFeatureLayer.LoadAsync(); // Add the feature layer to the Map myMap.OperationalLayers.Add(myFeatureLayer); // Provide used Map to the MapView _myMapView.Map = myMap; // Hook up the DrawStatusChanged event _myMapView.DrawStatusChanged += OnMapViewDrawStatusChanged; // Animate the activity spinner _activityIndicator.StartAnimating(); }
private void Initialize() { // Create new Map with basemap Map myMap = new Map(Basemap.CreateTopographic()); // Create and set initial map area Envelope initialLocation = new Envelope( -1.30758164047166E7, 4014771.46954516, -1.30730056797177E7, 4016869.78617381, SpatialReferences.WebMercator); myMap.InitialViewpoint = new Viewpoint(initialLocation); // Create uri to the used feature service var serviceUri = new Uri( "http://sampleserver6.arcgisonline.com/arcgis/rest/services/PoolPermits/FeatureServer/0"); // Create feature table for the pools feature service ServiceFeatureTable poolsFeatureTable = new ServiceFeatureTable(serviceUri); // Define the request mode poolsFeatureTable.FeatureRequestMode = FeatureRequestMode.OnInteractionNoCache; // Create FeatureLayer that uses the created table FeatureLayer poolsFeatureLayer = new FeatureLayer(poolsFeatureTable); // Add created layer to the map myMap.OperationalLayers.Add(poolsFeatureLayer); // Assign the map to the MapView MyMapView.Map = myMap; }
/// <summary>Construct FeatureLayerHitTesting sample control</summary> public FeatureLayerHitTesting() { InitializeComponent(); DataContext = this; _featureLayer = MyMapView.Map.Layers["FeatureLayer"] as FeatureLayer; }
/// <summary> /// Represents the Relationship Class information /// </summary> /// <param name="featureLayer"></param> /// <param name="selection"></param> public RelateInfo(FeatureLayer featureLayer, Selection selection) { _featureLayer = featureLayer; _selection = selection; _featureClassName = _featureLayer.GetFeatureClass().GetName(); }
private void Initialize() { // Create new Map with basemap Map myMap = new Map(Basemap.CreateTopographic()); // Create and set initial map location MapPoint initialLocation = new MapPoint( -11000000, 5000000, SpatialReferences.WebMercator); myMap.InitialViewpoint = new Viewpoint(initialLocation, 100000000); // Create feature table using a url _featureTable = new ServiceFeatureTable(new Uri(_statesUrl)); // Create feature layer using this feature table _featureLayer = new FeatureLayer(_featureTable); // Set the Opacity of the Feature Layer _featureLayer.Opacity = 0.6; // Create a new renderer for the States Feature Layer SimpleLineSymbol lineSymbol = new SimpleLineSymbol( SimpleLineSymbolStyle.Solid, Color.Black, 1); SimpleFillSymbol fillSymbol = new SimpleFillSymbol( SimpleFillSymbolStyle.Solid, Color.Yellow, lineSymbol); // Set States feature layer renderer _featureLayer.Renderer = new SimpleRenderer(fillSymbol); // Add feature layer to the map myMap.OperationalLayers.Add(_featureLayer); // Assign the map to the MapView _myMapView.Map = myMap; }
private void Initialize() { // Create new Map with basemap Map myMap = new Map(Basemap.CreateTopographic()); // Create uri to the used feature service var serviceUri = new Uri( "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3"); // Create service feature table ServiceFeatureTable statesFeatureTable = new ServiceFeatureTable(serviceUri); // Create a new feature layer using the service feature table FeatureLayer statesLayer = new FeatureLayer(statesFeatureTable); // Create a new unique value renderer UniqueValueRenderer regionRenderer = new UniqueValueRenderer(); // Add the "SUB_REGION" field to the renderer regionRenderer.FieldNames.Add("SUB_REGION"); // Define a line symbol to use for the region fill symbols SimpleLineSymbol stateOutlineSymbol = new SimpleLineSymbol( SimpleLineSymbolStyle.Solid, System.Drawing.Color.White, 0.7); // Define distinct fill symbols for a few regions (use the same outline symbol) SimpleFillSymbol pacificFillSymbol = new SimpleFillSymbol( SimpleFillSymbolStyle.Solid, System.Drawing.Color.Blue, stateOutlineSymbol); SimpleFillSymbol mountainFillSymbol = new SimpleFillSymbol( SimpleFillSymbolStyle.Solid, System.Drawing.Color.LawnGreen, stateOutlineSymbol); SimpleFillSymbol westSouthCentralFillSymbol = new SimpleFillSymbol( SimpleFillSymbolStyle.Solid, System.Drawing.Color.SandyBrown, stateOutlineSymbol); // Add values to the renderer: define the label, description, symbol, and attribute value for each regionRenderer.UniqueValues.Add( new UniqueValue("Pacific", "Pacific Region", pacificFillSymbol, "Pacific")); regionRenderer.UniqueValues.Add( new UniqueValue("Mountain", "Rocky Mountain Region", mountainFillSymbol, "Mountain")); regionRenderer.UniqueValues.Add( new UniqueValue("West South Central", "West South Central Region", westSouthCentralFillSymbol, "West South Central")); // Set the default region fill symbol (transparent with no outline) for regions not explicitly defined in the renderer SimpleFillSymbol defaultFillSymbol = new SimpleFillSymbol( SimpleFillSymbolStyle.Null, System.Drawing.Color.Transparent, null); regionRenderer.DefaultSymbol = defaultFillSymbol; regionRenderer.DefaultLabel = "Other"; // Apply the unique value renderer to the states layer statesLayer.Renderer = regionRenderer; // Add created layer to the map myMap.OperationalLayers.Add(statesLayer); // Assign the map to the MapView _myMapView.Map = myMap; // Feature table initialization statesFeatureTable.RetryLoadAsync(); }
/// <summary> /// Call this method to apply symbol groups to the featureLayer - one group per value in the renderer. /// The first group to be added will be the first group to be drawn /// </summary> /// <param name="featureLayer"></param> private void SetUpSymbolLevelsForUSHighways(FeatureLayer featureLayer) { //All of these methods have to be called on the MCT if (Module1.OnUIThread) throw new CalledOnWrongThreadException(); CIMBaseLayer baseLayer = featureLayer.GetDefinition(); //We need CIMGeoFeatureLayerBase because this class controls whether or not we //use 'groups' (ie Pro Symbol Levels) with the renderer CIMGeoFeatureLayerBase geoFeatureLayer = baseLayer as CIMGeoFeatureLayerBase; // assume the unique value renderer was created using the CreateCIMRenderer() CIMUniqueValueRenderer uniqueValueRenderer = geoFeatureLayer.Renderer as CIMUniqueValueRenderer; CIMSymbolLayerDrawing symbolLayerDrawing = new CIMSymbolLayerDrawing(); // This flag controls the drawing code and forces it to use defined symbol layers. //It must be set 'true' symbolLayerDrawing.UseSymbolLayerDrawing = true; // setup the symbol layers. List<CIMSymbolLayerIdentifier> symbolLayers = new List<CIMSymbolLayerIdentifier>(); // this will be a for loop that will iterate over the unique value classes and updating the symbol in each class int index = 0; foreach (CIMUniqueValueGroup nextGroup in uniqueValueRenderer.Groups) { foreach (CIMUniqueValueClass nextClass in nextGroup.Classes) { CIMMultiLayerSymbol multiLayerSymbol = nextClass.Symbol.Symbol as CIMMultiLayerSymbol; if (multiLayerSymbol == null) //This check probably is not needed continue; //Each group must be uniquely named string uniqueName = "Group_" + index.ToString(); nextClass.Symbol.SymbolName = uniqueName; for (int i = 0; i < multiLayerSymbol.SymbolLayers.Length; i++) //Assign the unique name to all of the layers in the symbol multiLayerSymbol.SymbolLayers[i].Name = uniqueName; index++; //Assign the name to a 'CIMSymbolLayerIdentifier'. This is the equivalent //of a KeyValuePair in a Dictionary. The Names of each SymbolLayerIdentifier //will be matched up in the renderer to a corresponding symbol (via nextClass.Symbol.SymbolName) //So that each SymbolLayer is associated with a specific symbol for a specific value CIMSymbolLayerIdentifier nextSymbolLayer = new CIMSymbolLayerIdentifier() { SymbolReferenceName = "symbolReferenceName", SymbolLayerName = uniqueName }; symbolLayers.Add(nextSymbolLayer); } } //This is where the symbol layers get added to the feature layer definition symbolLayerDrawing.SymbolLayers = symbolLayers.ToArray(); geoFeatureLayer.SymbolLayerDrawing = symbolLayerDrawing; // update the featureLayer definition. featureLayer.SetDefinition(geoFeatureLayer as CIMBaseLayer); }
public void UpdateFeature( IMap pMap ,ILayer pCurrentLayer,IPoint pPoint ) { //处理具体数据 if (pMap == null || pPoint == null ) return; m_pMap = pMap; //如果没有地图图层 ,则不处理 long nLayerCount = pMap.LayerCount; if( nLayerCount == 0 ) return; //删除树结点 FtTreeView.Nodes.Clear(); this.FTtreeList.Nodes.Clear(); //开始选择 IGeometry geom = pPoint; ISpatialReference spatialReference = m_pMap.SpatialReference; geom.SpatialReference = spatialReference; //Refresh the active view IActiveView activeView = (IActiveView)m_pMap; ISelectionEnvironment selEnv = new SelectionEnvironment(); selEnv.PointSelectionMethod = esriSpatialRelEnum.esriSpatialRelWithin; m_pMap.SelectByShape(geom, selEnv, false); activeView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, activeView.Extent); //如果没有设置 当前图层pCurrentLayer ,则不处理 ESRI.ArcGIS.esriSystem.IPersist pPersist = new FeatureLayer() as ESRI.ArcGIS.esriSystem.IPersist; UID uid = pPersist as UID ; IEnumLayer pEnumlayer = pMap.get_Layers(uid,true ); pEnumlayer.Reset(); ILayer pLayer = pEnumlayer.Next(); while( pLayer != null ) { if( pLayer.Visible == false ) { pLayer = pEnumlayer.Next(); continue; } IFeatureLayer2 pFtLayer = (IFeatureLayer2)pLayer; IFeatureSelection pFtSelect = (IFeatureSelection)pFtLayer; ISelectionSet pSelectset = (ISelectionSet)pFtSelect.SelectionSet; InitTreeView(pSelectset, pLayer); pLayer = pEnumlayer.Next(); } }
private void Clear(FeatureLayer featureLayer) { Clear(); WmsClient wmsClient = GetClient(featureLayer); if (null != wmsClient) { wmsClient.ClientImagePropertiesChanged -= new MapInfo.Wms.WmsClient.ClientImagePropertiesChangedHandler(wmsClient_ClientImagePropertiesChanged); } }
public FeatureLayerInfo(FeatureLayer featureLayer, bool isEditable, bool isSyncable, long edits, List<LegendInfo> legendInfos) { _featureLayer = featureLayer; _isEditable = isEditable; _isSyncable = isSyncable; _edits = edits; _legendInfos = legendInfos; }
public QueryFilterSample() { this.InitializeComponent(); _featureLayer = MyMapView.Map.Layers["FeatureLayer"] as FeatureLayer; ((ServiceFeatureTable)_featureLayer.FeatureTable).OutFields = OutFields.All; _queryResultsOverlay = MyMapView.GraphicsOverlays[0]; }
static void Main(string[] args) { // register URL with a specific WFS reader WfsReaderFactory.RegisterHandler(URL, typeof(WfsReader)); // Get the WFS capabilities of the WFS server using the HTTP GET method. try { // Get the WFS capabilities of the WFS server using the HTTP GET method. WfsCapabilities Capabilities = WfsClient.GetCapabilities(RequestMethod.GET, URL); } catch { MessageBox.Show("Please check if " + URL + " is a valid WFS URL"); return; } // Do something with the the WfsCapabilities here... // Get the schema for the USA feature type string[] TypeNames = new string[] { "miwfs:USA" }; // Do something with the schema here... XmlSchema usaSchema = WfsClient.DescribeFeatureType(URL, TypeNames); // Get all features from the USA feature type MultiFeatureCollection usa = WfsClient.GetFeature(URL, TypeNames, null, null, -1, null); IFeatureCollection fc = usa[0]; // iterate over the Usa MultiFeatureCollection and add each // IFeatureCollection to a MemTable, etc... TableInfoMemTable memTableInfo = new TableInfoMemTable("myMemTable"); foreach (Column c in fc.Columns) { memTableInfo.Columns.Add(c); } Table memTable = Session.Current.Catalog.CreateTable(memTableInfo); memTable.InsertFeatures(fc); // create a layer from the MemTable FeatureLayer featureLayer = new FeatureLayer(memTable); // create the map and add the layer Map map = Session.Current.MapFactory.CreateEmptyMap(new Size(500, 500)); map.Layers.Add(featureLayer); // export the map to a file if (args.Length > 0 && args[0] != null && args[0].Trim().Length != 0) { using (MapExport me = new MapExport(map)) { me.Format = ExportFormat.Gif; me.Export(args[0]); } } // clean up the map Session.Current.MapFactory.Remove(map); }
public FeatureLayerHitTesting() { this.InitializeComponent(); MyMapView.MapViewTapped += MyMapView_MapViewTapped; _featureLayer = MyMapView.Map.Layers["FeatureLayer"] as FeatureLayer; ((ServiceFeatureTable)_featureLayer.FeatureTable).OutFields = OutFields.All; }
public SimpleEditing() { InitializeComponent(); editor = LayoutRoot.Resources["MyEditor"] as Editor; editor.Map = MyMap; editLayer = MyMap.Layers["ThreatPoints"] as FeatureLayer; }
private void SbAddClick(object sender, RoutedEventArgs e) { var l = ((FrameworkElement) sender).DataContext as StoredLayer; if (l == null) return; switch (l.Type) { case "Map Service": var ml = new ArcGISImageServiceLayer(); ml.Url = l.Id; ml.ID = l.Title; ml.Visible = true; var pts = AppStateSettings.Instance.ViewDef.FindOrCreateAcceleratedGroupLayer(l.Path); pts.ChildLayers.Add(ml); ml.Initialize(); break; // FIXME TODO: Unreachable code //break; case "Feature Service": var fl = new FeatureLayer() {}; fl.Url = l.Id + @"/0"; fl.ID = l.Title; fl.Visible = true; fl.InitializationFailed += fl_InitializationFailed; fl.Initialized += fl_Initialized; fl.UpdateCompleted += fl_UpdateCompleted; var pt = AppStateSettings.Instance.ViewDef.FindOrCreateAcceleratedGroupLayer(l.Path); pt.ChildLayers.Add(fl); fl.Initialize(); fl.Update(); break; case "wms": var wl = new WmsLayer { SupportedSpatialReferenceIDs = new[] {102100}, Visible = false }; wl.Visible = true; wl.SkipGetCapabilities = false; wl.Initialized += (st, es) => { wl.Layers = wl.LayerList.Select(k => k.Title).ToArray(); }; wl.Url = l.Id; wl.ID = l.Title; wl.Title = l.Title; var p = AppStateSettings.Instance.ViewDef.FindOrCreateGroupLayer(l.Path); p.ChildLayers.Add(wl); wl.Initialize(); break; } AppStateSettings.Instance.ViewDef.StoredLayers.Add(l); AppStateSettings.Instance.ViewDef.StoredLayers.Save(); }
public FeatureLayerMapTips() { this.InitializeComponent(); _featureLayer = mapView.Map.Layers["FeatureLayer"] as FeatureLayer; ((GeodatabaseFeatureServiceTable)_featureLayer.FeatureTable).OutFields = OutFields.All; mapView.PointerMoved += mapView_PointerMoved; }
private async void Initialize() { //MyMapView.Map = new Map(Basemap.CreateImagery()); MyMapView.Map = new Map(new SpatialReference(3375)); //MyMapView.InteractionOptions = new MapViewInteractionOptions { IsZoomEnabled = false }; // Open the shapefile ShapefileFeatureTable myShapefile = await ShapefileFeatureTable.OpenAsync(shapeFilePath); // Create a feature layer to display the shapefile FeatureLayer newFeatureLayer = new FeatureLayer(myShapefile); // Add the feature layer to the map MyMapView.Map.OperationalLayers.Add(newFeatureLayer); await myShapefile.LoadAsync(); //Get mosaic dataset names in the SQLite database. var names = MosaicDatasetRaster.GetNames(rasterMapMosaicPath); var rasterName = names[0]; //Create a raster from a mosaic dataset Raster mapRaster = new MosaicDatasetRaster(rasterMapMosaicPath, "RasterMapTable"); // Create a RasterLayer to display the Raster RasterLayer rasterMapLayer = new RasterLayer(mapRaster); MyMapView.Map.OperationalLayers.Add(rasterMapLayer); rasterMapLayer.MinScale = 100000; rasterMapLayer.MaxScale = 2000; await rasterMapLayer.LoadAsync(); MyMapView.Map.MinScale = 3000000; MyMapView.Map.MaxScale = 2000; MyMapView.GraphicsOverlays.Add(graphicsOverlay); // Add a graphic at JFK to serve as the origin. start = new MapPoint(564968.155634, 431946.116905, new SpatialReference(3168)); mapPoints.Add(start); SimpleMarkerSymbol startMarker = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Cross, System.Drawing.Color.Blue, 15); //PictureMarkerSymbol markerSym = new PictureMarkerSymbol(new Uri("C:\\Users\\mfathin.CSYSINT\\Documents\\Visual Studio 2017\\Projects\\ArcGISControl\\ArcGISControl\\Icon\\icons8-man-filled-100.PNG")); // markerSym.Opacity = 0.5; _startLocationGraphic = new Graphic(start, startMarker); // Create the graphic for the destination. _endLocationGraphic = new Graphic { Symbol = startMarker }; // Create the graphic for the path. _pathGraphic = new Graphic { Symbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Blue, 1) }; graphic1 = new Graphic { Symbol = startMarker }; // Add the graphics to the overlay. graphicsOverlay.Graphics.Add(_startLocationGraphic); graphicsOverlay.Graphics.Add(_endLocationGraphic); graphicsOverlay.Graphics.Add(graphic1); graphicsOverlay.Graphics.Add(_pathGraphic); //// Update end location when the user taps. MyMapView.GeoViewTapped += MyMapViewOnGeoViewTapped; await MyMapView.SetViewpointAsync(new Viewpoint(start, 4000000)); // Update the extent to encompass all of the symbols //SetExtent(); // Add the graphics overlay to the map view //MyMapView.GraphicsOverlays.Add(_overlay); plotButton.Click += (sender, e) => { TryPlot(); }; TrueCalculation(); }
public static async void GetCollisionRisk() { await CommonMethod.OpenMap(ConstDefintion.ConstMap_EncounterSafety); //计算DDV TDV await QueuedTask.Run(() => { IList <Layer> listLayers = MapView.Active.Map.GetLayersAsFlattenedList().ToList(); FeatureLayer l_ownShip = listLayers.First(l => l.Name == ConstDefintion.ConstLayer_OwnShipLayerName) as FeatureLayer; FeatureLayer l_targetShip = listLayers.First(l => l.Name == ConstDefintion.ConstLayer_TargetShipLayerName) as FeatureLayer; FeatureClass fc_ownShip = l_ownShip.GetFeatureClass(); FeatureClass fc_targetShip = l_targetShip.GetFeatureClass(); Feature f_ownShip; Feature f_targetShip; //获取本船的Feature QueryFilter qf = new QueryFilter() { ObjectIDs = new List <long>() { 1 } }; RowCursor rowCursor1 = fc_ownShip.Search(qf, false); rowCursor1.MoveNext(); Row row1 = rowCursor1.Current; f_ownShip = row1 as Feature; //遍历目标船的Feature using (RowCursor rowCursor = fc_targetShip.Search(null, false)) { while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { f_targetShip = row as Feature; long objectid = f_targetShip.GetObjectID(); CollisionRisk ctd = new CollisionRisk(f_ownShip, f_targetShip); if (ctd.Calculate()) { using (Geodatabase gdb = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath)))) { gdb.ApplyEdits(() => { Feature target = row as Feature; target[ConstDefintion.ConstFieldName_asemi] = ctd.asemi; target[ConstDefintion.ConstFieldName_bsemi] = ctd.bsemi; target[ConstDefintion.ConstFieldName_aoffset] = ctd.aoffset; target[ConstDefintion.ConstFieldName_boffset] = ctd.boffset; target[ConstDefintion.ConstFieldName_ddv] = ctd.DDV; target[ConstDefintion.ConstFieldName_tdv1] = ctd.TDV1; target[ConstDefintion.ConstFieldName_tdv2] = ctd.TDV2; target[ConstDefintion.ConstFieldName_dcpa] = ctd.DCPA; target[ConstDefintion.ConstFieldName_tcpa] = ctd.TCPA; target[ConstDefintion.ConstFieldName_tmin] = ctd.Tmin; target[ConstDefintion.ConstFieldName_tcr] = ctd.TCR; target[ConstDefintion.ConstFieldName_CollisionRisk] = ctd.collisionRisk; target.Store(); }); } } } } } CreateAllDomain(fc_targetShip); //CreateVoyageMaskAsync(fc_targetShip); }); }
public override void Execute(object parameter) { if (Layer == null) { return; } bool isServerLayer = false; Envelope targetExtent = null; TiledLayer tiledLayer = Layer as TiledLayer; if (tiledLayer != null) { isServerLayer = true; targetExtent = LayerExtentExtensions.GetTiledLayerFullExtent(tiledLayer); // get the cached value (if any) which will likely be in the map's spRef already if (targetExtent == null) // value not known, use value on service metadata (will likely be in the services' spatial ref and not neccesarily in map's spRef) { targetExtent = tiledLayer.FullExtent; } if (tiledLayer is ESRI.ArcGIS.Client.Bing.TileLayer) { if (targetExtent.SpatialReference == null) { targetExtent.SpatialReference = new SpatialReference(102100); } } } DynamicLayer dynamicLayer = Layer as DynamicLayer; if (dynamicLayer != null) { isServerLayer = true; targetExtent = LayerExtentExtensions.GetDynamicLayerFullExtent(dynamicLayer); // get the cached value (if any) which will likely be in the map's spRef already if (targetExtent == null) // value not known, use value on service metadata (will likely be in the services' spatial ref and not neccesarily in map's spRef) { targetExtent = dynamicLayer.FullExtent; } } if (isServerLayer) { if (targetExtent == null || Map == null || Map.SpatialReference == null) { return; } if (Map.SpatialReference.Equals(targetExtent.SpatialReference)) { // spatial reference matches. can directly zoom Map.ZoomTo(targetExtent); } else { if (string.IsNullOrEmpty(GeometryServiceUrl)) { throw new Exception(Resources.Strings.ExceptionNoGeometryServiceUrlSpecifiedLayerZoomedIsDifferentSpatialReference); } GeometryServiceOperationHelper helper = new GeometryServiceOperationHelper(GeometryServiceUrl); helper.ProjectExtentCompleted += (o, e) => { // Cache (save) the projected extent values if (tiledLayer != null) { LayerExtentExtensions.SetTiledLayerFullExtent(tiledLayer, e.Extent); } else if (dynamicLayer != null) { LayerExtentExtensions.SetDynamicLayerFullExtent(dynamicLayer, e.Extent); } Map.ZoomTo(e.Extent); }; helper.ProjectExtent(targetExtent, Map.SpatialReference); } return; } // Non server rendererd layers follow GraphicsLayer graphicsLayer = Layer as GraphicsLayer; if (graphicsLayer == null) { return; } if (Map != null) { Envelope newMapExtent = null; if (graphicsLayer.Graphics.Count < 1) { FeatureLayer featureLayer = graphicsLayer as FeatureLayer; if (featureLayer != null && featureLayer.LayerInfo != null && featureLayer.LayerInfo.Extent != null) { Envelope env = featureLayer.LayerInfo.Extent; SpatialReference sr = env.SpatialReference; if (sr == null) { sr = featureLayer.LayerInfo.DefaultSpatialReference; } if (Map.SpatialReference.Equals(sr)) { Map.PanTo(env); } else if (sr != null) { GeometryServiceOperationHelper geomHelper = new GeometryServiceOperationHelper( new ConfigurationStoreHelper().GetGeometryServiceUrl(View.Instance.ConfigurationStore)); geomHelper.GeometryServiceOperationFailed += (o, args) => { Logger.Instance.LogError(args.Exception); throw args.Exception; }; geomHelper.ProjectExtentCompleted += (o, args) => { MapZoomOrPan(args.Extent); }; geomHelper.ProjectExtent(env, Map.SpatialReference); } } } else { foreach (Graphic graphic in graphicsLayer.Graphics) { if (graphic.Geometry != null && graphic.Geometry.Extent != null) { newMapExtent = graphic.Geometry.Extent.Union(newMapExtent); } } newMapExtent = MapZoomOrPan(newMapExtent); } } }
private async void LoadLayers_Clicked(object sender, RoutedEventArgs e) { // Skip if nothing selected. if (WfsLayerList.SelectedItems.Count < 1) { return; } // Show the progress bar. LoadingProgressBar.Visibility = Visibility.Visible; // Clear the existing layers. MyMapView.Map.OperationalLayers.Clear(); try { // Get the selected WFS layer. WfsLayerInfo selectedLayerInfo = (WfsLayerInfo)WfsLayerList.SelectedItems[0]; // Create the WFS feature table. WfsFeatureTable table = new WfsFeatureTable(selectedLayerInfo); // Set the feature request mode to manual - only manual is supported at v100.5. // In this mode, you must manually populate the table - panning and zooming won't request features automatically. table.FeatureRequestMode = FeatureRequestMode.ManualCache; // Set the axis order based on the UI. if (AxisOrderSwapCheckbox.IsChecked == true) { table.AxisOrder = OgcAxisOrder.Swap; } else { table.AxisOrder = OgcAxisOrder.NoSwap; } // Populate the WFS table. await table.PopulateFromServiceAsync(new QueryParameters(), false, null); // Create a feature layer from the WFS table. FeatureLayer wfsFeatureLayer = new FeatureLayer(table); // Choose a renderer for the layer based on the table. wfsFeatureLayer.Renderer = GetRendererForTable(table) ?? wfsFeatureLayer.Renderer; // Add the layer to the map. MyMapView.Map.OperationalLayers.Add(wfsFeatureLayer); // Zoom to the extent of the selected layer. await MyMapView.SetViewpointGeometryAsync(selectedLayerInfo.Extent, 50); } catch (Exception ex) { Debug.WriteLine(ex); await new MessageDialog(ex.ToString(), "Failed to load layer.").ShowAsync(); } finally { // Hide the progress bar. LoadingProgressBar.Visibility = Visibility.Collapsed; } }
private void Initialize() { try { // Define the URI for the service feature table (US state polygons). Uri featureTableUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3"); // Create a new service feature table from the URI. ServiceFeatureTable censusServiceFeatureTable = new ServiceFeatureTable(featureTableUri); // Create a new feature layer from the service feature table. FeatureLayer censusFeatureLayer = new FeatureLayer(censusServiceFeatureTable) { // Set the rendering mode of the feature layer to be dynamic (needed for extrusion to work). RenderingMode = FeatureRenderingMode.Dynamic }; // Create a new simple line symbol for the feature layer. SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Black, 1); // Create a new simple fill symbol for the feature layer. SimpleFillSymbol fillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.Blue, lineSymbol); // Create a new simple renderer for the feature layer. SimpleRenderer renderer = new SimpleRenderer(fillSymbol); // Get the scene properties from the simple renderer. RendererSceneProperties sceneProperties = renderer.SceneProperties; // Set the extrusion mode for the scene properties. sceneProperties.ExtrusionMode = ExtrusionMode.AbsoluteHeight; // Set the initial extrusion expression. sceneProperties.ExtrusionExpression = "[POP2007] / 10"; // Set the feature layer's renderer to the define simple renderer. censusFeatureLayer.Renderer = renderer; // Create a new scene with a topographic basemap. Scene myScene = new Scene(BasemapType.Topographic); // Set the scene view's scene to the newly create one. _mySceneView.Scene = myScene; // Add the feature layer to the scene's operational layer collection. myScene.OperationalLayers.Add(censusFeatureLayer); // Create a new map point to define where to look on the scene view. MapPoint myMapPoint = new MapPoint(-10974490, 4814376, 0, SpatialReferences.WebMercator); // Create and use an orbit location camera controller defined by a point and distance. _mySceneView.CameraController = new OrbitLocationCameraController(myMapPoint, 20000000); } catch (Exception ex) { // Something went wrong, display the error. UIAlertController alert = UIAlertController.Create("Error", ex.Message, UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alert, true, null); } }
protected override ConfigureFeatureLayerParameters GetConfigureFeatureLayerParametersCore(FeatureLayer featureLayer) { ConfigCsvFileUserControl userControl = new ConfigCsvFileUserControl(featureLayer); GeneralWindow window = new GeneralWindow(); window.Tag = userControl; window.OkButtonClicking += Window_OkButtonClicking; window.Title = GisEditor.LanguageManager.GetStringResource("CSVLayerWindowTitle"); window.Owner = Application.Current.MainWindow; window.HelpContainer.Content = HelpResourceHelper.GetHelpButton("CreateNewShapefileHelp", HelpButtonMode.NormalButton); window.WindowStartupLocation = WindowStartupLocation.CenterOwner; window.ResizeMode = ResizeMode.NoResize; window.SizeToContent = SizeToContent.WidthAndHeight; window.ContentUI.Content = userControl; ConfigureFeatureLayerParameters parameters = null; if (window.ShowDialog().GetValueOrDefault()) { parameters = userControl.GetFeatureLayerInfo(); parameters.CustomData["Delimiter"] = userControl.ViewModel.Delimiter; parameters.CustomData["MappingType"] = userControl.ViewModel.MappingType; parameters.CustomData["X"] = GetSpecificColumnName(userControl.ViewModel.CsvColumns, CsvColumnType.Longitude); parameters.CustomData["Y"] = GetSpecificColumnName(userControl.ViewModel.CsvColumns, CsvColumnType.Latitude); parameters.CustomData["WKT"] = GetSpecificColumnName(userControl.ViewModel.CsvColumns, CsvColumnType.WKT); CsvFeatureLayer csvFeatureLayer = featureLayer as CsvFeatureLayer; if (csvFeatureLayer != null) { csvFeatureLayer.XColumnName = parameters.CustomData["X"].ToString(); csvFeatureLayer.YColumnName = parameters.CustomData["Y"].ToString(); csvFeatureLayer.WellKnownTextColumnName = parameters.CustomData["WKT"].ToString(); } } return(parameters); }
private async void Initialize() { // Create a new map centered on Aurora Colorado. _myMapView.Map = new Map(BasemapType.Streets, 39.7294, -104.8319, 11); // Get the full path to the GeoPackage on the device. string geoPackagePath = DataManager.GetDataFolder("68ec42517cdd439e81b036210483e8e7", "AuroraCO.gpkg"); try { // Open the GeoPackage. GeoPackage geoPackage = await GeoPackage.OpenAsync(geoPackagePath); // Loop through each GeoPackageRaster. foreach (GeoPackageRaster oneGeoPackageRaster in geoPackage.GeoPackageRasters) { // Create a RasterLayer from the GeoPackageRaster. RasterLayer rasterLayer = new RasterLayer(oneGeoPackageRaster) { // Set the opacity on the RasterLayer to partially visible. Opacity = 0.55 }; // Load the RasterLayer - that way we can get to its properties. await rasterLayer.LoadAsync(); // Create a string variable to hold the human-readable name of the RasterLayer for display. string rasterLayerName = ""; if (rasterLayer.Name != "") { // We have a good human-readable name for the RasterLayer that came from the RasterLayer.Name property. rasterLayerName = rasterLayer.Name; } else if (oneGeoPackageRaster.Path.Split('/').Last() != "") { // We did not get a good human-readable name from the RasterLayer from the .Name // property, get the good human-readable name from the GeoPackageRaster.Path instead. rasterLayerName = oneGeoPackageRaster.Path.Split('/').Last(); } // Append the 'type of layer' to the raster layer name string to display in the ListBox and as the key for the dictionary. rasterLayerName = $"{rasterLayerName} - RasterLayer"; // Add the name of the RasterLayer and the RasterLayer itself into the dictionary. _nameToLayerDictionary[rasterLayerName] = rasterLayer; // Add the name of the RasterLayer to the layers not in the map collection // which displays the human-readable layer names used by the UISegmentedControl. _layersNotInMap.Add(rasterLayerName); } // Loop through each GeoPackageFeatureTable from the GeoPackage. foreach (GeoPackageFeatureTable oneGeoPackageFeatureTable in geoPackage.GeoPackageFeatureTables) { // Create a FeatureLayer from the GeoPackageFeatureLayer. FeatureLayer featureLayer = new FeatureLayer(oneGeoPackageFeatureTable); // Load the FeatureLayer - that way we can get to its properties. await featureLayer.LoadAsync(); // Create a string variable to hold the human-readable name of the FeatureLayer for display in the UISegmentedControl and the dictionary. string featureLayerName = featureLayer.Name; // Append the 'type of layer' to the feature layer name string to display in the ListBox and as the key for the dictionary. featureLayerName = $"{featureLayerName} - FeatureLayer"; // Add the name of the FeatureLayer and the FeatureLayer itself into the dictionary. _nameToLayerDictionary[featureLayerName] = featureLayer; // Add the name of the RasterLayer to the collection of layers not in the map which displays the human-readable layer names used by the UISegmentedControl. _layersNotInMap.Add(featureLayerName); } // Enable the UI. _addLayerButton.Enabled = true; _removeLayerButton.Enabled = true; } catch (Exception e) { new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show(); } }
//开始提取 private void Deal() { IWorkspace pWorkspace = default(IWorkspace); string sDesFeatClsName = null; IFeatureClass pDesFeatCls = default(IFeatureClass); string sInfo = null; IFeatureLayer pFeatLayer = default(IFeatureLayer); IFeatureClass pFeatureCls = default(IFeatureClass); IGeometry pDomainGeometry = default(IGeometry); int ErrorCount = 0; int lFeatCount = 0; if (this.ChkClip.Checked) { bIsCut = true; ////是否剪切 } else { bIsCut = false; } ////印骅 20081121 获得多边形范围 pDomainGeometry = m_pGeometry; if (m_pMap.LayerCount == 0) { //g_clsErrorHandle.DisplayInformation("没有加载图层或没有图层处于选中状态!请选中需要提取的图层!", false); MessageBoxEx.Show("没有加载图层或没有图层处于选中状态!请选中需要提取的图层!", "提示"); return; } //WHFUtilities.clsLog ploger = default(WHFUtilities.clsLog); // 陈昉 2009-2-23 修改 修改原因 写日志 int iCount = 0; IDataset pTempDataset = default(IDataset); //ploger = new WHFUtilities.clsLog(); //ploger.DBConnectionString = "Data Source=" + g_Sys.DbName + ";User ID=" + g_Sys.DbUser + " ;Password="******"Column3"]).Value)) { if (pWorkspace == null) { pWorkspace = GetWorkspace(); } intChooseLayer++; pFeatLayer = cheFeatureLayer[i];//地图上的图层 pFeatureCls = pFeatLayer.FeatureClass; sDesFeatClsName = pFeatureCls.AliasName; sInfo = "当前操作层:" + pFeatLayer.Name; this.lblInfo.Text = sInfo; Application.DoEvents(); if (!string.IsNullOrEmpty(sDesFeatClsName.Trim())) { if (pFeatureCls != null) { this.lblInfo.Text = sInfo + "正在获得目标要素类,请稍候...."; lblInfo.Refresh(); Application.DoEvents(); if (sDesFeatClsName.Contains(".")) { int dotIndex = 0; dotIndex = sDesFeatClsName.IndexOf("."); sDesFeatClsName = sDesFeatClsName.Substring(dotIndex + 1, sDesFeatClsName.Length - dotIndex - 1); } //判断是否需要创建要素类 yh 15/4/09 ClsCreateFeat.CheckFeatCls(bIsCut, pFeatLayer, ref lFeatCount, pDomainGeometry); if (lFeatCount != 0) { IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspace; IFields pFields = pFeatureCls.Fields; pDesFeatCls = ClsCreatAndGetDataset.CreatOrOpenFeatClsByName(ref pFeatureWorkspace, sDesFeatClsName, ref pFields, null, null); pWorkspace = (IWorkspace)pFeatureWorkspace; //pFeatureCls.Fields = pFields; } if (pDesFeatCls != null) { //如果不剪切的,则使用该方法,需要剪切,则使用选择集,分位于内部要素和位于外部要素或直接使用pfeatcls搜索二遍 //如果数据量大的话,搜索二遍的方法是不可行的 ISpatialReference pSpatialReference = null; Dictionary <string, string> pDicField = null; iCount = (int)ClsCreateFeat.OutPutFeat(ref pDesFeatCls, ref pFeatureCls, strArryExpress[i], pDomainGeometry, bIsCut, ref pSpatialReference, pDicField, ref this.lblInfo, sInfo); IFeatureLayer showFeatureLayer = new FeatureLayer(); showFeatureLayer.FeatureClass = pDesFeatCls; ILayer showLayer = showFeatureLayer as ILayer; showLayer.Name = pDesFeatCls.AliasName + "_Extract"; m_pMap.AddLayer(showLayer); // 陈昉 2009-3-1 修改 修改原因 写日志 if (iCount > 0) { pTempDataset = (IDataset)pFeatureCls; //ploger.log(System.Environment.MachineName, g_Sys.User.UserID, System.DateTime.Now.ToString(), // "数据管理子系统", "WHFDataExtract", "快速提取" + pTempDataset.Name + "中" + iCount + // "个要素到" + pDesFeatCls.AliasName, "目标:" + System.IO.Path.GetFileName(pWorkspace.PathName)); } } else { ErrorCount = ErrorCount + 1; } } } } } this.Refresh(); Application.DoEvents(); if (intChooseLayer == 0) { MessageBoxEx.Show("没有选择任何要素图层!", "提示"); return; } if (ErrorCount > 0) { this.lblInfo.Text = "操作中有错误发生!"; //g_clsErrorHandle.DisplayInformation("操作中有错误发生!", false); MessageBoxEx.Show("操作中有错误发生!", "提示"); } else { //Member member = new Member(); //member.AddLayerToMap(pWorkspace, m_pMap); ESRI.ArcGIS.Carto.IActiveView activeView = m_pMap as ESRI.ArcGIS.Carto.IActiveView; activeView.Refresh(); this.lblInfo.Text = "操作完成!"; //g_clsErrorHandle.DisplayInformation("操作完成!", false); MessageBoxEx.Show("操作完成!", "提示"); } }
private void get_feature_layer() { /*********************************************************************** * This function loads a feature layer from arcGIS online ************************************************************************/ // Create new Map with basemap myMap = new Map(Basemap.CreateTopographic()); // Create and set initial map area Envelope initialLocation = new Envelope( -160.6739, 13.3844, -179.5449, 80.2319, SpatialReferences.Wgs84); myMap.InitialViewpoint = new Viewpoint(initialLocation); /*********************************************************************** * Turtle Feature Layer ************************************************************************/ // Create uri to the used feature service var serviceUri = new Uri( "https://services6.arcgis.com/kInEIOmrLNzXMSuZ/arcgis/rest/services/Turtles/FeatureServer/0"); // Create feature table using a URL. _featureTable = new ServiceFeatureTable(serviceUri); MyMapView.Map = myMap; // Create feature layer using this feature table. Make it slightly transparent. _featureLayer = new FeatureLayer(_featureTable); string theJSON_String = @"{ ""labelExpressionInfo"":{""expression"":""$feature.Species""}, ""labelPlacement"":""esriServerLinePlacementAboveAlong"", ""where"":""Species <> ' '"", ""symbol"": { ""angle"":0, ""backgroundColor"":[0,0,0,0], ""borderLineColor"":[0,0,0,0], ""borderLineSize"":0, ""color"":[51, 51, 51, 255], ""font"": { ""decoration"":""none"", ""size"":10, ""style"":""normal"", ""weight"":""normal"" }, ""haloColor"":[0,0,0,0], ""haloSize"":1.5, ""horizontalAlignment"":""center"", ""kerning"":false, ""type"":""esriTS"", ""verticalAlignment"":""middle"", ""xoffset"":0, ""yoffset"":0 } }"; // Create a label definition from the JSON string. LabelDefinition turtleSpeciesLabelDefinition = LabelDefinition.FromJson(theJSON_String); /*********************************************************************** * Air Temp Feature Layer ************************************************************************/ var airServiceUri = new Uri( "https://services6.arcgis.com/kInEIOmrLNzXMSuZ/arcgis/rest/services/Air_Temp_/FeatureServer/0"); // Create feature table using a URL. _airFeatureTable = new ServiceFeatureTable(airServiceUri); // Create feature layer using this feature table. Make it slightly transparent. _airFeatureLayer = new FeatureLayer(_airFeatureTable) { Opacity = 0.6 }; /*********************************************************************** * Wind Feature Layer ************************************************************************/ var windServiceUri = new Uri( "https://services6.arcgis.com/kInEIOmrLNzXMSuZ/arcgis/rest/services/Wind/FeatureServer/0"); // Create feature table using a URL. _windFeatureTable = new ServiceFeatureTable(windServiceUri); // Create feature layer using this feature table. Make it slightly transparent. _windFeatureLayer = new FeatureLayer(_windFeatureTable) { Opacity = 0.6 }; /*********************************************************************** * Sea Surface Temperature Feature Layer ************************************************************************/ var seaTempServiceUri = new Uri( "https://services6.arcgis.com/kInEIOmrLNzXMSuZ/arcgis/rest/services/Sea_Temp/FeatureServer/0"); // Create feature table using a URL. _seaTempFeatureTable = new ServiceFeatureTable(seaTempServiceUri); // Create feature layer using this feature table. Make it slightly transparent. _seaTempFeatureLayer = new FeatureLayer(_seaTempFeatureTable) { Opacity = 0.6 }; // add feature layers to map /* myMap.OperationalLayers.Add(_featureLayer); * myMap.OperationalLayers.Add(_airFeatureLayer); * myMap.OperationalLayers.Add(_windFeatureLayer); * myMap.OperationalLayers.Add(_seaTempFeatureLayer);*/ // Add the label definition to the feature layer's label definition collection. _featureLayer.LabelDefinitions.Add(turtleSpeciesLabelDefinition); // Enable the visibility of labels to be seen. _featureLayer.LabelsEnabled = true; MyMapView.TimeExtent = new TimeExtent(start, end); // add the map to the map view MyMapView.Map = myMap; }
private async void Initialize() { // Create a new map centered on Aurora Colorado _myMapView.Map = new Map(BasemapType.Streets, 39.7294, -104.8319, 11); // Get the full path to the GeoPackage on the device string myGeoPackagePath = GetGeoPackagePath(); // Open the GeoPackage GeoPackage myGeoPackage = await GeoPackage.OpenAsync(myGeoPackagePath); // Get the read only list of GeoPackageRasters from the GeoPackage IReadOnlyList <GeoPackageRaster> myReadOnlyListOfGeoPackageRasters = myGeoPackage.GeoPackageRasters; // Loop through each GeoPackageRaster foreach (GeoPackageRaster oneGeoPackageRaster in myReadOnlyListOfGeoPackageRasters) { // Create a RasterLayer from the GeoPackageRaster RasterLayer myRasterLayer = new RasterLayer(oneGeoPackageRaster); // Set the opacity on the RasterLayer to partially visible myRasterLayer.Opacity = 0.55; // Load the RasterLayer - that way we can get to it's properties await myRasterLayer.LoadAsync(); // Create a string variable to hold the human-readable name of the RasterLayer for display // in the ListBox and the HybridDictonary - it will initially be an empty string string myRasterLayerName = ""; if (myRasterLayer.Name != "") { // We have a good human-readable name for the RasterLayer that came from // the RasterLayer.Name property myRasterLayerName = myRasterLayer.Name; } else if (oneGeoPackageRaster.Path.Split('/').Last() != "") { // We did not get a good human-readable name from the RasterLayer from the .Name // property, get the good human-readable name from the GeoPackageRaster.Path instead myRasterLayerName = oneGeoPackageRaster.Path.Split('/').Last(); } // Append the 'type of layer' to the myRasterLayerName string to display in the // ListBox and as the key for the HybridDictonary myRasterLayerName = myRasterLayerName + " - RasterLayer"; // Add the name of the RasterLayer and the RasterLayer itself into the HybridDictionary _myHybridDictionary_Layers.Add(myRasterLayerName, myRasterLayer); // Add the name of the RasterLayer to _myObservableCollection_LayerNamesNotInTheMap // which displays the human-readable layer names used by the _myListView_LayersNotInTheMap _myObservableCollection_LayerNamesNotInTheMap.Add(myRasterLayerName); } // Get the read only list of GeoPackageFeatureTabless from the GeoPackage IReadOnlyList <GeoPackageFeatureTable> myReadOnlyListOfGeoPackageFeatureTables = myGeoPackage.GeoPackageFeatureTables; // Loop through each GeoPackageFeatureTable foreach (GeoPackageFeatureTable oneGeoPackageFeatureTable in myReadOnlyListOfGeoPackageFeatureTables) { // Create a FeatureLayer from the GeoPackageFeatureLayer FeatureLayer myFeatureLayer = new FeatureLayer(oneGeoPackageFeatureTable); // Load the FeatureLayer - that way we can get to it's properties await myFeatureLayer.LoadAsync(); // Create a string variable to hold the human-readable name of the FeatureLayer for // display in the ListBox and the HybridDictonary string myFeatureLayerName = myFeatureLayer.Name; // Append the 'type of layer' to the myFeatureLayerName string to display in the // ListBox and as the key for the HybridDictonary myFeatureLayerName = myFeatureLayerName + " - FeatureLayer"; // Add the name of the FeatureLayer and the FeatureLayer itself into the HybridDictionary _myHybridDictionary_Layers.Add(myFeatureLayerName, myFeatureLayer); // Add the name of the RasterLayer to _myObservableCollection_LayerNamesNotInTheMap // which displays the human-readable layer names used by the _myListView_LayersNotInTheMap _myObservableCollection_LayerNamesNotInTheMap.Add(myFeatureLayerName); } // Create a simple string array of the human-readable layer names from the ObservableCollection string[] myStringArray_LayerNamesNotInTheMap = _myObservableCollection_LayerNamesNotInTheMap.ToArray(); // Create an ArrayAdapter from the simple string array ArrayAdapter myArrayAdapter_LayerNamesNotInTheMap = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleListItem1, myStringArray_LayerNamesNotInTheMap); // Set the _myListView_LayersNotInTheMap.Adapter to the myArrayAdapter_LayerNamesNotInTheMap // This allows the human-readable layer names to be displayed a ListView _myListView_LayersNotInTheMap.Adapter = myArrayAdapter_LayerNamesNotInTheMap; }
private async void Initialize() { try { // Define the Uri for the service feature table (US state polygons) var myServiceFeatureTable_Uri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3"); // Create a new service feature table from the Uri ServiceFeatureTable myServiceFeatureTable = new ServiceFeatureTable(myServiceFeatureTable_Uri); // Create a new feature layer from the service feature table FeatureLayer myFeatureLayer = new FeatureLayer(myServiceFeatureTable); // Set the rendering mode of the feature layer to be dynamic (needed for extrusion to work) myFeatureLayer.RenderingMode = FeatureRenderingMode.Dynamic; // Create a new simple line symbol for the feature layer SimpleLineSymbol mySimpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Colors.Black, 1); // Create a new simple fill symbol for the feature layer SimpleFillSymbol mysimpleFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Colors.Blue, mySimpleLineSymbol); // Create a new simple renderer for the feature layer SimpleRenderer mySimpleRenderer = new SimpleRenderer(mysimpleFillSymbol); // Get the scene properties from the simple renderer RendererSceneProperties myRendererSceneProperties = mySimpleRenderer.SceneProperties; // Set the extrusion mode for the scene properties to be base height myRendererSceneProperties.ExtrusionMode = ExtrusionMode.BaseHeight; // Set the initial extrusion expression myRendererSceneProperties.ExtrusionExpression = "[POP2007] / 10"; // Set the feature layer's renderer to the define simple renderer myFeatureLayer.Renderer = mySimpleRenderer; // Create a new scene with the topographic backdrop Scene myScene = new Scene(BasemapType.Topographic); // Set the scene view's scene to the newly create one MySceneView.Scene = myScene; // Add the feature layer to the scene's operational layer collection myScene.OperationalLayers.Add(myFeatureLayer); // Create a new map point to define where to look on the scene view MapPoint myMapPoint = new MapPoint(-10974490, 4814376, 0, SpatialReferences.WebMercator); // Create a new orbit location camera controller using the map point and defined distance OrbitLocationCameraController myOrbitLocationCameraController = new OrbitLocationCameraController(myMapPoint, 20000000); // Set the scene view's camera controller to the orbit location camera controller MySceneView.CameraController = myOrbitLocationCameraController; } catch (Exception ex) { // Something went wrong, display the error var message = new MessageDialog(ex.ToString(), "Error"); await message.ShowAsync(); } }
private void RefreshColumnList(FeatureLayer featureLayer) { Collection <ViewColumnItem> viewColumnItems = new Collection <ViewColumnItem>(); featureLayer.SafeProcess(() => { foreach (var column in featureLayer.FeatureSource.GetColumns()) { if (!string.IsNullOrEmpty(column.ColumnName)) { string alias = featureLayer.FeatureSource.GetColumnAlias(column.ColumnName); ViewColumnItem item = new ViewColumnItem(column, alias); viewColumnItems.Add(item); } } }); if (CalculatedDbfColumn.CalculatedColumns.ContainsKey(featureLayer.FeatureSource.Id)) { foreach (var column in CalculatedDbfColumn.CalculatedColumns[featureLayer.FeatureSource.Id]) { string alias = featureLayer.FeatureSource.GetColumnAlias(column.ColumnName); ViewColumnItem item = new ViewColumnItem(column, alias, true); item.EditAction = c => { DbfColumn dbfColumn = (DbfColumn)c; Collection <string> columns = new Collection <string>(); columns.Add(c.ColumnName); string tempAlias = featureLayer.FeatureSource.GetColumnAlias(dbfColumn.ColumnName); AddDbfColumnWindow window = new AddDbfColumnWindow(dbfColumn, columns, DbfColumnMode.Calculated, true, tempAlias); window.WindowStartupLocation = WindowStartupLocation.CenterOwner; window.Owner = Application.Current.MainWindow; if (window.ShowDialog().GetValueOrDefault()) { CalculatedDbfColumn newColumn = window.DbfColumn as CalculatedDbfColumn; if (newColumn != null) { //Check does edit CalculatedDbfColumn tempColumn = (CalculatedDbfColumn)c; if (newColumn.ColumnName == tempColumn.ColumnName && newColumn.CalculationType == tempColumn.CalculationType && newColumn.ColumnType == tempColumn.ColumnType && newColumn.DecimalLength == tempColumn.DecimalLength && newColumn.Length == tempColumn.Length && newColumn.LengthUnit == tempColumn.LengthUnit && newColumn.MaxLength == tempColumn.MaxLength && newColumn.AreaUnit == tempColumn.AreaUnit && newColumn.TypeName == tempColumn.TypeName) { return; } if (CheckHasDuplicatedColumn(newColumn)) { return; } if (CalculatedDbfColumn.CalculatedColumns.ContainsKey(featureLayer.FeatureSource.Id)) { CalculatedDbfColumn calColumn = (CalculatedDbfColumn)c; if (CalculatedDbfColumn.CalculatedColumns[featureLayer.FeatureSource.Id].Contains(calColumn)) { CalculatedDbfColumn.CalculatedColumns[featureLayer.FeatureSource.Id].Remove(calColumn); } CalculatedDbfColumn.CalculatedColumns[featureLayer.FeatureSource.Id].Add(newColumn); } RefreshColumnList(featureLayer); } } }; item.DeleteAction = c => { if (CalculatedDbfColumn.CalculatedColumns.ContainsKey(featureLayer.FeatureSource.Id)) { CalculatedDbfColumn calColumn = (CalculatedDbfColumn)c; if (CalculatedDbfColumn.CalculatedColumns[featureLayer.FeatureSource.Id].Contains(calColumn)) { CalculatedDbfColumn.CalculatedColumns[featureLayer.FeatureSource.Id].Remove(calColumn); RefreshColumnList(featureLayer); } } }; viewColumnItems.Add(item); } } ColumnList.ItemsSource = viewColumnItems; }
private async void Initialize() { try { // Construct the map and set the MapView.Map property. MyMapView.Map = new Map(Basemap.CreateLightGrayCanvasVector()); // Add a graphics overlay to MyMapView. (Will be used later to display routes) MyMapView.GraphicsOverlays.Add(new GraphicsOverlay()); // Create a ClosestFacilityTask using the San Diego Uri. _task = await ClosestFacilityTask.CreateAsync(_closestFacilityUri); // Create a symbol for displaying facilities. PictureMarkerSymbol facilitySymbol = new PictureMarkerSymbol(new Uri("http://static.arcgis.com/images/Symbols/SafetyHealth/FireStation.png")) { Height = 30, Width = 30 }; // Incident symbol. PictureMarkerSymbol incidentSymbol = new PictureMarkerSymbol(new Uri("http://static.arcgis.com/images/Symbols/SafetyHealth/esriCrimeMarker_56_Gradient.png")) { Height = 30, Width = 30 }; // Create a list of line symbols to show unique routes. Different colors help make different routes visually distinguishable. _routeSymbols = new List <SimpleLineSymbol>() { new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.FromArgb(125, 25, 45, 85), 5.0f), new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.FromArgb(125, 35, 65, 120), 5.0f), new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.FromArgb(125, 55, 100, 190), 5.0f), new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.FromArgb(125, 75, 140, 255), 5.0f) }; // Create a table for facilities using the FeatureServer. _facilityTable = new ServiceFeatureTable(_facilityUri); // Create a feature layer from the table. _facilityLayer = new FeatureLayer(_facilityTable) { Renderer = new SimpleRenderer(facilitySymbol) }; // Create a table for facilities using the FeatureServer. _incidentTable = new ServiceFeatureTable(_incidentUri); // Create a feature layer from the table. _incidentLayer = new FeatureLayer(_incidentTable) { Renderer = new SimpleRenderer(incidentSymbol) }; // Add the layers to the map. MyMapView.Map.OperationalLayers.Add(_facilityLayer); MyMapView.Map.OperationalLayers.Add(_incidentLayer); // Wait for both layers to load. await _facilityLayer.LoadAsync(); await _incidentLayer.LoadAsync(); // Zoom to the combined extent of both layers. Envelope fullExtent = GeometryEngine.CombineExtents(_facilityLayer.FullExtent, _incidentLayer.FullExtent); await MyMapView.SetViewpointGeometryAsync(fullExtent, 50); // Enable the solve button. SolveRoutesButton.IsEnabled = true; } catch (Exception exception) { System.Windows.MessageBox.Show("An exception has occurred.\n" + exception.Message, "Sample error"); } }
private void RefreshLayer(Layer layer, EventHandler refreshCompletedHander, EventHandler <TaskFailedEventArgs> refreshFailedHandler) { _isRefreshing = true; FeatureLayer featureLayer = layer as FeatureLayer; if (featureLayer != null && !string.IsNullOrEmpty(featureLayer.Url)) { // temporarly unhook the AttributeDisplay's layer while we refresh feature layer if (View.Instance != null && View.Instance.AttributeDisplay != null && View.Instance.AttributeDisplay.FeatureDataGrid != null) { ToggleTableCommand.SetTableVisibility(Visibility.Collapsed); // Set FeatureDataGrid layer to null so that we don't incur the overhead // of all the UpdateItemSource calls as the AttributeTable Graphics layer is // being set to null. View.Instance.AttributeDisplay.FeatureDataGrid.GraphicsLayer = null; // Set the FilterSource to null to prevent potential GraphicsLayer reference exceptions View.Instance.AttributeDisplay.FeatureDataGrid.FilterSource = null; // Now set the AttributeDisplay GraphicsLayer to null so that it // unhooks all the bindings and events View.Instance.AttributeDisplay.GraphicsLayer = null; // Hook up to the UpdateCompleted/UpdateFailed events so that the layer // can be reset to the SelectedLayer featureLayer.UpdateCompleted -= OnFeatureLayerUpdateCompleted; featureLayer.UpdateCompleted += OnFeatureLayerUpdateCompleted; featureLayer.UpdateFailed -= OnFeatureLayerUpdateFailed; featureLayer.UpdateFailed += OnFeatureLayerUpdateFailed; } if (refreshCompletedHander != null) { featureLayer.UpdateCompleted -= refreshCompletedHander; featureLayer.UpdateCompleted += refreshCompletedHander; } if (refreshFailedHandler != null) { featureLayer.UpdateFailed -= refreshFailedHandler; featureLayer.UpdateFailed += refreshFailedHandler; } featureLayer.Update(); return; } ArcGISDynamicMapServiceLayer dynamicLayer = layer as ArcGISDynamicMapServiceLayer; if (dynamicLayer != null) { dynamicLayer.Refresh(); if (refreshCompletedHander != null) { refreshCompletedHander.Invoke(layer, EventArgs.Empty); } return; } ArcGISTiledMapServiceLayer tiledLayer = layer as ArcGISTiledMapServiceLayer; if (tiledLayer != null) { // Tiled layers do not support refreshing if (refreshCompletedHander != null) { refreshCompletedHander.Invoke(layer, EventArgs.Empty); } return; } ArcGISImageServiceLayer imageServiceLayer = layer as ArcGISImageServiceLayer; if (imageServiceLayer != null) { imageServiceLayer.Refresh(); if (refreshCompletedHander != null) { refreshCompletedHander.Invoke(layer, EventArgs.Empty); } return; } ICustomGraphicsLayer customGraphicsLayer = layer as ICustomGraphicsLayer; if (customGraphicsLayer != null) { customGraphicsLayer.ForceRefresh(refreshCompletedHander, refreshFailedHandler); return; } HeatMapLayerBase heatMapLayer = layer as HeatMapLayerBase; if (heatMapLayer != null) { heatMapLayer.Update(); if (refreshCompletedHander != null) { refreshCompletedHander.Invoke(layer, EventArgs.Empty); } return; } GeoRssLayer geoRssLayer = Layer as GeoRssLayer; if (geoRssLayer != null) { geoRssLayer.Update(); return; } WmsLayer wmsLayer = Layer as WmsLayer; if (wmsLayer != null) { wmsLayer.Refresh(); return; } GraphicsLayer graphicsLayer = layer as GraphicsLayer; if (graphicsLayer != null) { graphicsLayer.Refresh(); if (refreshCompletedHander != null) { refreshCompletedHander.Invoke(layer, EventArgs.Empty); } return; } }
async public static void MethodSnippets() { Layout layout = LayoutView.Active.Layout; #region MapFrame_Export //See ProSnippets.cs "Export a map frame to JPG" #endregion MapFrame_Export #region MapFrame_GetMapView //see ProSnippets "Export the map view associated with a map frame to BMP" #endregion MapFrame_GetMapView #region MapFrame_SetCamera_Camera // see ProSnippets "Change map frames camera settings" #endregion MapFrame_SetCamera_Camera #region MapFrame_SetCamera_Bookmark //Set the extent of a map frame to a bookmark. //Perform on the worker thread await QueuedTask.Run(() => { //Reference MapFrame MapFrame mf_bk = layout.FindElement("Map Frame") as MapFrame; //Reference a bookmark that belongs to a map associated with the map frame Map m = mf_bk.Map; Bookmark bk = m.GetBookmarks().FirstOrDefault(item => item.Name.Equals("Lakes")); //Set the map frame extent using the bookmark mf_bk.SetCamera(bk); }); #endregion MapFrame_SetCamera_Bookmark #region MapFrame_SetCamera_Envelope //Set the extent of a map frame to the envelope of a feature. //Perform on the worker thread await QueuedTask.Run(() => { //Reference MapFrame MapFrame mf_env = layout.FindElement("Map Frame") as MapFrame; //Get map and a layer of interest Map m = mf_env.Map; //Get the specific layer you want from the map and its extent FeatureLayer lyr = m.FindLayers("GreatLakes").First() as FeatureLayer; Envelope lyrEnv = lyr.QueryExtent(); //Set the map frame extent to the feature layer's extent / envelope mf_env.SetCamera(lyrEnv); //Note - you could have also used the lyr as an overload option }); #endregion MapFrame_SetCamera_Envelope #region MapFrame_SetCamera_Layer //See ProSnppets "Zoom map frame to extent of a single layer" #endregion MapFrame_SetCamera_Layer #region MapFrame_SetCamera_Layers //See ProSnippets "Change map frame extent to selected features in multiple layers" #endregion MapFrame_SetCamera_Layers MapFrame mf = null; Map map = null; #region MapFrame_SetMap //Set the map that is associated with a map frame. //Perform on worker thread await QueuedTask.Run(() => { mf.SetMap(map); }); #endregion #region MapFrame_SetName //See ProSnppets "Zoom map frame to extent of a single layer" #endregion MapFrame_SetName }
/// <summary> /// The add XY event layer. /// </summary> /// <param name="table"> /// The table. /// </param> /// <param name="query"> /// The query. /// </param> /// <param name="tweetShow"> /// The tweet show. /// </param> public static void AddXyEventLayer(ITable table, string query, bool tweetShow = true) { var mxdoc = ArcMap.Application.Document as IMxDocument; if (mxdoc != null) { var map = mxdoc.FocusMap; // Get the table named XYSample.txt var stTableCollection = map as IStandaloneTableCollection; // Get the table name object var dataset = table as IDataset; var tableName = dataset.FullName; // Specify the X and Y fields var xyEvent2FieldsProperties = new XYEvent2FieldsProperties() as IXYEvent2FieldsProperties; if (xyEvent2FieldsProperties != null) { xyEvent2FieldsProperties.XFieldName = "x"; xyEvent2FieldsProperties.YFieldName = "y"; xyEvent2FieldsProperties.ZFieldName = string.Empty; // Specify the projection var spatialReferenceFactory = new SpatialReferenceEnvironment() as ISpatialReferenceFactory; var projectedCoordinateSystem = spatialReferenceFactory.CreateGeographicCoordinateSystem( (int)esriSRGeoCSType.esriSRGeoCS_WGS1984); // Create the XY name object as set it's properties var xyEventSourceName = new XYEventSourceName() as IXYEventSourceName; xyEventSourceName.EventProperties = xyEvent2FieldsProperties; xyEventSourceName.SpatialReference = projectedCoordinateSystem; xyEventSourceName.EventTableName = tableName; IName xyName = xyEventSourceName as IName; IXYEventSource xyEventSource = xyName.Open() as IXYEventSource; // Create a new Map Layer IFeatureLayer featureLayer = new FeatureLayer() as IFeatureLayer; featureLayer.FeatureClass = xyEventSource as IFeatureClass; featureLayer.Name = query; // Add the layer extension (this is done so that when you edit // the layer's Source properties and click the Set Data Source // button, the Add XY Events Dialog appears) ILayerExtensions layerExtensions = featureLayer as ILayerExtensions; XYDataSourcePageExtension resPageExtension = new XYDataSourcePageExtension(); layerExtensions.AddExtension(resPageExtension); IGeoFeatureLayer geoLayer = (IGeoFeatureLayer)featureLayer; ISimpleRenderer simpleRenderer = (ISimpleRenderer)geoLayer.Renderer; var randomNumber = NumberRandom.Next(0, Colors.Count - 1); var color = Colors[randomNumber]; IRgbColor rgbColor = new RgbColorClass(); rgbColor.Blue = color.B; rgbColor.Red = color.R; rgbColor.Green = color.G; IMarkerSymbol markerSymbol = new SimpleMarkerSymbolClass(); markerSymbol.Color = rgbColor; markerSymbol.Size = 5; simpleRenderer.Symbol = (ISymbol)markerSymbol; try { map.AddLayer(featureLayer); } catch (Exception error) { Console.WriteLine(error.Message); } } } }
/// <summary> /// Call this method to apply symbol groups to the featureLayer - one group per value in the renderer. /// The first group to be added will be the first group to be drawn /// </summary> /// <param name="featureLayer"></param> private void SetUpSymbolLevelsForUSHighways(FeatureLayer featureLayer) { //All of these methods have to be called on the MCT if (Module1.OnUIThread) { throw new CalledOnWrongThreadException(); } CIMBaseLayer baseLayer = featureLayer.GetDefinition(); //We need CIMGeoFeatureLayerBase because this class controls whether or not we //use 'groups' (ie Pro Symbol Levels) with the renderer CIMGeoFeatureLayerBase geoFeatureLayer = baseLayer as CIMGeoFeatureLayerBase; // assume the unique value renderer was created using the CreateCIMRenderer() CIMUniqueValueRenderer uniqueValueRenderer = geoFeatureLayer.Renderer as CIMUniqueValueRenderer; CIMSymbolLayerDrawing symbolLayerDrawing = new CIMSymbolLayerDrawing() { // This flag controls the drawing code and forces it to use defined symbol layers. //It must be set 'true' UseSymbolLayerDrawing = true }; // setup the symbol layers. List <CIMSymbolLayerIdentifier> symbolLayers = new List <CIMSymbolLayerIdentifier>(); // this will be a for loop that will iterate over the unique value classes and updating the symbol in each class int index = 0; foreach (CIMUniqueValueGroup nextGroup in uniqueValueRenderer.Groups) { foreach (CIMUniqueValueClass nextClass in nextGroup.Classes) { CIMMultiLayerSymbol multiLayerSymbol = nextClass.Symbol.Symbol as CIMMultiLayerSymbol; if (multiLayerSymbol == null) //This check probably is not needed { continue; } //Each group must be uniquely named string uniqueName = "Group_" + index.ToString(); nextClass.Symbol.SymbolName = uniqueName; for (int i = 0; i < multiLayerSymbol.SymbolLayers.Length; i++) { //Assign the unique name to all of the layers in the symbol multiLayerSymbol.SymbolLayers[i].Name = uniqueName; } index++; //Assign the name to a 'CIMSymbolLayerIdentifier'. This is the equivalent //of a KeyValuePair in a Dictionary. The Names of each SymbolLayerIdentifier //will be matched up in the renderer to a corresponding symbol (via nextClass.Symbol.SymbolName) //So that each SymbolLayer is associated with a specific symbol for a specific value CIMSymbolLayerIdentifier nextSymbolLayer = new CIMSymbolLayerIdentifier() { SymbolLayerName = uniqueName }; symbolLayers.Add(nextSymbolLayer); } } //This is where the symbol layers get added to the feature layer definition symbolLayerDrawing.SymbolLayers = symbolLayers.ToArray(); geoFeatureLayer.SymbolLayerDrawing = symbolLayerDrawing; // update the featureLayer definition. featureLayer.SetDefinition(geoFeatureLayer as CIMBaseLayer); }
private async void sureBtn_Click(object sender, RoutedEventArgs e) { try { FeatureLayer tempLayer = (FeatureLayer)myMapView.Map.OperationalLayers[index]; Esri.ArcGISRuntime.Data.FeatureTable tempTable = tempLayer.FeatureTable; // 语句 QueryParameters query = new QueryParameters(); query.WhereClause = string.Format(inTxt.Text); FeatureQueryResult queryResult = await tempTable.QueryFeaturesAsync(query); IEnumerator <Feature> resultFeatures = queryResult.GetEnumerator(); List <Feature> features = new List <Feature>(); while (resultFeatures.MoveNext()) { features.Add(resultFeatures.Current); } MessageBox.Show(inTxt.Text + "\n" + features.Count + "\n" + query.WhereClause); //long row = tempTable.NumberOfFeatures; long row = features.Count; int col = tempTable.Fields.Count; List <String> fieldNames = new List <string>(); for (int i = 0; i < col; i++) { fieldNames.Add(tempTable.Fields[i] + ""); } StackPanel stackPanel = new StackPanel(); WrapPanel[] wrapPanels = new WrapPanel[row]; // 字段名 WrapPanel wrapPanelField = new WrapPanel() { Margin = new Thickness() { Left = 10, Top = 1, Right = 10, Bottom = 1 } }; for (int i = 0; i < col; i++) { Button button = new Button() { Content = fieldNames[i], ToolTip = fieldNames[i], Width = 60, Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 100, 183, 134)) }; wrapPanelField.Children.Add(button); } stackPanel.Children.Add(wrapPanelField); // 记录 for (int i = 0; i < row; i++) { wrapPanels[i] = new WrapPanel() { Margin = new Thickness() { Left = 10, Top = 1, Right = 10, Bottom = 1 } }; for (int j = 0; j < col; j++) { Button button = new Button() { Width = 60, Content = features[i].GetAttributeValue(fieldNames[j]), ToolTip = features[i].GetAttributeValue(fieldNames[j]) }; wrapPanels[i].Children.Add(button); } stackPanel.Children.Add(wrapPanels[i]); } var window = new Window(); window.Content = stackPanel; window.SizeToContent = SizeToContent.WidthAndHeight; window.WindowStartupLocation = WindowStartupLocation.CenterScreen; window.Title = "属性查询结果"; window.Show(); } catch (Exception ex2) { MessageBox.Show("查询错误!\n" + ex2.Message + "\n"); } }
static void Main(string[] args) { // register URL with a specific WFS reader WfsReaderFactory.RegisterHandler(URL, typeof(WfsReader)); // Get the WFS capabilities of the WFS server using the HTTP GET method. try { // Get the WFS capabilities of the WFS server using the HTTP GET method. WfsCapabilities Capabilities = WfsClient.GetCapabilities(RequestMethod.GET, URL); } catch { MessageBox.Show("Please check if " + URL + " is a valid WFS URL"); return; } // Do something with the the WfsCapabilities here... // Get the schema for the USA feature type string[] TypeNames = new string[] { "miwfs:USA" }; // Do something with the schema here... XmlSchema usaSchema = WfsClient.DescribeFeatureType(URL, TypeNames); // Get all features from the USA feature type MultiFeatureCollection usa = WfsClient.GetFeature(URL, TypeNames, null, null, -1, null); IFeatureCollection fc = usa[0]; // iterate over the Usa MultiFeatureCollection and add each // IFeatureCollection to a MemTable, etc... TableInfoMemTable memTableInfo = new TableInfoMemTable("myMemTable"); foreach (Column c in fc.Columns) { memTableInfo.Columns.Add(c); } Table memTable = Session.Current.Catalog.CreateTable(memTableInfo); memTable.InsertFeatures(fc); // create a layer from the MemTable FeatureLayer featureLayer = new FeatureLayer(memTable); // create the map and add the layer Map map = Session.Current.MapFactory.CreateEmptyMap(new Size(500, 500)); map.Layers.Add(featureLayer); // export the map to a file if (args.Length > 0 && args[0] != null && args[0].Trim().Length != 0) { using (MapExport me = new MapExport(map)) { me.Format = ExportFormat.Gif; me.Export(args[0]); } } // clean up the map Session.Current.MapFactory.Remove(map); }
private async void Initialize() { // Create a map with a light gray canvas basemap. Map sampleMap = new Map(Basemap.CreateLightGrayCanvas()); // Assign the map to the MapView. MyMapView.Map = sampleMap; // Define the Url string for the US highways feature layer. string highwaysUrlString = "http://sampleserver6.arcgisonline.com/arcgis/rest/services/USA/MapServer/1"; // Create a service feature table from the url to the US highways feature service. ServiceFeatureTable highwaysServiceFeatureTable = new ServiceFeatureTable(new System.Uri(highwaysUrlString)); // Create a feature layer from the service feature table. FeatureLayer highwaysFeatureLayer = new FeatureLayer(highwaysServiceFeatureTable); // Load the US highways feature layer - this way we can obtain it's extent. await highwaysFeatureLayer.LoadAsync(); // Zoom the map view to the extent of the US highways feature layer. await MyMapView.SetViewpointGeometryAsync(highwaysFeatureLayer.FullExtent); // Help regarding the Json syntax for defining the LabelDefinition.FromJson syntax can be found here: // https://developers.arcgis.com/web-map-specification/objects/labelingInfo/ // This particular JSON string will have the following characteristics: // (1) The 'labelExpressionInfo' defines that the label text displayed comes from the field 'rte_num1' in the // feature service and will be prefaced with an "I -". Example: "I - 10", "I - 15", "I - 95", etc. // (2) The 'labelPlacement' will be placed above and along the highway polyline segment. // (3) The 'where' clause restricts the labels to be displayed that has valid (non-empty) data. Empty data // for this service has a single blank space in the 'rte_num1' field. // (4) The 'symbol' for the labeled text will be blue with a yellow halo. string theJSON_String = @"{ ""labelExpressionInfo"":{""expression"":""'I - ' + $feature.rte_num1""}, ""labelPlacement"":""esriServerLinePlacementAboveAlong"", ""where"":""rte_num1 <> ' '"", ""symbol"": { ""angle"":0, ""backgroundColor"":[0,0,0,0], ""borderLineColor"":[0,0,0,0], ""borderLineSize"":0, ""color"":[0,0,255,255], ""font"": { ""decoration"":""none"", ""size"":15, ""style"":""normal"", ""weight"":""normal"" }, ""haloColor"":[255,255,0,255], ""haloSize"":1.5, ""horizontalAlignment"":""center"", ""kerning"":false, ""type"":""esriTS"", ""verticalAlignment"":""middle"", ""xoffset"":0, ""yoffset"":0 } }"; // Create a label definition from the JSON string. LabelDefinition highwaysLabelDefinition = LabelDefinition.FromJson(theJSON_String); // Add the label definition to the feature layer's label definition collection. highwaysFeatureLayer.LabelDefinitions.Add(highwaysLabelDefinition); // Enable the visibility of labels to be seen. highwaysFeatureLayer.LabelsEnabled = true; // Add the US highways feature layer to the operations layers collection of the map. sampleMap.OperationalLayers.Add(highwaysFeatureLayer); }
private async void Snapping() { Map myMap = null; FeatureLayer fLayer = null; IEnumerable <FeatureLayer> layerList = null; #region Configure Snapping (Turn Snapping on or off) //enable snapping ArcGIS.Desktop.Mapping.Snapping.IsEnabled = true; // disable snapping ArcGIS.Desktop.Mapping.Snapping.IsEnabled = false; #endregion #region Configure Snapping (Application SnapModes) // set only Point and Edge snapping modes, clear everything else ArcGIS.Desktop.Mapping.Snapping.SetSnapModes(SnapMode.Point, SnapMode.Edge); // clear all snap modes ArcGIS.Desktop.Mapping.Snapping.SetSnapModes(); // set snap modes one at a time ArcGIS.Desktop.Mapping.Snapping.SetSnapMode(SnapMode.Edge, true); ArcGIS.Desktop.Mapping.Snapping.SetSnapMode(SnapMode.End, true); ArcGIS.Desktop.Mapping.Snapping.SetSnapMode(SnapMode.Intersection, true); // get current snap modes var snapModes = ArcGIS.Desktop.Mapping.Snapping.SnapModes; // get state of a specific snap mode bool isOn = ArcGIS.Desktop.Mapping.Snapping.GetSnapMode(SnapMode.Vertex); #endregion #region Configure Snapping (Layer Snappability) // is the layer snappable? bool isSnappable = fLayer.IsSnappable; // set snappability for a specific layer - needs to run on the MCT await QueuedTask.Run(() => { // use an extension method fLayer.SetSnappable(true); // or use the CIM directly //var layerDef = fLayer.GetDefinition() as ArcGIS.Core.CIM.CIMGeoFeatureLayerBase; //layerDef.Snappable = true; //fLayer.SetDefinition(layerDef); }); // turn all layers snappability off layerList = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>(); await QueuedTask.Run(() => { foreach (var layer in layerList) { layer.SetSnappable(false); } }); #endregion #region Configure Snapping (LayerSnapModes) layerList = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>(); // configure by layer foreach (var layer in layerList) { // find the state of the snapModes for the layer var lsm = ArcGIS.Desktop.Mapping.Snapping.GetLayerSnapModes(layer); bool vertexOn = lsm.Vertex; // or use vertexOn = lsm.GetSnapMode(SnapMode.Vertex); bool edgeOn = lsm.Edge; // or use edgeOn = lsm.GetSnapMode(SnapMode.Edge); bool endOn = lsm.End; // or use endOn = lsm.GetSnapMode(SnapMode.End); // update a few snapModes // turn Vertex off lsm.SetSnapMode(SnapMode.Vertex, false); // intersections on lsm.SetSnapMode(SnapMode.Intersection, true); // and set back to the layer ArcGIS.Desktop.Mapping.Snapping.SetLayerSnapModes(layer, lsm); // assign a single snap mode at once ArcGIS.Desktop.Mapping.Snapping.SetLayerSnapModes(layer, SnapMode.Vertex, false); // turn ALL snapModes on ArcGIS.Desktop.Mapping.Snapping.SetLayerSnapModes(layer, true); // turn ALL snapModes off ArcGIS.Desktop.Mapping.Snapping.SetLayerSnapModes(layer, false); } // configure for a set of layers // set Vertex, edge, end on for a set of layers, other snapModes false var vee = new LayerSnapModes(false); vee.Vertex = true; vee.Edge = true; vee.End = true; ArcGIS.Desktop.Mapping.Snapping.SetLayerSnapModes(layerList, vee); // ensure intersection is on for a set of layers without changing any other snapModes // get the layer snapModes for the set of layers var dictLSM = ArcGIS.Desktop.Mapping.Snapping.GetLayerSnapModes(layerList); foreach (var layer in dictLSM.Keys) { var lsm = dictLSM[layer]; lsm.Intersection = true; } ArcGIS.Desktop.Mapping.Snapping.SetLayerSnapModes(dictLSM); // set all snapModes off for a list of layers ArcGIS.Desktop.Mapping.Snapping.SetLayerSnapModes(layerList, false); #endregion #region Configure Snapping (Combined Example) // interested in only snapping to the vertices of a specific layer of interest and not the vertices of other layers // all other snapModes should be off. // snapping must be on ArcGIS.Desktop.Mapping.Snapping.IsEnabled = true; // turn all application snapModes off ArcGIS.Desktop.Mapping.Snapping.SetSnapModes(); // set application snapMode vertex on ArcGIS.Desktop.Mapping.Snapping.SetSnapMode(SnapMode.Vertex, true); // ensure layer snapping is on await QueuedTask.Run(() => { fLayer.SetSnappable(true); }); // set vertex snapping only var vertexOnly = new LayerSnapModes(false); vertexOnly.Vertex = true; // set vertex only for the specific layer, clearing all others var dict = new Dictionary <Layer, LayerSnapModes>(); dict.Add(fLayer, vertexOnly); ArcGIS.Desktop.Mapping.Snapping.SetLayerSnapModes(dict, true); // true = reset other layers #endregion #region Snap Options //Set snapping options via get/set options var snapOptions = ArcGIS.Desktop.Mapping.Snapping.GetOptions(myMap); snapOptions.SnapToSketchEnabled = true; snapOptions.XYTolerance = 100; snapOptions.ZToleranceEnabled = true; snapOptions.ZTolerance = 0.6; ArcGIS.Desktop.Mapping.Snapping.SetOptions(myMap, snapOptions); #endregion }
private async void Initialize() { // Create a map with a light gray canvas basemap. Map sampleMap = new Map(Basemap.CreateLightGrayCanvas()); // Assign the map to the MapView. MyMapView.Map = sampleMap; // Define the URL string for the feature layer. string layerUrl = "https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/USA_Congressional_Districts_analysis/FeatureServer/0"; // Create a service feature table from the URL. ServiceFeatureTable featureTable = new ServiceFeatureTable(new System.Uri(layerUrl)); // Create a feature layer from the service feature table. FeatureLayer districtFeatureLabel = new FeatureLayer(featureTable); // Add the feature layer to the operations layers collection of the map. sampleMap.OperationalLayers.Add(districtFeatureLabel); // Load the feature layer - this way we can obtain it's extent. await districtFeatureLabel.LoadAsync(); // Zoom the map view to the extent of the feature layer. await MyMapView.SetViewpointCenterAsync(new MapPoint(-10846309.950860, 4683272.219411, SpatialReferences.WebMercator), 20000000); // Help regarding the Json syntax for defining the LabelDefinition.FromJson syntax can be found here: // https://developers.arcgis.com/web-map-specification/objects/labelingInfo/ // This particular JSON string will have the following characteristics: string redLabelJson = @"{ ""labelExpressionInfo"":{""expression"":""$feature.NAME + ' (' + left($feature.PARTY,1) + ')\\nDistrict' + $feature.CDFIPS""}, ""labelPlacement"":""esriServerPolygonPlacementAlwaysHorizontal"", ""where"":""PARTY = 'Republican'"", ""symbol"": { ""angle"":0, ""backgroundColor"":[0,0,0,0], ""borderLineColor"":[0,0,0,0], ""borderLineSize"":0, ""color"":[255,0,0,255], ""font"": { ""decoration"":""none"", ""size"":10, ""style"":""normal"", ""weight"":""normal"" }, ""haloColor"":[255,255,255,255], ""haloSize"":2, ""horizontalAlignment"":""center"", ""kerning"":false, ""type"":""esriTS"", ""verticalAlignment"":""middle"", ""xoffset"":0, ""yoffset"":0 } }"; string blueLabelJson = @"{ ""labelExpressionInfo"":{""expression"":""$feature.NAME + ' (' + left($feature.PARTY,1) + ')\\nDistrict' + $feature.CDFIPS""}, ""labelPlacement"":""esriServerPolygonPlacementAlwaysHorizontal"", ""where"":""PARTY = 'Democrat'"", ""symbol"": { ""angle"":0, ""backgroundColor"":[0,0,0,0], ""borderLineColor"":[0,0,0,0], ""borderLineSize"":0, ""color"":[0,0,255,255], ""font"": { ""decoration"":""none"", ""size"":10, ""style"":""normal"", ""weight"":""normal"" }, ""haloColor"":[255,255,255,255], ""haloSize"":2, ""horizontalAlignment"":""center"", ""kerning"":false, ""type"":""esriTS"", ""verticalAlignment"":""middle"", ""xoffset"":0, ""yoffset"":0 } }"; // Create a label definition from the JSON string. LabelDefinition redLabelDefinition = LabelDefinition.FromJson(redLabelJson); LabelDefinition blueLabelDefinition = LabelDefinition.FromJson(blueLabelJson); // Add the label definition to the feature layer's label definition collection. districtFeatureLabel.LabelDefinitions.Add(redLabelDefinition); districtFeatureLabel.LabelDefinitions.Add(blueLabelDefinition); // Enable the visibility of labels to be seen. districtFeatureLabel.LabelsEnabled = true; }
public MapForm1() { // // Required for Windows Form Designer support // InitializeComponent(); // Set table search path to value sampledatasearch registry key string s = Environment.CurrentDirectory; Microsoft.Win32.RegistryKey keySamp = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(@"SOFTWARE\MapInfo\MapXtreme\6.6"); if ((keySamp != null) && (keySamp.GetValue("SampleDataSearchPath") != null)) { s = (string)keySamp.GetValue("SampleDataSearchPath"); if (s.EndsWith("\\") == false) { s += "\\"; } keySamp.Close(); } Session.Current.TableSearchPath.Path = s; // Add the USA table to the map mapControl1.Map.Load(new MapTableLoader("usa.tab")); // Listen to the appropriate map event to allow the status bar to be updated mapControl1.Map.ViewChangedEvent += new ViewChangedEventHandler(Map_ViewChanged); // Create a ranged theme on the USA layer. Map map = mapControl1.Map; FeatureLayer lyr = map.Layers["usa"] as MapInfo.Mapping.FeatureLayer; RangedTheme thm = new MapInfo.Mapping.Thematics.RangedTheme( lyr, "Round(MI_Area(Obj, 'sq mi', 'Spherical'), 1)", "Area (square miles)", 5, MapInfo.Mapping.Thematics.DistributionMethod.EqualCountPerRange); lyr.Modifiers.Append(thm); // Create a legend Legend legend = map.Legends.CreateLegend(new Size(5, 5)); // Create a LegendFrame that contains the theme and add that frame to the Legend. ThemeLegendFrame frame = LegendFrameFactory.CreateThemeLegendFrame("Area", "Area", thm); legend.Frames.Append(frame); frame.Title = "Area (sq. mi.)"; // Create a LegendExport and export the legend to a bitmap file. MapInfo.Mapping.LegendExport legendExport = new MapInfo.Mapping.LegendExport(map, legend); legendExport.Format = ExportFormat.Bmp; legendExport.ExportSize = new ExportSize(300, 200); legendExport.Export("legend.bmp"); // Display the legend in a window. System.Windows.Forms.Form legendForm = new LegendForm(); legendForm.BackgroundImage = System.Drawing.Image.FromFile("legend.bmp"); legendForm.Size = new Size(300, 200); legendForm.Show(); // Alternatively, you can add the legend as a child window of the map // by appending it to the Adornments collection. In this case, most likely // a smaller size should be used when the Legend object is created. // //legend.Border = true; //map.Adornments.Append(legend); // Set the initial legend location to be the upper left corner of the map control. //legend.Location = new System.Drawing.Point(mapControl1.Left, mapControl1.Top); }
public static long OutPutFeat(ref IFeatureClass pDesFeatCls, ref IFeatureClass pOriFeatCls, string sSql, IGeometry pDomainGeometry, bool bIsCut, ref ISpatialReference pSpatialReference, Dictionary <string, string> pDicField, ref ProgressBarX vProgressBar, ref LabelX lblInfo, string sInfo) { long functionReturnValue = 0; //DevComponents.DotNetBar.LabelItem IFeatureCursor pWithINFeatCursor = null; IFeatureCursor pFeatCursor = default(IFeatureCursor); IFeatureLayer pFeatLayer = default(IFeatureLayer); IFeatureSelection pFeatSelection = default(IFeatureSelection); int lFeatCount = 0; bool bInsertRight = true; if (pDesFeatCls == null | pOriFeatCls == null) { return(functionReturnValue); } if (pDesFeatCls.ShapeType == esriGeometryType.esriGeometryPoint) { bIsCut = false; } if (pDomainGeometry == null) { bIsCut = false; } //如果需要剪切,则对面要素类和线要素类分成范围内的要素和与范围相交的要素,提高提取效率 //否则,使用featurecursor进行提取,不进行选择,相对要快 if (lblInfo != null) { lblInfo.Text = sInfo + "正在获得满足条件的要素,请稍候....."; lblInfo.Refresh(); Application.DoEvents(); } if (bIsCut) { pFeatLayer = new FeatureLayer(); pFeatLayer.FeatureClass = pOriFeatCls; pFeatLayer.Name = pOriFeatCls.AliasName; //获得选择集 pFeatSelection = ClsSelectAndQuery.GetFeatSelection(ref pFeatLayer, sSql, esriSelectionResultEnum.esriSelectionResultNew, esriSpatialRelEnum.esriSpatialRelIntersects, ref pDomainGeometry); lFeatCount = pFeatSelection.SelectionSet.Count; if (vProgressBar != null) { vProgressBar.Value = 0; vProgressBar.Maximum = lFeatCount; } //获得位范围内的以及与范围相交的要素集 ClsSelectAndQuery.ClassifyFeatCursorByGeometry(ref pFeatSelection, pDomainGeometry, ref pWithINFeatCursor, pDesFeatCls.ShapeType); // 陈昉 2009-3-12 修改 修改原因 原来的方法不能搜索到包含一此Geometry的要素 //ClassifyFeatCursorByGeometry(pFeatSelection, pDomainGeometry, pWithINFeatCursor, pCrossFeatCursor, pDesFeatCls.ShapeType) if (lblInfo != null) { lblInfo.Text = sInfo + "正在输出要素,请稍候....."; lblInfo.Refresh(); Application.DoEvents(); } InsertFeatIntoFeatClsByCursor(ref pDesFeatCls, ref pWithINFeatCursor, true, pDomainGeometry, ref pSpatialReference, pDicField, ref vProgressBar); //首先把位于图幅内的要素插入 //InsertFeatIntoFeatClsByCursor(pDesFeatCls, pWithINFeatCursor, True, pDomainGeometry, pSpatialReference, _ // pDicField, vProgressBar) //'再把与范围相交的要素插入,(插入时需要进行剪切) //InsertFeatIntoFeatClsByCursor(pDesFeatCls, pCrossFeatCursor, True, pDomainGeometry, pSpatialReference, _ // pDicField, vProgressBar) } else { //获得需要提取的要素 long lFeatCount2 = (long)lFeatCount; pFeatCursor = ClsSelectAndQuery.GetFeatCursor(pOriFeatCls, sSql, esriSpatialRelEnum.esriSpatialRelIntersects, ref pDomainGeometry, true, ref lFeatCount2); lFeatCount = (int)lFeatCount2; if (vProgressBar != null) { vProgressBar.Maximum = lFeatCount; vProgressBar.Value = 0; } if (lblInfo != null) { lblInfo.Text = sInfo + "正在输出要素,请稍候....."; lblInfo.Refresh(); Application.DoEvents(); } bInsertRight = InsertFeatIntoFeatClsByCursor(ref pDesFeatCls, ref pFeatCursor, false, pDomainGeometry, ref pSpatialReference, pDicField, ref vProgressBar); //印骅 20081202 Insert失败,退出函数 if (bInsertRight == false) { functionReturnValue = -1; return(functionReturnValue); } } //杨旭斌于20080825添加,返回提取的要素个数 functionReturnValue = lFeatCount; if ((vProgressBar != null)) { //vProgressBar.Visible = False vProgressBar.Value = 0; } pWithINFeatCursor = null; return(functionReturnValue); }
private void VersionsCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Fl = (MyMap.Layers["ServiceConnections"] as FeatureLayer); Fl.GdbVersion = (e.AddedItems[0] as Graphic).Attributes["name"].ToString(); Fl.Update(); }
private static void ZoomToExtent() { RectangleShape resultExtent = null; if (GisEditor.LayerListManager.SelectedLayerListItem == null) { return; } if (GisEditor.LayerListManager.SelectedLayerListItem.ConcreteObject is Overlay && GisEditor.LayerListManager.SelectedLayerListItems.Count > 0) { Collection <RectangleShape> extents = new Collection <RectangleShape>(); foreach (var item in GisEditor.LayerListManager.SelectedLayerListItems) { var tmpOverlay = item.ConcreteObject as Overlay; if (tmpOverlay != null) { extents.Add(tmpOverlay.GetBoundingBox()); } } resultExtent = ExtentHelper.GetBoundingBoxOfItems(extents); } else if (GisEditor.LayerListManager.SelectedLayerListItems.Count > 0) { Collection <RectangleShape> extents = new Collection <RectangleShape>(); foreach (var item in GisEditor.LayerListManager.SelectedLayerListItems) { Layer tmpLayer = item.ConcreteObject as Layer; if (tmpLayer != null && tmpLayer.HasBoundingBox) { tmpLayer.SafeProcess(() => { extents.Add(tmpLayer.GetBoundingBox()); }); //tmpLayer.Open(); //extents.Add(tmpLayer.GetBoundingBox()); //tmpLayer.Close(); } } resultExtent = ExtentHelper.GetBoundingBoxOfItems(extents); } else if (GisEditor.LayerListManager.SelectedLayerListItem.ConcreteObject is Overlay) { resultExtent = (GisEditor.LayerListManager.SelectedLayerListItem.ConcreteObject as Overlay).GetBoundingBox(); } else if (GisEditor.LayerListManager.SelectedLayerListItem.ConcreteObject is Layer) { Layer layer = GisEditor.LayerListManager.SelectedLayerListItem.ConcreteObject as Layer; if (layer.HasBoundingBox) { layer.SafeProcess(() => { resultExtent = layer.GetBoundingBox(); }); } } else if (GisEditor.LayerListManager.SelectedLayerListItem.ConcreteObject is ValueItem) { string value = ((ValueItem)GisEditor.LayerListManager.SelectedLayerListItem.ConcreteObject).Value; string columnName = ((ValueStyle)GisEditor.LayerListManager.SelectedLayerListItem.Parent.ConcreteObject).ColumnName; FeatureLayer featureLayer = LayerListHelper.FindMapElementInTree <FeatureLayer>(GisEditor.LayerListManager.SelectedLayerListItem); if (featureLayer != null) { System.Windows.Forms.DialogResult dialogResult = System.Windows.Forms.DialogResult.Yes; FeatureLayerPlugin[] layerPlugins = GisEditor.LayerManager.GetLayerPlugins(featureLayer.GetType()).OfType <FeatureLayerPlugin>().ToArray(); if (layerPlugins.Length > 0 && !layerPlugins[0].CanQueryFeaturesEfficiently) { dialogResult = System.Windows.Forms.MessageBox.Show(GisEditor.LanguageManager.GetStringResource("ZoomToExtentWarning"), GisEditor.LanguageManager.GetStringResource("MapElementsListPluginZoomToExtent"), System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Information); } if (dialogResult == System.Windows.Forms.DialogResult.Yes) { Collection <Feature> features = new Collection <Feature>(); featureLayer.SafeProcess(() => { features = featureLayer.QueryTools.GetFeaturesByColumnValue(columnName, value); resultExtent = ExtentHelper.GetBoundingBoxOfItems(features); }); if (features.Count == 0) { MessageBoxHelper.ShowMessage("No features matched.", "Zoom to extent", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information); } } } } if (resultExtent != null) { GisEditor.ActiveMap.CurrentExtent = resultExtent; GisEditor.ActiveMap.Refresh(); } }
//开始提取 private void Deal() { IWorkspace pWorkspace = default(IWorkspace); //grouplayer中图层可见性 string sDesFeatClsName = null; IFeatureClass pDesFeatCls = default(IFeatureClass); string sInfo = null; IFeatureLayer pFeatLayer = default(IFeatureLayer); IFeatureClass pFeatureCls = default(IFeatureClass); int ErrorCount = 0; ErrorCount = 0; if (_map.LayerCount == 0) { //g_clsErrorHandle.DisplayInformation("没有加载图层或没有图层处于选中状态!请选中需要提取的图层!", false); MessageBoxEx.Show("没有加载图层或没有图层处于选中状态!请选中需要提取的图层!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //WHFUtilities.clsLog ploger = default(WHFUtilities.clsLog); //// 陈昉 2009-2-23 修改 修改原因 写日志 IDataset pTempDataset = default(IDataset); int iCount = 0; //ploger = new WHFUtilities.clsLog(); //ploger.DBConnectionString = "Data Source=" + g_Sys.DbName + ";User ID=" + g_Sys.DbUser + " ;Password="******"当前操作层:" + pFeatLayer.Name; this.lblInfo.Text = sInfo; Application.DoEvents(); if (!string.IsNullOrEmpty(sDesFeatClsName.Trim())) { if (pFeatureCls != null) { this.lblInfo.Text = sInfo + "正在获得目标要素类,请稍候...."; lblInfo.Refresh(); Application.DoEvents(); if (sDesFeatClsName.Contains(".")) { int dotIndex = 0; dotIndex = sDesFeatClsName.IndexOf("."); sDesFeatClsName = sDesFeatClsName.Substring(dotIndex + 1, sDesFeatClsName.Length - dotIndex - 1); } IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspace; IFields pFields = pFeatureCls.Fields; pDesFeatCls = ClsCreatAndGetDataset.CreatOrOpenFeatClsByName(ref pFeatureWorkspace, sDesFeatClsName, ref pFields, null, null); pWorkspace = (IWorkspace)pFeatureWorkspace; //pFeatureCls.Fields = pFields; if (pDesFeatCls != null) { //如果不剪切的,则使用该方法,需要剪切,则使用选择集,分位于内部要素和位于外部要素或直接使用pfeatcls搜索二遍 //如果数据量大的话,搜索二遍的方法是不可行的 ISpatialReference pSpatialRefer = null; iCount = (int)ClsCreateFeat.OutPutFeat(ref pDesFeatCls, ref pFeatureCls, "", null, false, ref pSpatialRefer, null, ref this.lblInfo, sInfo); IFeatureLayer showFeatureLayer = new FeatureLayer(); showFeatureLayer.FeatureClass = pDesFeatCls; ILayer showLayer = showFeatureLayer as ILayer; showLayer.Name = pDesFeatCls.AliasName + "_Extract"; _map.AddLayer(showLayer); if (iCount > 0) { pTempDataset = (IDataset)pFeatureCls; //// 陈昉 2009-3-1 修改 修改原因 写日志 //ploger.log(System.Environment.MachineName, g_Sys.User.UserID, System.DateTime.Now.ToString(), "数据管理子系统", "WHFDataExtract", "快速提取" + pTempDataset.Name + "中" + iCount + "个要素到" + pDesFeatCls.AliasName, "目标 :" + System.IO.Path.GetFileName(pWorkspace.PathName)); } } else { ErrorCount = ErrorCount + 1; } } } } } if (intChooseLayer == 0) { MessageBoxEx.Show("没有选择提取要素,请选择!", "提示"); return; } this.Refresh(); Application.DoEvents(); if (ErrorCount > 0) { this.lblInfo.Text = "操作中有错误发生!"; //g_clsErrorHandle.DisplayInformation("操作中有错误发生!", false); MessageBoxEx.Show("操作中有错误发生!", "提示"); return; } else { //Member member = new Member(); //member.AddLayerToMap(pWorkspace, _map); this.lblInfo.Text = "操作完成!"; //g_clsErrorHandle.DisplayInformation("操作完成!", false); MessageBoxEx.Show("操作完成!", "提示"); } }
public static void ReplaceFromLibrary() { StyleLibraryWindow library = new StyleLibraryWindow(); if (library.ShowDialog().GetValueOrDefault()) { if (GisEditor.LayerListManager.SelectedLayerListItem == null) { return; } var styleItem = GisEditor.LayerListManager.SelectedLayerListItem; //var styleItem = GisEditor.LayerListManager.SelectedLayerListItem.ConcreteObject as StyleItem; //if (styleItem != null) { TileOverlay containingOverlay = null; var compositeStyle = GisEditor.LayerListManager.SelectedLayerListItem.ConcreteObject as CompositeStyle; if (compositeStyle != null) { FeatureLayer currentFeatureLayer = GisEditor.LayerListManager.SelectedLayerListItem.Parent.ConcreteObject as FeatureLayer; if (currentFeatureLayer != null) { foreach (var zoomLevel in currentFeatureLayer.ZoomLevelSet.CustomZoomLevels) { var index = zoomLevel.CustomStyles.IndexOf(compositeStyle); if (index >= 0) { zoomLevel.CustomStyles.RemoveAt(index); zoomLevel.CustomStyles.Insert(index, library.Result.CompositeStyle); } } containingOverlay = GisEditor.LayerListManager.SelectedLayerListItem.Parent.Parent.ConcreteObject as TileOverlay; } } else if (styleItem.ConcreteObject is Styles.Style && styleItem.Parent.ConcreteObject is Styles.Style) { var index = styleItem.Parent.Children.IndexOf(styleItem); styleItem.Parent.Children.RemoveAt(index); var compositeStyleItem = GisEditor.StyleManager.GetStyleLayerListItem(library.Result.CompositeStyle); foreach (var item in compositeStyleItem.Children) { styleItem.Parent.Children.Insert(index, item); index++; } ((StyleLayerListItem)styleItem.Parent).UpdateConcreteObject(); containingOverlay = LayerListHelper.FindMapElementInTree <TileOverlay>(GisEditor.LayerListManager.SelectedLayerListItem); } else { styleItem.Children.Clear(); var compositeStyleItem = GisEditor.StyleManager.GetStyleLayerListItem(library.Result.CompositeStyle); foreach (var item in compositeStyleItem.Children) { styleItem.Children.Add(item); } ((StyleLayerListItem)styleItem).UpdateConcreteObject(); containingOverlay = LayerListHelper.FindMapElementInTree <TileOverlay>(GisEditor.LayerListManager.SelectedLayerListItem); } if (containingOverlay != null) { containingOverlay.Invalidate(); GisEditor.UIManager.InvokeRefreshPlugins(new RefreshArgs(containingOverlay, RefreshArgsDescriptions.ReplaceFromLibraryDescription)); } } } }
private async void Initialize() { try { IsBusy.Visibility = Visibility.Visible; Status.Text = "Loading Utility Network..."; // Create a map. MyMapView.Map = new Map(Basemap.CreateStreetsNightVector()) { InitialViewpoint = _startingViewpoint }; // Add the layer with electric distribution lines. FeatureLayer lineLayer = new FeatureLayer(new Uri($"{FeatureServiceUrl}/115")); UniqueValue mediumVoltageValue = new UniqueValue("N/A", "Medium Voltage", new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.DarkCyan, 3), 5); UniqueValue lowVoltageValue = new UniqueValue("N/A", "Low Voltage", new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, System.Drawing.Color.DarkCyan, 3), 3); lineLayer.Renderer = new UniqueValueRenderer(new List <string>() { "ASSETGROUP" }, new List <UniqueValue>() { mediumVoltageValue, lowVoltageValue }, "", new SimpleLineSymbol()); MyMapView.Map.OperationalLayers.Add(lineLayer); // Add the layer with electric devices. FeatureLayer electricDevicelayer = new FeatureLayer(new Uri($"{FeatureServiceUrl}/100")); MyMapView.Map.OperationalLayers.Add(electricDevicelayer); // Set the selection color for features in the map view. MyMapView.SelectionProperties = new SelectionProperties(System.Drawing.Color.Yellow); // Create and load the utility network. _utilityNetwork = await UtilityNetwork.CreateAsync(new Uri(FeatureServiceUrl), MyMapView.Map); // Update the trace configuration UI. TraceTypes.ItemsSource = new List <UtilityTraceType>() { UtilityTraceType.Connected, UtilityTraceType.Subnetwork, UtilityTraceType.Upstream, UtilityTraceType.Downstream }; TraceTypes.SelectedIndex = 0; // Get the utility tier used for traces in this network. For this data set, the "Medium Voltage Radial" tier from the "ElectricDistribution" domain network is used. UtilityDomainNetwork domainNetwork = _utilityNetwork.Definition.GetDomainNetwork("ElectricDistribution"); _mediumVoltageTier = domainNetwork.GetTier("Medium Voltage Radial"); // More complex datasets may require using utility trace configurations from different tiers. The following LINQ expression gets all tiers present in the utility network. //IEnumerable<UtilityTier> tiers = _utilityNetwork.Definition.DomainNetworks.Select(domain => domain.Tiers).SelectMany(tier => tier); // Create symbols for starting locations and barriers. _startingPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Cross, System.Drawing.Color.LightGreen, 25d); _barrierPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.X, System.Drawing.Color.OrangeRed, 25d); // Create a graphics overlay. GraphicsOverlay graphicsOverlay = new GraphicsOverlay(); MyMapView.GraphicsOverlays.Add(graphicsOverlay); // Set the instruction text. Status.Text = "Click on the network lines or points to add a utility element."; } catch (Exception ex) { Status.Text = "Loading Utility Network failed..."; MessageBox.Show(ex.Message, ex.GetType().Name, MessageBoxButton.OK, MessageBoxImage.Error); } finally { MainUI.IsEnabled = true; IsBusy.Visibility = Visibility.Hidden; } }
public ConfigTinyGeoFileUserControl(FeatureLayer featureLayer) { InitializeComponent(); lbxFeatureLayers.ItemsSource = GisEditor.ActiveMap.GetFeatureLayers(); txtOutput.Text = ConfigShapeFileViewModel.GetDefaultOutputPath(); }