private async void StartLocalMapService(string filename, string path) { // Start a service from the blank MPK string mapServiceUrl = GetMpkPath(); // Create the local map service _localMapService = new LocalMapService(mapServiceUrl); // Create the Raster workspace; this workspace name was chosen arbitrarily RasterWorkspace rasterWorkspace = new RasterWorkspace("ras_wkspc", path); // Create the layer source that represents the Raster on disk RasterSublayerSource source = new RasterSublayerSource(rasterWorkspace.Id, filename); // Create a sublayer instance from the table source _rasterSublayer = new ArcGISMapImageSublayer(0, source); // Add the dynamic workspace to the map service _localMapService.SetDynamicWorkspaces(new List <DynamicWorkspace>() { rasterWorkspace }); // Subscribe to notifications about service status changes _localMapService.StatusChanged += _localMapService_StatusChanged; // Start the map service await _localMapService.StartAsync(); }
public ViewModel() { myModel = new Model(); localMapService = new LocalMapService(myModel.MapPackage); starting += onStarting; starting(this, EventArgs.Empty); }
private void CreateServices() { try { // Arrange the data before starting the services string mapServicePath = GetMpkPath(); string featureServicePath = GetFeatureLayerPath(); string geoprocessingPath = GetGpPath(); // Create each service but don't start any _localMapService = new LocalMapService(mapServicePath); _localFeatureService = new LocalFeatureService(featureServicePath); _localGeoprocessingService = new LocalGeoprocessingService(geoprocessingPath); // Subscribe to status updates for each service _localMapService.StatusChanged += (o, e) => { UpdateUiWithServiceUpdate("Map Service", e.Status); }; _localFeatureService.StatusChanged += (o, e) => { UpdateUiWithServiceUpdate("Feature Service", e.Status); }; _localGeoprocessingService.StatusChanged += (o, e) => { UpdateUiWithServiceUpdate("Geoprocessing Service", e.Status); }; // Enable the UI to select services ServiceSelectionCombo.IsEnabled = true; } catch (Exception ex) { MessageBox.Show(ex.Message, "Failed to create services"); } }
private async void StartLocalMapService(string filename, string path) { // Start a service from the blank MPK String mapServiceUrl = GetMpkPath(); // Create the local map service _localMapService = new LocalMapService(mapServiceUrl); // Create the shapefile workspace ShapefileWorkspace shapefileWorkspace = new ShapefileWorkspace("shp_wkspc", path); // Create the layer source that represents the shapefile on disk TableSublayerSource source = new TableSublayerSource(shapefileWorkspace.Id, filename); // Create a sublayer instance from the table source _shapefileSublayer = new ArcGISMapImageSublayer(0, source); // Add the dynamic workspace to the map service _localMapService.SetDynamicWorkspaces(new List <DynamicWorkspace>() { shapefileWorkspace }); // Subscribe to notifications about service status changes _localMapService.StatusChanged += _localMapService_StatusChanged; // Start the map service await _localMapService.StartAsync(); }
private async void Initialize() { // Create a map and add it to the view MyMapView.Map = new Map(Basemap.CreateLightGrayCanvas()); try { // LocalServer must not be running when setting the data path. if (LocalServer.Instance.Status == LocalServerStatus.Started) { await LocalServer.Instance.StopAsync(); } // Set the local data path - must be done before starting. On most systems, this will be C:\EsriSamples\AppData. // This path should be kept short to avoid Windows path length limitations. string tempDataPathRoot = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.Windows)).FullName; string tempDataPath = Path.Combine(tempDataPathRoot, "EsriSamples", "AppData"); Directory.CreateDirectory(tempDataPath); // CreateDirectory won't overwrite if it already exists. LocalServer.Instance.AppDataPath = tempDataPath; // Start the local server instance await LocalServer.Instance.StartAsync(); // Get the path to the map package that will be served string datapath = GetDataPath(); // Create the Map Service from the data _localMapService = new LocalMapService(datapath); // Start the feature service await _localMapService.StartAsync(); // Get the url to the map service Uri myServiceUri = _localMapService.Url; // Create the layer from the url ArcGISMapImageLayer myImageLayer = new ArcGISMapImageLayer(myServiceUri); // Add the layer to the map MyMapView.Map.OperationalLayers.Add(myImageLayer); // Wait for the layer to load await myImageLayer.LoadAsync(); // Set the viewpoint on the map to show the data MyMapView.SetViewpoint(new Viewpoint(myImageLayer.FullExtent)); } catch (Exception ex) { var localServerTypeInfo = typeof(LocalMapService).GetTypeInfo(); var localServerVersion = FileVersionInfo.GetVersionInfo(localServerTypeInfo.Assembly.Location); var dlg = new MessageDialog2($"Please ensure that local server {localServerVersion.FileVersion} is installed prior to using the sample. The download link is in the description. Message: {ex.Message}", "Local Server failed to start"); _ = dlg.ShowAsync(); } }
public async void CreateLocalServiceAndDynamicLayer() { LocalMapService localMapService = new LocalMapService(this.MapPackage); await localMapService.StartAsync(); ArcGISDynamicMapServiceLayer arcGISDynamicMapServiceLayer = new ArcGISDynamicMapServiceLayer() { ID = "Restaurants", ServiceUri = localMapService.UrlMapService, }; this.mapView.Map.Layers.Add(arcGISDynamicMapServiceLayer); }
private async void StopServerButtonClicked(object sender, RoutedEventArgs e) { // Update the UI btnServiceStart.IsEnabled = false; btnServiceStop.IsEnabled = false; LocalServerStartButton.IsEnabled = true; LocalServerStopButton.IsEnabled = false; // Stop the server await LocalServer.Instance.StopAsync(); // Clear references to the services _localFeatureService = null; _localMapService = null; _localGeoprocessingService = null; }
public async void CreateLocalServiceAndDynamicLayer() { try { LocalMapService localMapService = new LocalMapService(@"..\..\..\..\..\samples-data\maps\water-distribution-network.mpk"); await localMapService.StartAsync(); ArcGISDynamicMapServiceLayer arcGISDynamicMapServiceLayer = new ArcGISDynamicMapServiceLayer() { ID = "arcGISDynamicMapServiceLayer", ServiceUri = localMapService.UrlMapService, }; MyMapView.Map.Layers.Add(arcGISDynamicMapServiceLayer); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public async void CreateLocalServiceAndDynamicLayer() { try { LocalMapService localMapService = new LocalMapService(@"..\..\..\samples-data\maps\water-distribution-network.mpk"); await localMapService.StartAsync(); ArcGISDynamicMapServiceLayer arcGISDynamicMapServiceLayer = new ArcGISDynamicMapServiceLayer() { ID = "arcGISDynamicMapServiceLayer", ServiceUri = localMapService.UrlMapService, }; MyMapView.Map.Layers.Add(arcGISDynamicMapServiceLayer); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// 加载本地Map服务,并加载底图 /// </summary> /// <param name="myMapView"></param> public async void CreatLocalMapService(MapView myMapView) { try { var localMapServiceUri = ConfigurationSettings.AppSettings["LocalMapServiceUri"]; var localMapService = new LocalMapService(localMapServiceUri); await localMapService.StartAsync(); var arcGISDynamicMapServiceLayer = new ArcGISDynamicMapServiceLayer { ID = "arcGISDynamicMapServiceLayer", DisplayName = "测试图层", ServiceUri = localMapService.UrlMapService }; myMapView.Map.Layers.Add(arcGISDynamicMapServiceLayer); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private async void Initialize() { // Create a map and add it to the view MyMapView.Map = new Map(Basemap.CreateLightGrayCanvasVector()); try { // Start the local server instance await LocalServer.Instance.StartAsync(); // Get the path to the map package that will be served string datapath = GetDataPath(); // Create the Map Service from the data _localMapService = new LocalMapService(datapath); // Start the feature service await _localMapService.StartAsync(); // Get the url to the map service Uri myServiceUri = _localMapService.Url; // Create the layer from the url ArcGISMapImageLayer myImageLayer = new ArcGISMapImageLayer(myServiceUri); // Add the layer to the map MyMapView.Map.OperationalLayers.Add(myImageLayer); // Wait for the layer to load await myImageLayer.LoadAsync(); // Set the viewpoint on the map to show the data MyMapView.SetViewpoint(new Viewpoint(myImageLayer.FullExtent)); } catch (Exception ex) { MessageBox.Show(string.Format("Please ensure that local server is installed prior to using the sample. See instructions in readme.md or metadata.json. Message: {0}", ex.Message), "Local Server failed to start"); } }
public MainWindow() { // License setting and ArcGIS Runtime initialization is done in Application.xaml.cs. InitializeComponent(); /* * Asynchronously start all the services... */ LocalGeoprocessingService.GetServiceAsync(@"..\Maps-and-Data\TraceGeometricNetwork.gpk", GPServiceType.SubmitJob, localServiceCallback => { if (localServiceCallback.Error != null) { MessageBox.Show(localServiceCallback.Error.Message); return; } traceNetworkLocalGpService = localServiceCallback; geoprocessorTask = new Geoprocessor(traceNetworkLocalGpService.Tasks[0].Url); // Enable the UI when the Trace Geometric Network service is available TraceUpstreamButton.IsEnabled = true; }); LocalGeometryService.GetServiceAsync(callback => { localGeometryService = callback; geometryTask = new GeometryService(); geometryTask.Url = localGeometryService.UrlGeometryService; }); LocalMapService.GetServiceAsync(@"..\Maps-and-Data\WaterDistributionNetwork.mpk", callback => { if (callback.Error != null) { MessageBox.Show("WaterDistributionNetwork map failed to load"); return; } waterNetworkLocalMapService = callback; ArcGISLocalDynamicMapServiceLayer WaterDistributionNetworkLayer = new ArcGISLocalDynamicMapServiceLayer(waterNetworkLocalMapService); MyMap.Layers.Insert(1, WaterDistributionNetworkLayer); }); /* * Create the Results GraphicsLayers and associated Renderers */ valvesGraphicsLayer = new GraphicsLayer() { Renderer = new SimpleRenderer() { Symbol = MainGrid.Resources["ValveMarkerSymbol"] as Symbol } }; mainsGraphicsLayer = new GraphicsLayer() { Renderer = new SimpleRenderer() { Symbol = new SimpleLineSymbol() { Color = new SolidColorBrush(Colors.Red), Width = 8, Style = SimpleLineSymbol.LineStyle.Dash } } }; // Add the GraphicsLayers to the Map MyMap.Layers.Add(mainsGraphicsLayer); MyMap.Layers.Add(valvesGraphicsLayer); }
private async Task<ArcGISDynamicMapServiceLayer> AddFileDatasetToDynamicMapServiceLayer(WorkspaceFactoryType workspaceType, string directoryPath, List<string> fileNames) { try { // Create a new WorkspaceInfo object with a unique ID. string uniqueId = Guid.NewGuid().ToString(); WorkspaceInfo workspaceInfo = new WorkspaceInfo(uniqueId, workspaceType, "DATABASE=" + directoryPath); // Create and initialize a new LocalMapService instance. LocalMapService localMapService = new LocalMapService(_emptyMapPackage) { EnableDynamicLayers = true }; localMapService.DynamicWorkspaces.Add(workspaceInfo); await localMapService.StartAsync(); // Create and initialize new ArcGISLocalDynamicMapServiceLayer over the local service. var dynLayer = new ArcGISDynamicMapServiceLayer() { ID = "Workspace: " + (new DirectoryInfo(directoryPath)).Name, ServiceUri = localMapService.UrlMapService }; await dynLayer.InitializeAsync(); // Create a DynamicLayerInfoCollection to hold the new datasets as "dynamic layers". DynamicLayerInfoCollection dynamicLayerInfoCollection = new DynamicLayerInfoCollection(); dynLayer.DynamicLayerInfos = dynamicLayerInfoCollection; // Create a LayerDrawingOptionsCollection to specify the symbology for each layer. LayerDrawingOptionCollection layerDrawingOptionsCollection = new LayerDrawingOptionCollection(); dynLayer.LayerDrawingOptions = layerDrawingOptionsCollection; // Iterate over each of the selected files in the workspace. int counter = 0; foreach (string fileName in fileNames) { // Create a new DynamicLayerInfo (to make changes to existing map service layers use the CreateDynamicLayerInfosFromLayerInfos() method. DynamicLayerInfo dynamicLayerInfo = new DynamicLayerInfo { ID = counter, Name = "Dataset: " + fileName }; // Create a DataSource object to represent the physical datasource implementation (table or raster) which will become the DataSource // property of a new LayerDataSource in the map service. Other supported datasource types are JoinDataSource and QueryDataSource. DataSource dataSource = null; // If the workspace type is Raster create a new RasterDataSource. if (workspaceInfo.FactoryType == WorkspaceFactoryType.Raster) { // Create a new RasterDataSource object dataSource = new RasterDataSource { // Match the DataSourceName to the physical filename on disk (including extension). DataSourceName = fileName, // Provide the WorkspaceID (the unique workspace identifier created earlier). A LocalMapService may have multiple dynamic workspaces. WorkspaceID = workspaceInfo.Id }; } else { // Else if the workspace is not Raster create a new TableDataSource dataSource = new TableDataSource { // Match the DataSourceName to the physical filename on disk (excluding extension). DataSourceName = fileName, // Provide the WorkspaceID (the unique workspace identifier created earlier). A LocalMapService may have multiple dynamic workspaces. WorkspaceID = workspaceInfo.Id }; } // Set the Source property of the DynamicLayerInfo object. dynamicLayerInfo.Source = new LayerDataSource { DataSource = dataSource }; // Add the new DynamicLayerInfo object to the collection. dynamicLayerInfoCollection.Add(dynamicLayerInfo); // Create a new LayerDrawingOptions object to hold the renderer information. var layerDrawOpt = new LayerDrawingOptions() { // Match up the LayerID to the ID of the layer within the service. LayerID = counter, }; // Use the GetDetails method which now supports dynamic data sources to determine the geometry type of the new datasource. var featureLayerInfo = await dynLayer.GetDetailsAsync(dynamicLayerInfo.ID); switch (featureLayerInfo.GeometryType) { case GeometryType.Envelope: layerDrawOpt.Renderer = new SimpleRenderer() { Symbol = new SimpleFillSymbol() { Color = GetRandomColor(), Outline = new SimpleLineSymbol() { Color = GetRandomColor() } } }; break; case GeometryType.MultiPoint: layerDrawOpt.Renderer = new SimpleRenderer() { Symbol = new SimpleMarkerSymbol() { Color = GetRandomColor(), Size = 8 } }; break; case GeometryType.Point: layerDrawOpt.Renderer = new SimpleRenderer() { Symbol = new SimpleMarkerSymbol() { Color = GetRandomColor(), Size = 8 } }; break; case GeometryType.Polygon: layerDrawOpt.Renderer = new SimpleRenderer() { Symbol = new SimpleFillSymbol() { Color = GetRandomColor(), Outline = new SimpleLineSymbol() { Color = GetRandomColor() } } }; break; case GeometryType.Polyline: layerDrawOpt.Renderer = new SimpleRenderer() { Symbol = new SimpleLineSymbol() { Color = GetRandomColor() } }; break; default: break; } // Set the LayerDrawingOptions property on the local dynamic map service layer (the LayerID property ties this to the DynamicLayerInfo object). layerDrawingOptionsCollection.Add(layerDrawOpt); counter++; } return dynLayer; } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); return null; } }
private async Task <ArcGISDynamicMapServiceLayer> AddFileDatasetToDynamicMapServiceLayer(WorkspaceFactoryType workspaceType, string directoryPath, List <string> fileNames) { try { // Create a new WorkspaceInfo object with a unique ID. string uniqueId = Guid.NewGuid().ToString(); WorkspaceInfo workspaceInfo = new WorkspaceInfo(uniqueId, workspaceType, "DATABASE=" + directoryPath); // Create and initialize a new LocalMapService instance. LocalMapService localMapService = new LocalMapService(_emptyMapPackage) { EnableDynamicLayers = true }; localMapService.DynamicWorkspaces.Add(workspaceInfo); await localMapService.StartAsync(); // Create and initialize new ArcGISLocalDynamicMapServiceLayer over the local service. var dynLayer = new ArcGISDynamicMapServiceLayer() { ID = "Workspace: " + (new DirectoryInfo(directoryPath)).Name, ServiceUri = localMapService.UrlMapService }; await dynLayer.InitializeAsync(); // Create a DynamicLayerInfoCollection to hold the new datasets as "dynamic layers". DynamicLayerInfoCollection dynamicLayerInfoCollection = new DynamicLayerInfoCollection(); dynLayer.DynamicLayerInfos = dynamicLayerInfoCollection; // Create a LayerDrawingOptionsCollection to specify the symbology for each layer. LayerDrawingOptionCollection layerDrawingOptionsCollection = new LayerDrawingOptionCollection(); dynLayer.LayerDrawingOptions = layerDrawingOptionsCollection; // Iterate over each of the selected files in the workspace. int counter = 0; foreach (string fileName in fileNames) { // Create a new DynamicLayerInfo (to make changes to existing map service layers use the CreateDynamicLayerInfosFromLayerInfos() method. DynamicLayerInfo dynamicLayerInfo = new DynamicLayerInfo { ID = counter, Name = "Dataset: " + fileName }; // Create a DataSource object to represent the physical datasource implementation (table or raster) which will become the DataSource // property of a new LayerDataSource in the map service. Other supported datasource types are JoinDataSource and QueryDataSource. DataSource dataSource = null; // If the workspace type is Raster create a new RasterDataSource. if (workspaceInfo.FactoryType == WorkspaceFactoryType.Raster) { // Create a new RasterDataSource object dataSource = new RasterDataSource { // Match the DataSourceName to the physical filename on disk (including extension). DataSourceName = fileName, // Provide the WorkspaceID (the unique workspace identifier created earlier). A LocalMapService may have multiple dynamic workspaces. WorkspaceID = workspaceInfo.Id }; } else { // Else if the workspace is not Raster create a new TableDataSource dataSource = new TableDataSource { // Match the DataSourceName to the physical filename on disk (excluding extension). DataSourceName = fileName, // Provide the WorkspaceID (the unique workspace identifier created earlier). A LocalMapService may have multiple dynamic workspaces. WorkspaceID = workspaceInfo.Id }; } // Set the Source property of the DynamicLayerInfo object. dynamicLayerInfo.Source = new LayerDataSource { DataSource = dataSource }; // Add the new DynamicLayerInfo object to the collection. dynamicLayerInfoCollection.Add(dynamicLayerInfo); // Create a new LayerDrawingOptions object to hold the renderer information. var layerDrawOpt = new LayerDrawingOptions() { // Match up the LayerID to the ID of the layer within the service. LayerID = counter, }; // Use the GetDetails method which now supports dynamic data sources to determine the geometry type of the new datasource. var featureLayerInfo = await dynLayer.GetDetailsAsync(dynamicLayerInfo.ID); switch (featureLayerInfo.GeometryType) { case GeometryType.Envelope: layerDrawOpt.Renderer = new SimpleRenderer() { Symbol = new SimpleFillSymbol() { Color = GetRandomColor(), Outline = new SimpleLineSymbol() { Color = GetRandomColor() } } }; break; case GeometryType.Multipoint: layerDrawOpt.Renderer = new SimpleRenderer() { Symbol = new SimpleMarkerSymbol() { Color = GetRandomColor(), Size = 8 } }; break; case GeometryType.Point: layerDrawOpt.Renderer = new SimpleRenderer() { Symbol = new SimpleMarkerSymbol() { Color = GetRandomColor(), Size = 8 } }; break; case GeometryType.Polygon: layerDrawOpt.Renderer = new SimpleRenderer() { Symbol = new SimpleFillSymbol() { Color = GetRandomColor(), Outline = new SimpleLineSymbol() { Color = GetRandomColor() } } }; break; case GeometryType.Polyline: layerDrawOpt.Renderer = new SimpleRenderer() { Symbol = new SimpleLineSymbol() { Color = GetRandomColor() } }; break; default: break; } // Set the LayerDrawingOptions property on the local dynamic map service layer (the LayerID property ties this to the DynamicLayerInfo object). layerDrawingOptionsCollection.Add(layerDrawOpt); counter++; } return(dynLayer); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); return(null); } }
/// <summary> /// Adds a file dataset (Shapefile or raster) to a new local dynamic map service layer. /// </summary> /// <param name="workspaceType">The workspace type (FileGDB, Raster, SDE, Shapefile) <see cref="http://resources.arcgis.com/en/help/runtime-wpf/apiref/index.html?ESRI.ArcGIS.Client.Local~ESRI.ArcGIS.Client.Local.WorkspaceFactoryType.html"/>.</param> /// <param name="directoryPath">A <see cref="System.String"/> representing the directory path.</param> /// <param name="fileNames">A <see cref="System.Collections.Generic.List{System.String}"/> representing the name of the file (for raster datasets this must include the extension).</param> /// <param name="callback">The Action delegate to call back on once the dynamic layer work is complete.</param> public void AddFileDatasetToDynamicMapServiceLayer(WorkspaceFactoryType workspaceType, string directoryPath, List <string> fileNames, Action <ArcGISLocalDynamicMapServiceLayer> callback) { try { // Generate a unique workspace ID (any unique string). string uniqueId = Guid.NewGuid().ToString(); // Create a new WorkspaceInfo object with a unique ID. WorkspaceInfo workspaceInfo = new WorkspaceInfo(uniqueId, workspaceType, "DATABASE=" + directoryPath); // Create a new LocalMapService instance. LocalMapService localMapService = new LocalMapService { // Set the path property. Path = _emptyMpkPath, // Enable the dynamic layers capability. EnableDynamicLayers = true }; // Register the workspace to be used with this service. localMapService.DynamicWorkspaces.Add(workspaceInfo); // Asynchronously start the local map service. localMapService.StartAsync(x => { // Create the local dynamic map service layer. ArcGISLocalDynamicMapServiceLayer arcGisLocalDynamicMapServiceLayer = null; // Create a new ArcGISLocalDynamicMapServiceLayer passing in the newly started local service. arcGisLocalDynamicMapServiceLayer = new ArcGISLocalDynamicMapServiceLayer(localMapService) { // Assign the filename as the map layer ID. ID = "Workspace: " + (new DirectoryInfo(directoryPath)).Name, // Enable the dynamic layers capability. EnableDynamicLayers = true, }; // Handle the layer initialized event inline to perform the layer dynamic layer management. arcGisLocalDynamicMapServiceLayer.Initialized += (s, e) => { // Create a DynamicLayerInfoCollection to hold the new datasets as "dynamic layers". DynamicLayerInfoCollection dynamicLayerInfoCollection = new DynamicLayerInfoCollection(); // Create a LayerDrawingOptionsCollection to specify the symbology for each layer. LayerDrawingOptionsCollection layerDrawingOptionsCollection = new LayerDrawingOptionsCollection(); // Iterate over each of the selected files in the workspace. int counter = 0; foreach (string fileName in fileNames) { // Create a new DynamicLayerInfo (to make changes to existing map service layers use the CreateDynamicLayerInfosFromLayerInfos() method. DynamicLayerInfo dynamicLayerInfo = new DynamicLayerInfo { // Assign a layer ID. ID = counter, // Specify a friendly name. Name = "Dataset: " + fileName }; // Create a DataSource object to represent the physical datasource implementation (table or raster) which will become the DataSource // property of a new LayerDataSource in the map service. Other supported datasource types are JoinDataSource and QueryDataSource. DataSource dataSource = null; // If the workspace type is Raster create a new RasterDataSource. if (workspaceInfo.FactoryType == WorkspaceFactoryType.Raster) { // Create a new RasterDataSource object dataSource = new RasterDataSource { // Match the DataSourceName to the physical filename on disk (including extension). DataSourceName = fileName, // Provide the WorkspaceID (the unique workspace identifier created earlier). A LocalMapService may have multiple dynamic workspaces. WorkspaceID = workspaceInfo.Id }; } else { // Else if the workspace is not Raster create a new TableDataSource dataSource = new TableDataSource { // Match the DataSourceName to the physical filename on disk (excluding extension). DataSourceName = fileName, // Provide the WorkspaceID (the unique workspace identifier created earlier). A LocalMapService may have multiple dynamic workspaces. WorkspaceID = workspaceInfo.Id }; /* * Apply a renderer for vector layers. * Note: It is always necessary to provide a renderer when the layer being added (represented by a DynamicLayerInfo) is part of a new * DynamicLayerInfoCollection as opposed to using the CreateDynamicLayerInfosFromLayerInfos() method which creates a DynamicLayerInfoCollection * containing the existing layers in the map service. */ // Create a new LayerDrawingOptions object to hold the renderer information. var layerDrawOpt = new LayerDrawingOptions() { // Match up the LayerID to the ID of the layer within the service. LayerID = counter, }; // We need to determine the geometry type of the new feature class. // To do this, we will submit a request to the ..\MapServer\dynamicLayer?.. endpoint which will return the service level metadata, // allowing us to identify the geometry type and create an appropriate renderer. // Note:- This is a workaround until the next release where GetAllDetails will honor the DynamicLayerInfoCollection. // Create a new WebClient instance to make the request and download the response. WebClient webClient = new WebClient(); // Register an asynchronous handler in which to create the renderers and apply the to the dynamic map service layer. webClient.DownloadDataCompleted += (client, downloadDataEventArgs) => { // Read the JSON response as XML XmlReader reader = System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonReader(downloadDataEventArgs.Result, new XmlDictionaryReaderQuotas()); // Get the root XML element XElement root = XElement.Load(reader); // Query for the "geometryType" element XElement geometryType = root.XPathSelectElement("//geometryType"); // Create the render based on the geometry type switch (geometryType.Value) { case "esriGeometryPoint": layerDrawOpt.Renderer = new SimpleRenderer() { Symbol = new SimpleMarkerSymbol() { Color = new SolidColorBrush(GetRandomColor()), Size = 8 } }; break; case "esriGeometryPolyline": layerDrawOpt.Renderer = new SimpleRenderer() { Symbol = new SimpleLineSymbol() { Color = new SolidColorBrush(GetRandomColor()) } }; break; case "esriGeometryPolygon": layerDrawOpt.Renderer = new SimpleRenderer() { Symbol = new SimpleFillSymbol() { Fill = new SolidColorBrush(GetRandomColor()), BorderBrush = new SolidColorBrush(GetRandomColor()) } }; break; } // Set the LayerDrawingOptions property on the local dynamic map service layer (the LayerID property ties this to the DynamicLayerInfo object). layerDrawingOptionsCollection.Add(layerDrawOpt); // Update the layer drawing options property on the dynamic map service layer. arcGisLocalDynamicMapServiceLayer.LayerDrawingOptions = layerDrawingOptionsCollection; // Need to refresh the layer after the renderer(s) have been applied. arcGisLocalDynamicMapServiceLayer.Refresh(); }; // Make the request for the service metadata // e.g. http://127.0.0.1:<PORT>/arcgis/rest/services/<MPK_NAME>/MapServer/dynamicLayer?layer={"id":0,"source":{"type":"dataLayer","dataSource":{"type":"table","workspaceId":"MyWorkspace","dataSourceName":"MyFeatureClassName"}}} webClient.DownloadDataAsync(new Uri(arcGisLocalDynamicMapServiceLayer.Url + "/dynamicLayer?layer={'id':" + counter.ToString() + "," + "'source':{'type':'dataLayer','dataSource':{" + "'type':'table'," + "'workspaceId':'" + workspaceInfo.Id + "'," + "'dataSourceName':'" + fileName + "'" + "}}}")); } // Set the Source property of the DynamicLayerInfo object. dynamicLayerInfo.Source = new LayerDataSource { DataSource = dataSource }; // Add the new DynamicLayerInfo object to the collection. dynamicLayerInfoCollection.Add(dynamicLayerInfo); // Increment the counter which is being used to assign Layer IDs. counter++; } // Update the DynamicLayerInfos property on the dynamic map service layer. arcGisLocalDynamicMapServiceLayer.DynamicLayerInfos = dynamicLayerInfoCollection; // Call the Action delegate. callback(arcGisLocalDynamicMapServiceLayer); }; // Call the Initialize method on the layer to initialize the layer properties. arcGisLocalDynamicMapServiceLayer.Initialize(); }); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
public MainWindow() { // License setting and ArcGIS Runtime initialization is done in Application.xaml.cs. InitializeComponent(); /* * Asynchronously start all the services... */ LocalGeoprocessingService.GetServiceAsync(@"..\Maps-and-Data\TraceGeometricNetwork.gpk", GPServiceType.SubmitJob, localServiceCallback => { if (localServiceCallback.Error != null) { MessageBox.Show(localServiceCallback.Error.Message); return; } traceNetworkLocalGpService = localServiceCallback; geoprocessorTask = new Geoprocessor(traceNetworkLocalGpService.Tasks[0].Url); // Enable the UI when the Trace Geometric Network service is available TraceUpstreamButton.IsEnabled = true; }); LocalGeometryService.GetServiceAsync(callback => { localGeometryService = callback; geometryTask = new GeometryService(); geometryTask.Url = localGeometryService.UrlGeometryService; }); LocalMapService.GetServiceAsync(@"..\Maps-and-Data\WaterDistributionNetwork.mpk", callback => { if (callback.Error != null) { MessageBox.Show("WaterDistributionNetwork map failed to load"); return; } waterNetworkLocalMapService = callback; ArcGISLocalDynamicMapServiceLayer WaterDistributionNetworkLayer = new ArcGISLocalDynamicMapServiceLayer(waterNetworkLocalMapService); MyMap.Layers.Insert(1, WaterDistributionNetworkLayer); }); /* * Create the Results GraphicsLayers and associated Renderers */ valvesGraphicsLayer = new GraphicsLayer() { Renderer = new SimpleRenderer() { Symbol = MainGrid.Resources["ValveMarkerSymbol"] as Symbol } }; mainsGraphicsLayer = new GraphicsLayer() { Renderer = new SimpleRenderer() { Symbol = new SimpleLineSymbol() { Color = new SolidColorBrush(Colors.Red), Width = 8, Style = SimpleLineSymbol.LineStyle.Dash } } }; // Add the GraphicsLayers to the Map MyMap.Layers.Add(mainsGraphicsLayer); MyMap.Layers.Add(valvesGraphicsLayer); }
private async void Initialize() { // Set paths that are relative to execution path string currentDir = Directory.GetCurrentDirectory(); int idx = currentDir.IndexOf("bin") - 1; appRootDir = currentDir.Substring(0, idx); appDataDir = appRootDir + @"\Data"; appTempDir = appRootDir + @"\temp"; // Set up files testImage = appDataDir + @"\sampleFile.tiff"; gpPackage = appDataDir + @"\CreateMapTilePackage.gpkx"; mapPackage = appDataDir + @"\emptyMapPackage.mpkx"; Debug.WriteLine(">> App Root Directory = " + appRootDir); Debug.WriteLine(">> App Data Directory = " + appDataDir); Debug.WriteLine(">> App Temp Directory = " + appTempDir); ////////////// start Q Basket set up ////////////////// // Create raster layer from a raster file (Geotiff) Debug.WriteLine("Loading raster layer from " + testImage); RasterLayer inRasterLayer = new RasterLayer(testImage); // Load Raster into Raster Layer try { await inRasterLayer.LoadAsync(); if (inRasterLayer.LoadStatus != Esri.ArcGISRuntime.LoadStatus.Loaded) { Debug.WriteLine("Error - Input Raster Layer not loaded "); } } catch (Exception ex) { string msg = "Unable to load the raster\n"; msg += "Raster file = " + testImage; msg += "Load status = " + inRasterLayer.LoadStatus.ToString(); msg += "\n\nMessage: " + ex.Message; MessageBox.Show(msg, "inRasterLayer.LoadAsync failed"); } // Create a new EnvelopeBuilder from the full extent of the raster layer. // Add a small zoom to make sure entire map is viewable EnvelopeBuilder envelopeBuilder = new EnvelopeBuilder(inRasterLayer.FullExtent); envelopeBuilder.Expand(0.75); // Create a basemap from the raster layer Basemap baseMap = new Basemap(inRasterLayer); // Create a new map using the new basemap Map newMap = new Map(baseMap); // Set the viewpoint of the map to the proper extent. newMap.InitialViewpoint = new Viewpoint(envelopeBuilder.ToGeometry().Extent); // Create a map and add it to the view MyMapView.Map = newMap; // Load new map to display basemap try { // Add map to the map view. MyMapView.Map = newMap; // Wait for the map to load. await newMap.LoadAsync(); } catch (Exception ex) { string msg = "Unable to load the Map\n"; msg += "\n\nMessage: " + ex.Message; MessageBox.Show(msg, "newMap.LoadAsync failed"); } // Wait for rendering to finish before taking the screenshot for the thumbnail await WaitForRenderCompleteAsync(MyMapView); ////////////// end Q Basket set up ////////////////// // Start the Local Server try { // LocalServer must not be running when setting the data path. if (LocalServer.Instance.Status == LocalServerStatus.Started) { await LocalServer.Instance.StopAsync(); } // Set the local data path - must be done before starting. // Avoid Windows path length limitations (260). // CreateDirectory won't overwrite if it already exists. Directory.CreateDirectory(appTempDir); LocalServer.Instance.AppDataPath = appTempDir; // Start the local server instance await LocalServer.Instance.StartAsync(); MessageBox.Show("Local Server started"); Debug.WriteLine(">> Local Server started"); // Get the URL for the localServer // localhost port is variable localServerURL = LocalServer.Instance.Url.AbsoluteUri; Debug.WriteLine("\n>> Local server url - " + localServerURL); Debug.WriteLine(">> Local server App Data Path - " + LocalServer.Instance.AppDataPath); } catch (Exception ex) { string msg = "Please ensure the local server is installed \nand configured correctly"; msg += String.Format("\nMessage: {0}", ex.Message); MessageBox.Show(msg, "Local Server failed to start"); Debug.WriteLine(msg); App.Current.Shutdown(); } // LOCAL MAP SERVICE INIT // Create and start the local map service try { _localMapService = new LocalMapService(mapPackage); } catch (Exception ex) { string msg = "Cannot create the local map service"; msg += "Map Package = " + mapPackage; msg += String.Format("\nMessage: {0}", ex.Message); MessageBox.Show(msg, "Local Map Server failed to start"); Debug.WriteLine(msg); App.Current.Shutdown(); } // RASTER WORKSPACE CREATION // Create the Raster workspace; this workspace name was chosen arbitrarily // Does workspace need to be the same directory as rasters? // setting to temp directory rasterWorkspace = new RasterWorkspace("raster_wkspc", appTempDir); Debug.WriteLine(">> raster workspace folder = " + rasterWorkspace.FolderPath); Debug.WriteLine(">> raster workspace id = " + rasterWorkspace.Id); // Create the layer source that represents the Raster on disk RasterSublayerSource source = new RasterSublayerSource(rasterWorkspace.Id, testImage); // Create a sublayer instance from the table source _rasterSublayer = new ArcGISMapImageSublayer(0, source); // Add the dynamic workspace to the map service _localMapService.SetDynamicWorkspaces(new List <DynamicWorkspace>() { rasterWorkspace }); // Register map service status chagne event handle _localMapService.StatusChanged += _localMapService_StatusChanged; // Start the map service try { await _localMapService.StartAsync(); } catch (Exception ex) { string msg = "Cannot start the local map service"; msg += "Map Package = " + mapPackage; msg += String.Format("\nMessage: {0}", ex.Message); MessageBox.Show(msg, "Local Map Server failed to start"); Debug.WriteLine(msg); App.Current.Shutdown(); } // Get the url to the local map service localMapServiceURL = _localMapService.Url.AbsoluteUri; MessageBox.Show("Local Map Service URL = " + localMapServiceURL); Debug.WriteLine("Local Map Service URL = " + localMapServiceURL); // LOCAL GEOPROCESSING SERVICE INIT // Create the geoprocessing service _localGPservice = new LocalGeoprocessingService(gpPackage, gpServiceType); // Ass GP service status chagned event handler _localGPservice.StatusChanged += GpServiceOnStatusChanged; // Try to start the service try { // Start the service await _localGPservice.StartAsync(); if (_localGPservice.Status == LocalServerStatus.Failed) { string msg = ("Geoprocessing service failed to start.\n"); MessageBox.Show(msg, "gpService.StartAsync failed"); App.Current.Shutdown(); } else if (_localGPservice.Status == LocalServerStatus.Started) { localGPserviceUrl = _localGPservice.Url.AbsoluteUri + "/CreateMapTilePackage"; string msg = ("Geoprocessing service started.\n"); msg += "\n>> GP Service URL: " + localGPserviceUrl; msg += ">> GP Service Max Records: " + _localGPservice.MaxRecords; msg += ">> GP Service Package Path: " + _localGPservice.PackagePath; msg += ">> GP Service Type: " + _localGPservice.ServiceType; MessageBox.Show(msg, "gpService.StartAsync started"); Debug.WriteLine("\n>> GP Service URL: " + localGPserviceUrl); Debug.WriteLine(">> GP Service Max Records: " + _localGPservice.MaxRecords); Debug.WriteLine(">> GP Service Package Path: " + _localGPservice.PackagePath); Debug.WriteLine(">> GP Service Type: " + _localGPservice.ServiceType); } } catch (Exception ex) { string msg = ("Geoprocessing service failed to start.\n"); msg += "\nGeoprocessing package - " + gpPackage + "\n"; msg += String.Format("\nMessage: {0}", ex.Message); MessageBox.Show(msg, "gpService.StartAsync failed"); return; } // GEOPROCESSING TASK INIT // Create the geoprocessing task from the service try { string url = _localGPservice.Url + "/CreateMapTilePackage"; _gpTask = await GeoprocessingTask.CreateAsync(new Uri(url)); } catch (Exception ex) { string msg = ("Geoprocessing task failed to start.\n"); msg += "\nlocalGPserviceUrl- " + localGPserviceUrl + "\n"; msg += String.Format("\nMessage: {0}", ex.Message); MessageBox.Show(msg, "GeoprocessingTask.CreateAsync failed"); return; } MessageBox.Show("GeoprocessingTask.CreateAsync created"); // GEOPROCESSING JOB // Create the geoprocessing parameters GeoprocessingParameters gpParams = new GeoprocessingParameters(gpExecutionType); // Add the interval parameter to the geoprocessing parameters //GeoprocessingString Input_Map = new GeoprocessingString("MyMapView.Map"); GeoprocessingString Input_Map = new GeoprocessingString("localMapServiceURL"); GeoprocessingDouble Max_LOD = new GeoprocessingDouble(10); GeoprocessingString Output_Package = new GeoprocessingString("C://Karen/Data/TilePackages/test.tpkx"); gpParams.Inputs.Add("Input_Map", Input_Map); gpParams.Inputs.Add("Max_LOD", Max_LOD); gpParams.Inputs.Add("Output_Package", Output_Package); // Create the job try { _gpJob = _gpTask.CreateJob(gpParams); } catch (Exception ex) { string msg = ("Geoprocessing job cannot be created.\n"); msg += String.Format("\nMessage: {0}", ex.Message); MessageBox.Show(msg, "_gpTask.CreateJob failed"); return; } MessageBox.Show("GeoprocessingTask.CreateJob created"); MyLoadingIndicator.Visibility = Visibility.Visible; // Update the UI when job progress changes _gpJob.ProgressChanged += (sender, args) => { Dispatcher.Invoke(() => { MyLoadingIndicator.Value = _gpJob.Progress; }); }; // Be notified when the task completes (or other change happens) _gpJob.JobChanged += GpJobOnJobChanged; // Start the job try { _gpJob.Start(); } catch (Exception ex) { string msg = ("Geoprocessing start job failed to start.\n"); msg += String.Format("\nMessage: {0}", ex.Message); MessageBox.Show(msg, "_gpjob.Start failed"); return; } MessageBox.Show("GeoprocessingTask job started"); }
public async void CreateLocalServiceAndDynamicLayer() { LocalMapService localMapService = new LocalMapService(this.MapPackage); await localMapService.StartAsync(); ArcGISDynamicMapServiceLayer arcGISDynamicMapServiceLayer = new ArcGISDynamicMapServiceLayer() { ID = "Restaurants", ServiceUri = localMapService.UrlMapService, }; this.mapView.Map.Layers.Add(arcGISDynamicMapServiceLayer); }
/// <summary> /// Adds a file dataset (Shapefile or raster) to a new local dynamic map service layer. /// </summary> /// <param name="workspaceType">The workspace type (FileGDB, Raster, SDE, Shapefile) <see cref="http://resources.arcgis.com/en/help/runtime-wpf/apiref/index.html?ESRI.ArcGIS.Client.Local~ESRI.ArcGIS.Client.Local.WorkspaceFactoryType.html"/>.</param> /// <param name="directoryPath">A <see cref="System.String"/> representing the directory path.</param> /// <param name="fileNames">A <see cref="System.Collections.Generic.List{System.String}"/> representing the name of the file (for raster datasets this must include the extension).</param> /// <param name="callback">The Action delegate to call back on once the dynamic layer work is complete.</param> public void AddFileDatasetToDynamicMapServiceLayer(WorkspaceFactoryType workspaceType, string directoryPath, List<string> fileNames, Action<ArcGISLocalDynamicMapServiceLayer> callback) { try { // Generate a unique workspace ID (any unique string). string uniqueId = Guid.NewGuid().ToString(); // Create a new WorkspaceInfo object with a unique ID. WorkspaceInfo workspaceInfo = new WorkspaceInfo(uniqueId, workspaceType, "DATABASE=" + directoryPath); // Create a new LocalMapService instance. LocalMapService localMapService = new LocalMapService { // Set the path property. Path = _emptyMpkPath, // Enable the dynamic layers capability. EnableDynamicLayers = true }; // Register the workspace to be used with this service. localMapService.DynamicWorkspaces.Add(workspaceInfo); // Asynchronously start the local map service. localMapService.StartAsync(x => { // Create the local dynamic map service layer. ArcGISLocalDynamicMapServiceLayer arcGisLocalDynamicMapServiceLayer = null; // Create a new ArcGISLocalDynamicMapServiceLayer passing in the newly started local service. arcGisLocalDynamicMapServiceLayer = new ArcGISLocalDynamicMapServiceLayer(localMapService) { // Assign the filename as the map layer ID. ID = "Workspace: " + (new DirectoryInfo(directoryPath)).Name, // Enable the dynamic layers capability. EnableDynamicLayers = true, }; // Handle the layer initialized event inline to perform the layer dynamic layer management. arcGisLocalDynamicMapServiceLayer.Initialized += (s, e) => { // Create a DynamicLayerInfoCollection to hold the new datasets as "dynamic layers". DynamicLayerInfoCollection dynamicLayerInfoCollection = new DynamicLayerInfoCollection(); // Create a LayerDrawingOptionsCollection to specify the symbology for each layer. LayerDrawingOptionsCollection layerDrawingOptionsCollection = new LayerDrawingOptionsCollection(); // Iterate over each of the selected files in the workspace. int counter = 0; foreach (string fileName in fileNames) { // Create a new DynamicLayerInfo (to make changes to existing map service layers use the CreateDynamicLayerInfosFromLayerInfos() method. DynamicLayerInfo dynamicLayerInfo = new DynamicLayerInfo { // Assign a layer ID. ID = counter, // Specify a friendly name. Name = "Dataset: " + fileName }; // Create a DataSource object to represent the physical datasource implementation (table or raster) which will become the DataSource // property of a new LayerDataSource in the map service. Other supported datasource types are JoinDataSource and QueryDataSource. DataSource dataSource = null; // If the workspace type is Raster create a new RasterDataSource. if (workspaceInfo.FactoryType == WorkspaceFactoryType.Raster) { // Create a new RasterDataSource object dataSource = new RasterDataSource { // Match the DataSourceName to the physical filename on disk (including extension). DataSourceName = fileName, // Provide the WorkspaceID (the unique workspace identifier created earlier). A LocalMapService may have multiple dynamic workspaces. WorkspaceID = workspaceInfo.Id }; } else { // Else if the workspace is not Raster create a new TableDataSource dataSource = new TableDataSource { // Match the DataSourceName to the physical filename on disk (excluding extension). DataSourceName = fileName, // Provide the WorkspaceID (the unique workspace identifier created earlier). A LocalMapService may have multiple dynamic workspaces. WorkspaceID = workspaceInfo.Id }; /* * Apply a renderer for vector layers. * Note: It is always necessary to provide a renderer when the layer being added (represented by a DynamicLayerInfo) is part of a new * DynamicLayerInfoCollection as opposed to using the CreateDynamicLayerInfosFromLayerInfos() method which creates a DynamicLayerInfoCollection * containing the existing layers in the map service. */ // Create a new LayerDrawingOptions object to hold the renderer information. var layerDrawOpt = new LayerDrawingOptions() { // Match up the LayerID to the ID of the layer within the service. LayerID = counter, }; // We need to determine the geometry type of the new feature class. // To do this, we will submit a request to the ..\MapServer\dynamicLayer?.. endpoint which will return the service level metadata, // allowing us to identify the geometry type and create an appropriate renderer. // Note:- This is a workaround until the next release where GetAllDetails will honor the DynamicLayerInfoCollection. // Create a new WebClient instance to make the request and download the response. WebClient webClient = new WebClient(); // Register an asynchronous handler in which to create the renderers and apply the to the dynamic map service layer. webClient.DownloadDataCompleted += (client, downloadDataEventArgs) => { // Read the JSON response as XML XmlReader reader = System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonReader(downloadDataEventArgs.Result, new XmlDictionaryReaderQuotas()); // Get the root XML element XElement root = XElement.Load(reader); // Query for the "geometryType" element XElement geometryType = root.XPathSelectElement("//geometryType"); // Create the render based on the geometry type switch (geometryType.Value) { case "esriGeometryPoint": layerDrawOpt.Renderer = new SimpleRenderer() { Symbol = new SimpleMarkerSymbol() { Color = new SolidColorBrush(GetRandomColor()), Size = 8 } }; break; case "esriGeometryPolyline": layerDrawOpt.Renderer = new SimpleRenderer() { Symbol = new SimpleLineSymbol() { Color = new SolidColorBrush(GetRandomColor()) } }; break; case "esriGeometryPolygon": layerDrawOpt.Renderer = new SimpleRenderer() { Symbol = new SimpleFillSymbol() { Fill = new SolidColorBrush(GetRandomColor()), BorderBrush = new SolidColorBrush(GetRandomColor()) } }; break; } // Set the LayerDrawingOptions property on the local dynamic map service layer (the LayerID property ties this to the DynamicLayerInfo object). layerDrawingOptionsCollection.Add(layerDrawOpt); // Update the layer drawing options property on the dynamic map service layer. arcGisLocalDynamicMapServiceLayer.LayerDrawingOptions = layerDrawingOptionsCollection; // Need to refresh the layer after the renderer(s) have been applied. arcGisLocalDynamicMapServiceLayer.Refresh(); }; // Make the request for the service metadata // e.g. http://127.0.0.1:<PORT>/arcgis/rest/services/<MPK_NAME>/MapServer/dynamicLayer?layer={"id":0,"source":{"type":"dataLayer","dataSource":{"type":"table","workspaceId":"MyWorkspace","dataSourceName":"MyFeatureClassName"}}} webClient.DownloadDataAsync(new Uri(arcGisLocalDynamicMapServiceLayer.Url + "/dynamicLayer?layer={'id':" + counter.ToString() + "," + "'source':{'type':'dataLayer','dataSource':{" + "'type':'table'," + "'workspaceId':'" + workspaceInfo.Id + "'," + "'dataSourceName':'" + fileName + "'" + "}}}")); } // Set the Source property of the DynamicLayerInfo object. dynamicLayerInfo.Source = new LayerDataSource { DataSource = dataSource }; // Add the new DynamicLayerInfo object to the collection. dynamicLayerInfoCollection.Add(dynamicLayerInfo); // Increment the counter which is being used to assign Layer IDs. counter++; } // Update the DynamicLayerInfos property on the dynamic map service layer. arcGisLocalDynamicMapServiceLayer.DynamicLayerInfos = dynamicLayerInfoCollection; // Call the Action delegate. callback(arcGisLocalDynamicMapServiceLayer); }; // Call the Initialize method on the layer to initialize the layer properties. arcGisLocalDynamicMapServiceLayer.Initialize(); }); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
/// <summary> /// Adds a file dataset (Shapefile or raster) to a new local dynamic map service layer. /// </summary> /// <param name="workspaceType">The workspace type (FileGDB, Raster, SDE, Shapefile) <see cref="http://resources.arcgis.com/en/help/runtime-wpf/apiref/index.html?ESRI.ArcGIS.Client.Local~ESRI.ArcGIS.Client.Local.WorkspaceFactoryType.html"/>.</param> /// <param name="directoryPath">A <see cref="System.String"/> representing the directory path.</param> /// <param name="fileNames">A <see cref="System.Collections.Generic.List{System.String}"/> representing the name of the file (for raster datasets this must include the extension).</param> /// <param name="callback">The Action delegate to call back on once the dynamic layer work is complete.</param> public void AddFileDatasetToDynamicMapServiceLayer(WorkspaceFactoryType workspaceType, string directoryPath, List <string> fileNames, Action <ArcGISLocalDynamicMapServiceLayer> callback) { try { // Generate a unique workspace ID (any unique string). string uniqueId = Guid.NewGuid().ToString(); // Create a new WorkspaceInfo object with a unique ID. WorkspaceInfo workspaceInfo = new WorkspaceInfo(uniqueId, workspaceType, "DATABASE=" + directoryPath); // Create a new LocalMapService instance. LocalMapService localMapService = new LocalMapService { // Set the path property. Path = _emptyMpkPath, // Enable the dynamic layers capability. EnableDynamicLayers = true }; // Register the workspace to be used with this service. localMapService.DynamicWorkspaces.Add(workspaceInfo); // Asynchronously start the local map service. localMapService.StartAsync(x => { // Create the local dynamic map service layer. ArcGISLocalDynamicMapServiceLayer arcGisLocalDynamicMapServiceLayer = null; // Create a new ArcGISLocalDynamicMapServiceLayer passing in the newly started local service. arcGisLocalDynamicMapServiceLayer = new ArcGISLocalDynamicMapServiceLayer(localMapService) { // Assign the filename as the map layer ID. ID = "Workspace: " + (new DirectoryInfo(directoryPath)).Name, // Enable the dynamic layers capability. EnableDynamicLayers = true, }; // Handle the layer initialized event inline to perform the layer dynamic layer management. arcGisLocalDynamicMapServiceLayer.Initialized += (s, e) => { // Create a DynamicLayerInfoCollection to hold the new datasets as "dynamic layers". DynamicLayerInfoCollection dynamicLayerInfoCollection = new DynamicLayerInfoCollection(); // Create a LayerDrawingOptionsCollection to specify the symbology for each layer. LayerDrawingOptionsCollection layerDrawingOptionsCollection = new LayerDrawingOptionsCollection(); // Iterate over each of the selected files in the workspace. int counter = 0; foreach (string fileName in fileNames) { // Create a new DynamicLayerInfo (to make changes to existing map service layers use the CreateDynamicLayerInfosFromLayerInfos() method. DynamicLayerInfo dynamicLayerInfo = new DynamicLayerInfo { // Assign a layer ID. ID = counter, // Specify a friendly name. Name = "Dataset: " + fileName }; // Create a DataSource object to represent the physical datasource implementation (table or raster) which will become the DataSource // property of a new LayerDataSource in the map service. Other supported datasource types are JoinDataSource and QueryDataSource. DataSource dataSource = null; // If the workspace type is Raster create a new RasterDataSource. if (workspaceInfo.FactoryType == WorkspaceFactoryType.Raster) { // Create a new RasterDataSource object dataSource = new RasterDataSource { // Match the DataSourceName to the physical filename on disk (including extension). DataSourceName = fileName, // Provide the WorkspaceID (the unique workspace identifier created earlier). A LocalMapService may have multiple dynamic workspaces. WorkspaceID = workspaceInfo.Id }; } else { // Else if the workspace is not Raster create a new TableDataSource dataSource = new TableDataSource { // Match the DataSourceName to the physical filename on disk (excluding extension). DataSourceName = fileName, // Provide the WorkspaceID (the unique workspace identifier created earlier). A LocalMapService may have multiple dynamic workspaces. WorkspaceID = workspaceInfo.Id }; /* * Apply a renderer for vector layers. * Note: It is always necessary to provide a renderer when the layer being added (represented by a DynamicLayerInfo) is part of a new * DynamicLayerInfoCollection as opposed to using the CreateDynamicLayerInfosFromLayerInfos() method which creates a DynamicLayerInfoCollection * containing the existing layers in the map service. However, the renderer provided does not need to be valid with regard to the actual * layer and geometry type, it simply needs to be a valid renderer. If the renderer specified here is not appropriate for the geometry type of * the layer the symbology will fall back to a default SimpleMarkerSymbol, SimpleLineSymbol or SimpleFillSymbol. */ // Create a new LayerDrawingOptions object to hold the renderer information. var layerDrawOpt = new LayerDrawingOptions() { // Match up the LayerID to the ID of the layer within the service. LayerID = counter, // Provide a renderer. In this example it is an empty SimpleMarkerSymbol. Renderer = new SimpleRenderer() { Symbol = new SimpleMarkerSymbol() { } }, }; // Set the LayerDrawingOptions property on the local dynamic map service layer (the LayerID property ties this to the DynamicLayerInfo object). layerDrawingOptionsCollection.Add(layerDrawOpt); } // Set the Source property of the DynamicLayerInfo object. dynamicLayerInfo.Source = new LayerDataSource { DataSource = dataSource }; // Add the new DynamicLayerInfo object to the collection. dynamicLayerInfoCollection.Add(dynamicLayerInfo); // Increment the counter which is being used to assign Layer IDs. counter++; } // Update the DynamicLayerInfos property on the dynamic map service layer. arcGisLocalDynamicMapServiceLayer.DynamicLayerInfos = dynamicLayerInfoCollection; // Update the layer drawing options property on the dynamic map service layer. arcGisLocalDynamicMapServiceLayer.LayerDrawingOptions = layerDrawingOptionsCollection; // Refresh the layer. arcGisLocalDynamicMapServiceLayer.Refresh(); // Call the Action delegate. callback(arcGisLocalDynamicMapServiceLayer); }; // Call the Initialize method on the layer to initialize the layer properties. arcGisLocalDynamicMapServiceLayer.Initialize(); }); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
private void btnopen_Click(object sender, RoutedEventArgs e) { // Disable the UI Grid until the ArcGISDynamicMapServiceLayer has initialized. // DynamicLayersUiGrid.IsEnabled = false; // Create a new local map service from an MPK and enable the // Dynamic Layers capability // Start the local map service and once initialized // Setup the OpenFiledialog. OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "mpk (*.mpk)|*.mpk"; openFileDialog.RestoreDirectory = true; openFileDialog.Multiselect = false; if (openFileDialog.ShowDialog() == true) { try { List <string> fileNames = new List <string>(); string filename = openFileDialog.FileName; LocalMapService localMapService = new LocalMapService() { Path = filename, EnableDynamicLayers = true }; localMapService.StartAsync((mapService) => { // create a new local dynamic map service layer based on the local map service _arcGISLocalDynamicMapServiceLayer = new ArcGISLocalDynamicMapServiceLayer(localMapService) { ID = "_arcGISLocalDynamicMapServiceLayer", ImageFormat = ArcGISDynamicMapServiceLayer.RestImageFormat.PNG32, }; // Set up an event handler for the layer initialized event _arcGISLocalDynamicMapServiceLayer.Initialized += (s, re) => { //Enable the UI once the layer has initialized // DynamicLayersUiGrid.IsEnabled = true; DataContext = this; // IsBusy = false; }; // Add the layer to the map MyMap.Layers.Add(_arcGISLocalDynamicMapServiceLayer); }); // ArcGISLocalDynamicMapServiceLayer layer = new ArcGISLocalDynamicMapServiceLayer() { Path = filename, ID = "_arcGISLocalDynamicMapServiceLayer" }; // _arcGISLocalDynamicMapServiceLayer = layer; layerids = new string[1] { "_arcGISLocalDynamicMapServiceLayer" }; legendtoolkit.LayerIDs = layerids; // MyMap.Layers.Add(layer); // openlayer.Path = filename; //foreach (var item in openFileDialog.FileName) //{ // fileNames.Add(Path.GetFileNameWithoutExtension(item)); //} //// Call the add dataset method with workspace type, parent directory path, file names (without extensions) and delegate. //AddFileDatasetToDynamicMapServiceLayer(WorkspaceFactoryType.Shapefile, // Path.GetDirectoryName(openFileDialog.FileName), // fileNames, // arcGisLocalDynamicMapServiceLayer => // { // // Add the dynamic map service layer to the map. // MyMap.Layers.Add(arcGisLocalDynamicMapServiceLayer); // }); } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); } } }