Esempio n. 1
0
 private void map1_ExtentChanged(object sender, ExtentEventArgs e)
 {
     try
     {
         ArcGISTiledMapServiceLayer layer = map1.Layers["PBSLayer"] as ArcGISTiledMapServiceLayer;
         //find current lod
         int i;
         for (i = 0; i < layer.TileInfo.Lods.Length; i++)
         {
             if (Math.Abs(map1.Resolution - layer.TileInfo.Lods[i].Resolution) < 0.000001)
             {
                 break;
             }
         }
         tbZoomLevel.Text  = FindResource("tbLevel").ToString() + ":" + _service.DataSource.TilingScheme.LODs[i].LevelID + " ";
         tbScale.Text      = FindResource("tbScale").ToString() + ":" + string.Format("{0:N0}", _service.DataSource.TilingScheme.LODs[i].Scale) + " ";
         tbResolution.Text = FindResource("tbResolution").ToString() + ":" + _service.DataSource.TilingScheme.LODs[i].Resolution;
         //if zoom level changed, then cleargraphics
         if (Math.Abs(_oldResolution - _service.DataSource.TilingScheme.LODs[i].Resolution) > 0.0000001)
         {
             _gLayer.ClearGraphics();
             _dictDrawedGrids.Clear();
         }
         _oldResolution = _service.DataSource.TilingScheme.LODs[i].Resolution;
     }
     catch (Exception)
     {
     }
 }
		// Create the online basemap layer (with token credentials) and add it to the map
		private async Task InitializeOnlineBasemap()
		{
			try
			{
				_onlineTiledLayer = new ArcGISTiledMapServiceLayer(new Uri(ONLINE_BASEMAP_URL));
				_onlineTiledLayer.ID = _onlineTiledLayer.DisplayName = ONLINE_LAYER_ID;

				// Generate token credentials if using tiledbasemaps.arcgis.com
				if (!string.IsNullOrEmpty(ONLINE_BASEMAP_TOKEN_URL))
				{
					// Set credentials and token for online basemap
					var options = new GenerateTokenOptions()
					{
						Referer = new Uri(_onlineTiledLayer.ServiceUri)
					};

					var cred = await IdentityManager.Current.GenerateCredentialAsync(ONLINE_BASEMAP_TOKEN_URL, USERNAME, PASSWORD);

					if (cred != null && !string.IsNullOrEmpty(cred.Token))
					{
						_onlineTiledLayer.Token = cred.Token;
						IdentityManager.Current.AddCredential(cred);
					}
				}

				await _onlineTiledLayer.InitializeAsync();
				MyMapView.Map.Layers.Add(_onlineTiledLayer);
			}
			catch (Exception ex)
			{
				var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync();
			}
		}
Esempio n. 3
0
        public UIElement CreateMap()
        {
            _map = new Map {
                UseAcceleratedDisplay = false,
                Extent     = new Envelope(-2014711, 15, 156956, 12175318),
                WrapAround = true
            };

            var baseMap = new ArcGISTiledMapServiceLayer
            {
                ID  = "BaseMap",
                Url =
                    "http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer"
            };

            baseMap.Initialized += BaseMapInitialized;
            _map.Layers.Add(baseMap);

            _flagsGraphicsLayer = new GraphicsLayer {
                ID = "FlagsGraphicsLayer"
            };
            _map.Layers.Add(_flagsGraphicsLayer);

            return(_map);
        }
Esempio n. 4
0
        private static Layer Convert(Esri.ArcGISRuntime.Mapping.ILayerContent item)
        {
            Layer layer = null;


            if (item is Esri.ArcGISRuntime.Mapping.ArcGISTiledLayer tile)
            {
                layer = new ArcGISTiledMapServiceLayer
                {
                    Url = tile.Source.ToString()
                };
            }

            if (item is Esri.ArcGISRuntime.Mapping.ArcGISMapImageLayer dynamic)
            {
                layer = new ArcGISDynamicMapServiceLayer
                {
                    Url = dynamic.Source.ToString(),
                };
            }

            if (layer != null)
            {
                layer.Visible = item.IsVisible;
                layer.ID      = item.Name;
                layer.InitializationFailed += InitializationFailed;
                layer.Initialized          += Layer_Initialized;
            }

            return(layer);
        }
        private void OnMapLoadComplete(object sender, RoutedEventArgs e)
        {
            LivingMapLayer[] livingMaps = this.AppConfig.MapConfig.LivingMaps;

            if (livingMaps != null && livingMaps.Length > 0)
            {
                for (int i = 0; i < livingMaps.Length; i++)
                {
                    // Create Map Layer Nodes
                    TreeViewItem tvItem = CreateMapLayerNode(livingMaps[i]);
                    MapContentTree.Items.Add(tvItem);

                    if (this.MapControl.Layers[livingMaps[i].ID] is ArcGISTiledMapServiceLayer)
                    {
                        ArcGISTiledMapServiceLayer cachedLayer = this.MapControl.Layers[livingMaps[i].ID] as ArcGISTiledMapServiceLayer;
                        cachedLayer.QueryLegendInfos((legendInfo => OnLegendInfoSucceed(legendInfo, tvItem)), (exception => OnLegendInfoFailed(exception, livingMaps[i].Title)));
                    }
                    else if (this.MapControl.Layers[livingMaps[i].ID] is ArcGISDynamicMapServiceLayer)
                    {
                        ArcGISDynamicMapServiceLayer dynamicLayer = this.MapControl.Layers[livingMaps[i].ID] as ArcGISDynamicMapServiceLayer;
                        dynamicLayer.QueryLegendInfos((legendInfo => OnLegendInfoSucceed(legendInfo, tvItem)), (exception => OnLegendInfoFailed(exception, livingMaps[i].Title)));
                    }
                    else if (this.MapControl.Layers[livingMaps[i].ID] is FeatureLayer)
                    {
                        FeatureLayer featureLayer = this.MapControl.Layers[livingMaps[i].ID] as FeatureLayer;
                        featureLayer.QueryLegendInfos((legendInfo => OnLegendInfoSucceed(legendInfo, tvItem)), (exception => OnLegendInfoFailed(exception, livingMaps[i].Title)));
                    }
                }
            }
        }
Esempio n. 6
0
        private void RadioButton_Click(object sender, RoutedEventArgs e)
        {
            ArcGISTiledMapServiceLayer arcgisLayer = Map.Layers["CensusLayer"] as ArcGISTiledMapServiceLayer;

            arcgisLayer.Url = ((RadioButton)sender).Tag as string;
            //arcgisLayer.Opacity = 0.5;
        }
        // Create the online basemap layer (with token credentials) and add it to the map
        private async Task InitializeOnlineBasemap()
        {
            try
            {
                _onlineTiledLayer    = new ArcGISTiledMapServiceLayer(new Uri(ONLINE_BASEMAP_URL));
                _onlineTiledLayer.ID = _onlineTiledLayer.DisplayName = ONLINE_LAYER_ID;

                // Generate token credentials if using tiledbasemaps.arcgis.com
                if (!string.IsNullOrEmpty(ONLINE_BASEMAP_TOKEN_URL))
                {
                    // Set credentials and token for online basemap
                    var options = new GenerateTokenOptions()
                    {
                        Referer = new Uri(_onlineTiledLayer.ServiceUri)
                    };

                    var cred = await IdentityManager.Current.GenerateCredentialAsync(ONLINE_BASEMAP_TOKEN_URL, USERNAME, PASSWORD);

                    if (cred != null && !string.IsNullOrEmpty(cred.Token))
                    {
                        _onlineTiledLayer.Token = cred.Token;
                        IdentityManager.Current.AddCredential(cred);
                    }
                }

                await _onlineTiledLayer.InitializeAsync();

                MyMapView.Map.Layers.Add(_onlineTiledLayer);
            }
            catch (Exception ex)
            {
                var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync();
            }
        }
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        public AgsCachedLayer(AgsServer server, MapLayer layer)
            : base(layer)
        {
            Debug.Assert(layer.MapServiceInfo != null);

            LayerType = AgsLayerType.Cached;
            Server = server;

            if (String.IsNullOrEmpty(layer.MapServiceInfo.Url))
                throw new SettingsException((string)App.Current.FindResource("InvalidMapLayerURL"));

            // format REST URL
            string restUrl = FormatRestUrl(layer.MapServiceInfo.Url);
            if (restUrl == null)
                throw new SettingsException((string)App.Current.FindResource("FailedFormatRESTURL"));

            // create ArcGIS layer
            ArcGISTiledMapServiceLayer arcGISTiledMapServiceLayer = new ArcGISTiledMapServiceLayer();
            arcGISTiledMapServiceLayer.ID = "map";
            arcGISTiledMapServiceLayer.Url = restUrl;
            arcGISTiledMapServiceLayer.Visible = layer.MapServiceInfo.IsVisible;
            arcGISTiledMapServiceLayer.Opacity = layer.MapServiceInfo.Opacity;
            ArcGISLayer = arcGISTiledMapServiceLayer;

            UpdateTokenIfNeeded();
        }
        void Layers_LayersInitialized(object sender, System.EventArgs args)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(string.Format("Spatial Reference: {0}", MyMap.SpatialReference.WKT != null ? MyMap.SpatialReference.WKT : MyMap.SpatialReference.WKID.ToString()));
            sb.AppendLine(string.Format("Minimum Resolution: {0}", MyMap.MinimumResolution));
            sb.AppendLine(string.Format("Maximum Resolution: {0}", MyMap.MaximumResolution));
            sb.AppendLine(string.Format("Width (pixels): {0}", MyMap.ActualWidth));
            sb.AppendLine(string.Format("Height (pixels): {0}", MyMap.ActualHeight));
            sb.AppendLine();
            sb.AppendLine(string.Format("---Map Layers ({0})---", MyMap.Layers.Count));
            sb.AppendLine();

            foreach (Layer layer in MyMap.Layers)
            {
                sb.AppendLine(string.Format("ID: {0}", layer.ID));
                sb.AppendLine(string.Format("Type: {0}", layer.GetType().ToString()));
                sb.AppendLine(string.Format("Visibility : {0}", layer.Visible));
                sb.AppendLine(string.Format("Opacity : {0}", layer.Opacity));
                if (layer is ArcGISDynamicMapServiceLayer)
                {
                    ArcGISDynamicMapServiceLayer dynLayer = layer as ArcGISDynamicMapServiceLayer;
                    sb.AppendLine(string.Format("\t---Layers ({0})---", dynLayer.Layers.Length));
                    foreach (LayerInfo layerinfo in dynLayer.Layers)
                    {
                        sb.AppendLine(string.Format("\tID: {0}", layerinfo.ID));
                        sb.AppendLine(string.Format("\tName: {0}", layerinfo.Name));
                        sb.AppendLine(string.Format("\tDefault Visibility: {0}", layerinfo.DefaultVisibility));

                        sb.AppendLine(string.Format("\tMinimum Scale: {0}", layerinfo.MinScale));
                        sb.AppendLine(string.Format("\tMaximum Scale: {0}", layerinfo.MaxScale));
                        if (layerinfo.SubLayerIds != null)
                        {
                            sb.AppendLine(string.Format("\tSubLayer IDs: {0}", layerinfo.SubLayerIds.ToString()));
                        }
                        sb.AppendLine();
                    }
                }
                if (layer is ArcGISTiledMapServiceLayer)
                {
                    ArcGISTiledMapServiceLayer tiledLayer = layer as ArcGISTiledMapServiceLayer;
                    TileInfo ti = tiledLayer.TileInfo;
                    sb.AppendLine("Levels and Resolution :");
                    for (int i = 0; i < ti.Lods.Length; i++)
                    {
                        if (i < 10)
                        {
                            sb.Append(string.Format("Level: {0} \t \tResolution: {1}\r", i, ti.Lods[i].Resolution));
                        }
                        else
                        {
                            sb.Append(string.Format("Level: {0} \tResolution: {1}\r", i, ti.Lods[i].Resolution));
                        }
                    }
                }
                sb.AppendLine();
            }

            PropertiesTextBlock.Text = sb.ToString();
        }
Esempio n. 10
0
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////

        public AgsCachedLayer(AgsServer server, MapLayer layer)
            : base(layer)
        {
            Debug.Assert(layer.MapServiceInfo != null);

            LayerType = AgsLayerType.Cached;
            Server    = server;

            if (String.IsNullOrEmpty(layer.MapServiceInfo.Url))
            {
                throw new SettingsException((string)App.Current.FindResource("InvalidMapLayerURL"));
            }

            // format REST URL
            string restUrl = FormatRestUrl(layer.MapServiceInfo.Url);

            if (restUrl == null)
            {
                throw new SettingsException((string)App.Current.FindResource("FailedFormatRESTURL"));
            }

            // create ArcGIS layer
            ArcGISTiledMapServiceLayer arcGISTiledMapServiceLayer = new ArcGISTiledMapServiceLayer();

            arcGISTiledMapServiceLayer.ID      = "map";
            arcGISTiledMapServiceLayer.Url     = restUrl;
            arcGISTiledMapServiceLayer.Visible = layer.MapServiceInfo.IsVisible;
            arcGISTiledMapServiceLayer.Opacity = layer.MapServiceInfo.Opacity;
            ArcGISLayer = arcGISTiledMapServiceLayer;

            UpdateTokenIfNeeded();
        }
        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var combo = sender as ComboBox;
            var sel   = combo.SelectedItem as ComboBoxItem;

            if (sel.Tag == null)
            {
                return;
            }

            // Find and remove the current basemap layer from the map
            if (MyMap == null)
            {
                return;
            }
            var oldBasemap = MyMap.Layers["BaseMap"];

            MyMap.Layers.Remove(oldBasemap);

            // Create a new basemap layer
            var newBasemap = new ArcGISTiledMapServiceLayer();

            // Set the ServiceUri with the url defined for the ComboBoxItem's Tag
            newBasemap.Url = sel.Tag.ToString();

            // Give the layer the same ID so it can still be found with the code above
            newBasemap.ID = "BaseMap";

            // Insert the new basemap layer as the first (bottom) layer in the map
            MyMap.Layers.Insert(0, newBasemap);
        }
        protected override void WriteAttributes(Layer layer)
        {
            base.WriteAttributes(layer);
            ArcGISTiledMapServiceLayer tiledLayer = layer as ArcGISTiledMapServiceLayer;

            if (tiledLayer != null)
            {
                WriteAttribute("Url", tiledLayer.Url);
                if (!LayerExtensions.GetUsesProxy(layer))
                {
                    if (!string.IsNullOrEmpty(tiledLayer.ProxyURL))
                    {
                        WriteAttribute("ProxyURL", tiledLayer.ProxyURL);
                    }
                    if (!string.IsNullOrEmpty(tiledLayer.Token))
                    {
                        WriteAttribute("Token", tiledLayer.Token);
                    }
                }
                if (!double.IsInfinity(tiledLayer.MaximumResolution) && !double.IsNaN(tiledLayer.MaximumResolution))
                {
                    WriteAttribute("MaximumResolution", tiledLayer.MaximumResolution);
                }
                if (!double.IsInfinity(tiledLayer.MinimumResolution) && !double.IsNaN(tiledLayer.MinimumResolution))
                {
                    WriteAttribute("MinimumResolution", tiledLayer.MinimumResolution);
                }
            }
        }
Esempio n. 13
0
        // Initializes the Layer property
        private void initializeLayer()
        {
            Layer layer = null;

            // Create the layer based on the type of service encapsulated by the search result
            if (Service is MapService)
            {
                MapService mapService = (MapService)Service;
                if (mapService.IsTiled &&
                    mapService.SpatialReference.WKID == MapApplication.Current.Map.SpatialReference.WKID)
                {
                    layer = new ArcGISTiledMapServiceLayer()
                    {
                        Url = Service.Url, ProxyURL = ProxyUrl
                    }
                }
                ;
                else
                {
                    layer = new ArcGISDynamicMapServiceLayer()
                    {
                        Url = Service.Url, ProxyURL = ProxyUrl
                    }
                };
            }
            else if (Service is ImageService)
            {
                layer = new ArcGISImageServiceLayer()
                {
                    Url = Service.Url, ProxyURL = ProxyUrl
                };
            }
            else if (Service is FeatureLayerService || (Service is FeatureService && ((FeatureService)Service).Layers.Count() == 1))
            {
                string url = Service is FeatureService?string.Format("{0}/0", Service.Url) : Service.Url;

                layer = new FeatureLayer()
                {
                    Url       = url,
                    ProxyUrl  = ProxyUrl,
                    OutFields = new OutFields()
                    {
                        "*"
                    }
                };
            }

            // Initialize the layer's ID and display name
            if (layer != null)
            {
                string id   = Guid.NewGuid().ToString("N");
                string name = propertyExists("Title") ? Result.Title : id;

                layer.ID = id;
                MapApplication.SetLayerName(layer, name);
            }
            Layer = layer;
        }
Esempio n. 14
0
 public void AddLayerObjectTest()
 {
     ArcGISTiledMapServiceLayer newLayer = new ArcGISTiledMapServiceLayer();
     newLayer.ID = "NewLayer";
     MapLayersManager.Instance.AddLayer(newLayer);
     //Now we should have 7 layers
     Assert.AreEqual(7, MapLayersManager.Instance.MapLayers.Count);
     Assert.AreEqual("NewLayer", MapLayersManager.Instance.MapLayers[6].ID);
 }
        // When map service item selected in Listbox, choose appropriate type and add to the map
        void webclient_DownloadStringCompleted(object sender, ArcGISWebClient.DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null)
                {
                    throw new Exception(e.Error.Message);
                }

                // Get the service url from the user object
                string svcUrl = e.UserState as string;

                //only available in Silverlight or .Net 4.5
                // Abstract JsonValue holds json response
                // JsonValue serviceInfo = JsonObject.Parse(e.Result);

                string[] jsonPairs           = e.Result.Split(',');
                string   mapCachePair        = jsonPairs.Where(json => json.Contains("singleFusedMapCache")).FirstOrDefault();
                string[] mapCacheKeyAndValue = mapCachePair.Split(':');
                bool     isTiledMapService   = Boolean.Parse(mapCacheKeyAndValue[1]);

                // Use "singleFusedMapCache" to determine if a tiled or dynamic layer should be added to the map
                //bool isTiledMapService = Boolean.Parse(serviceInfo["singleFusedMapCache"].ToString());

                Layer lyr = null;

                if (isTiledMapService)
                {
                    lyr = new ArcGISTiledMapServiceLayer()
                    {
                        Url = svcUrl
                    }
                }
                ;
                else
                {
                    lyr = new ArcGISDynamicMapServiceLayer()
                    {
                        Url = svcUrl
                    }
                };

                if (lyr != null)
                {
                    lyr.InitializationFailed += (a, b) =>
                    {
                        throw new Exception(lyr.InitializationFailure.Message);
                    };
                    MyMap.Layers.Add(lyr);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        protected virtual void OnDownloadConfigXMLCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            OverviewConfig = (OverviewMapConfig)OverviewMapConfig.Deserialize(e.Result, typeof(OverviewMapConfig));

            if (OverviewConfig != null)
            {
                this.IsOpen   = OverviewConfig.OpenInitial;
                this.Position = (OverviewConfig.Position == OverviewMapPosition.Undefined) ? OverviewMapPosition.LowerRight : OverviewConfig.Position;

                myOverviewMap.Width         = (OverviewConfig.Width > 0) ? OverviewConfig.Width : 250;
                myOverviewMap.Height        = (OverviewConfig.Height > 0) ? OverviewConfig.Height : 200;
                myOverviewMap.MaximumExtent = OverviewConfig.MaximumExtent.ToEnvelope(this.CurrentPage.MapSRWKID);

                if (OverviewConfig.MapLayer != null)
                {
                    myOverviewMap.Layer = new ArcGISTiledMapServiceLayer()
                    {
                        ID = "Overview_Layer", Url = OverviewConfig.MapLayer.RESTURL, ProxyURL = OverviewConfig.MapLayer.ProxyURL
                    };
                }
                else if (this.MapControl.Layers[0] is ArcGISTiledMapServiceLayer)
                {
                    ArcGISTiledMapServiceLayer agisTiledLayer = this.MapControl.Layers[0] as ArcGISTiledMapServiceLayer;
                    myOverviewMap.Layer = new ArcGISTiledMapServiceLayer()
                    {
                        ID = "Overview_Layer", Url = agisTiledLayer.Url, ProxyURL = agisTiledLayer.ProxyURL
                    };
                }
                else if (this.MapControl.Layers[0] is ArcGISDynamicMapServiceLayer)
                {
                    ArcGISDynamicMapServiceLayer agisDynamicLayer = this.MapControl.Layers[0] as ArcGISDynamicMapServiceLayer;
                    myOverviewMap.Layer = new ArcGISDynamicMapServiceLayer()
                    {
                        ID = "Overview_Layer", Url = agisDynamicLayer.Url, ProxyURL = agisDynamicLayer.ProxyURL
                    };
                }
                else if (this.MapControl.Layers[0] is ESRI.ArcGIS.Client.Bing.TileLayer)
                {
                    TileLayer bingTiledLayer = this.MapControl.Layers[0] as TileLayer;
                    myOverviewMap.Layer = new TileLayer()
                    {
                        ID = "Overview_Layer", ServerType = bingTiledLayer.ServerType, LayerStyle = bingTiledLayer.LayerStyle, Token = bingTiledLayer.Token
                    };
                }

                // Initialize Map extent here to sychronize with OverviewMap extent on the first loading
                if (this.CurrentPage.InitMapExtent != null)
                {
                    this.MapControl.ZoomTo(this.CurrentPage.InitMapExtent);
                }
                else if (this.CurrentPage.FullMapExtent != null)
                {
                    this.MapControl.ZoomTo(this.CurrentPage.FullMapExtent);
                }
            }
        }
Esempio n. 17
0
        public MapControl()
        {
            InitializeComponent();
            ArcGISTiledMapServiceLayer imgLyr = new ArcGISTiledMapServiceLayer(new Uri("http://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer"));

            Map1.Layers.Add(imgLyr);
            ArcGISTiledMapServiceLayer terrainLyr = new ArcGISTiledMapServiceLayer(new Uri("http://server.arcgisonline.com/arcgis/rest/services/Ocean_Basemap/MapServer"));

            Scene1.Layers.Add(terrainLyr);
        }
Esempio n. 18
0
        /// <summary>
        /// Called a radio buttons in the base layer menu is selected.
        /// Each radiobutton has a string tag that contains the URL to the service url
        /// </summary>
        private void BaseLayer_Changed(object sender, RoutedEventArgs e)
        {
            if (Map == null)
            {
                return;
            }
            ArcGISTiledMapServiceLayer layer = Map.Layers[0] as ArcGISTiledMapServiceLayer;

            layer.Url = (sender as FrameworkElement).Tag as string;
        }
Esempio n. 19
0
        private Layer CreateStaticLayer()
        {
            Layer layer = null;

            if (!string.IsNullOrWhiteSpace(Path) && File.Exists(Path))
            {
                layer =
                    AssociatedObject.Layers.FirstOrDefault(
                        l => !String.IsNullOrWhiteSpace(l.ID) && l.ID.Equals(ID)) as ArcGISLocalTiledLayer;

                if (layer != null)
                {
                    return(null);               // no need to add it is already added
                }
                layer = new ArcGISLocalTiledLayer(Path);
                //layer = new ArcGISTiledMapServiceLayer() { Url = Path };

                OnAddLayer();

                layer.ID = ID;

                layer.Initialized          += OnLayerInitalized;
                layer.InitializationFailed += (o, e) =>
                {
                    OnDone();
                };
            }
            else if (!string.IsNullOrWhiteSpace(Path))
            {
                layer =
                    AssociatedObject.Layers.FirstOrDefault(
                        l => !String.IsNullOrWhiteSpace(l.ID) && l.ID.Equals(ID)) as ArcGISLocalTiledLayer;

                if (layer != null)
                {
                    return(null);               // no need to add it is already added
                }
                //layer = new ArcGISLocalTiledLayer(Path);
                layer = new ArcGISTiledMapServiceLayer()
                {
                    Url = Path
                };

                OnAddLayer();

                layer.ID = ID;

                layer.Initialized          += OnLayerInitalized;
                layer.InitializationFailed += (o, e) =>
                {
                    OnDone();
                };
            }
            return(layer);
        }
Esempio n. 20
0
        public void CloneLayerTest()
        {
            ArcGISTiledMapServiceLayer originalLayer = new ArcGISTiledMapServiceLayer();
            originalLayer.ID = "OriLayer";
            originalLayer.Url = "http://www.example.com";
            originalLayer.Opacity = 1.0;

            ArcGISTiledMapServiceLayer copiedLayer = (ArcGISTiledMapServiceLayer) MapLayersManager.Instance.CloneLayer(originalLayer);
            Assert.AreEqual(copiedLayer.ID, originalLayer.ID);
            Assert.AreEqual(copiedLayer.Url, originalLayer.Url);
            Assert.AreEqual(copiedLayer.Opacity, originalLayer.Opacity);
        }
        private void AddOnlineBaseMap()
        {
            if (Projects.UseGeographicMap)
            {
                ArcGISTiledMapServiceLayer baseLayer =
                    new ArcGISTiledMapServiceLayer();
                baseLayer.ID         = "BaseLayer";
                baseLayer.ServiceUri = "http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer";
                baseLayer.IsVisible  = true;

                Map.Layers.Insert(0, baseLayer);
            }
        }
        public override Client.TiledMapServiceLayer CreateBaseMapLayer(BaseMapInfo baseMapInfo)
        {
            ArcGISTiledMapServiceLayer agsLayer = new ArcGISTiledMapServiceLayer() { Url = baseMapInfo.Url };
            
            // Apply proxy if necessary
            if (baseMapInfo.UseProxy)
            {
                agsLayer.ProxyURL = ProxyUrl;
                LayerExtensions.SetUsesProxy(agsLayer, true);
            }

            return agsLayer;
        }
        private void AddLayerButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            MyMap.Layers.Clear();

            ArcGISTiledMapServiceLayer NewTiledLayer = new ArcGISTiledMapServiceLayer();

            MyMap.Layers.LayersInitialized += (evtsender, args) =>
            {
                MyMap.ZoomTo(NewTiledLayer.InitialExtent);
            };

            NewTiledLayer.Url = UrlTextBox.Text;
            MyMap.Layers.Add(NewTiledLayer);
        }
        private void AddLayerButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            MyMap.Layers.Clear();

            ArcGISTiledMapServiceLayer NewTiledLayer = new ArcGISTiledMapServiceLayer();

            MyMap.Layers.LayersInitialized += (evtsender, args) =>
            {
                MyMap.ZoomTo(NewTiledLayer.InitialExtent);
            };

            NewTiledLayer.Url = UrlTextBox.Text;
            MyMap.Layers.Add(NewTiledLayer);
        }
Esempio n. 25
0
        public MainPage()
        {
            InitializeComponent();

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

            //MyMap.Extent = initialExtent;

            _candidateGraphicsLayer = MyMap.Layers["CandidateGraphicsLayer"] as GraphicsLayer;
            arcgisLayer             = MyMap.Layers["CensusLayer"] as ArcGISTiledMapServiceLayer;

            LoadComboBoxData();
        }
        /// <summary>
        /// Initializes layers and tasks
        /// </summary>
        protected override async Task InitializeAsync()
        {
            // Create map with layers and set startup location
            var map = new Map()
            {
                InitialExtent = new Envelope(-13636132.3698584, 4546349.82732426, -13633579.1021618, 4547513.1599185, SpatialReferences.WebMercator)
            };

            Map = map;

            // Basemap layer from ArcGIS Online hosted service
            var basemap = new ArcGISTiledMapServiceLayer()
            {
                ID          = "Basemap",
                DisplayName = "Basemap",
                ServiceUri  = "http://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer"
            };

            // Initialize layer in Try - Catch
            Exception exceptionToHandle = null;

            try
            {
                await basemap.InitializeAsync();

                map.Layers.Add(basemap);

                // Create graphics layer for start and endpoints
                CreateEndpointLayer();
                CreateRouteLayer();

                // Create geocoding and routing tasks
                _locatorTask  = new LocalLocatorTask(@"../../../../Data/Locators/SanFrancisco/SanFranciscoLocator.loc");
                _routeTask    = new LocalRouteTask(@"../../../../Data/Networks/RuntimeSanFrancisco.geodatabase", "Routing_ND");
                IsInitialized = true;
            }
            catch (Exception exception)
            {
                // Exception is thrown ie if layer url is not found - ie. {"Error code '400' : 'Invalid URL'"}
                exceptionToHandle = exception;
            }

            if (exceptionToHandle != null)
            {
                // Initialization failed, show message and return
                await MessageService.Instance.ShowMessage(string.Format(
                                                              "Could not create basemap. Error = {0}", exceptionToHandle.ToString()),
                                                          "An error occured");
            }
        }
        public MainPage()
        {
            InitializeComponent();

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

            //MyMap.Extent = initialExtent;

            _candidateGraphicsLayer = MyMap.Layers["CandidateGraphicsLayer"] as GraphicsLayer;
            arcgisLayer = MyMap.Layers["CensusLayer"] as ArcGISTiledMapServiceLayer;

            LoadComboBoxData();
        }
        // When map service item selected in Listbox, choose appropriate type and add to the map
        void webclient_DownloadStringCompleted(object sender, ArcGISWebClient.DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null)
                {
                    throw new Exception(e.Error.Message);
                }

                // Get the service url from the user object
                string svcUrl = e.UserState as string;

                // Abstract JsonValue holds json response
                JsonValue serviceInfo = JsonObject.Parse(e.Result);
                // Use "singleFusedMapCache" to determine if a tiled or dynamic layer should be added to the map
                bool isTiledMapService = Boolean.Parse(serviceInfo["singleFusedMapCache"].ToString());

                Layer lyr = null;

                if (isTiledMapService)
                {
                    lyr = new ArcGISTiledMapServiceLayer()
                    {
                        Url = svcUrl
                    }
                }
                ;
                else
                {
                    lyr = new ArcGISDynamicMapServiceLayer()
                    {
                        Url = svcUrl
                    }
                };

                if (lyr != null)
                {
                    lyr.InitializationFailed += (a, b) =>
                    {
                        throw new Exception(lyr.InitializationFailure.Message);
                    };
                    MyMap.Layers.Add(lyr);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 29
0
            /// <summary>
            /// Initializes a new instance of the MainViewModel class.
            /// </summary>
            public MainViewModel()
            {
                if (IsInDesignMode)
                {
                    // Code runs in Blend --> create design time data.
                }
                else
                {
                    // Code runs "for real"
                    ConfigService config = new ConfigService();
                    this.myModel = config.LoadJSON();

                    this.SearchRelayCommand = new RelayCommand<int>(Search);
                    this.ZoomRelayCommand = new RelayCommand(Zoom);
                    // added
                    
                    Messenger.Default.Register<Esri.ArcGISRuntime.Controls.MapView>(this, (mapView) =>
                    {
                        this.mapView = mapView;

                        this.mapView.MapGrid = new LatLonMapGrid(LatLonMapGridLabelStyle.DegreesMinutesSeconds);

                        this.mapView.InteractionOptions.PanOptions.IsEnabled = true;
                        this.mapView.InteractionOptions.PanOptions.IsDragEnabled = true;
                        this.mapView.InteractionOptions.PanOptions.IsFlickEnabled = true;
                        this.mapView.InteractionOptions.PanOptions.IsKeyboardEnabled = true;

                        this.mapView.InteractionOptions.ZoomOptions.IsEnabled = true;
                        this.mapView.InteractionOptions.ZoomOptions.IsDoubleTappedEnabled = false;
                        this.mapView.InteractionOptions.ZoomOptions.IsMouseWheelEnabled = true;
                        this.mapView.InteractionOptions.ZoomOptions.IsPinchEnabled = true;
                        this.mapView.InteractionOptions.ZoomOptions.IsTwoFingerTapEnabled = true;
                        this.mapView.InteractionOptions.ZoomOptions.IsKeyboardEnabled = true;

                        Uri uriBasemap = new Uri(this.BasemapUri);
                        ArcGISTiledMapServiceLayer basemapLayer = new ArcGISTiledMapServiceLayer(uriBasemap);

                        Uri uriUSA = new Uri(this.USAUri);
                        ArcGISDynamicMapServiceLayer dynamicMapLayer = new ArcGISDynamicMapServiceLayer(uriUSA);

                        this.mapView.Map.Layers.Add(basemapLayer);
                        this.mapView.Map.Layers.Add(dynamicMapLayer);


                        this.SetInitialExtent();

                    });
                }
            }
Esempio n. 30
0
        // Toggle display of layer with resampled tiles vs. no data tiles
        private void ResampleNoDataTilesCheckBox_Checked(object sender, System.Windows.RoutedEventArgs e)
        {
            if (MyMap == null)
            {
                return;
            }

            ArcGISTiledMapServiceLayer resampledTiledLayer =
                MyMap.Layers["TiledLayerResampled"] as ArcGISTiledMapServiceLayer;
            ArcGISTiledMapServiceLayer showNoDataTiledLayer =
                MyMap.Layers["TiledLayerNoData"] as ArcGISTiledMapServiceLayer;

            showNoDataTiledLayer.Visible = !showNoDataTiledLayer.Visible;
            resampledTiledLayer.Visible  = !resampledTiledLayer.Visible;
        }
Esempio n. 31
0
        private void zoomToScaleLevel(int scaleLevel, ArcGISTiledMapServiceLayer layer)
        {
            double targetResolution = layer.TileInfo.Lods[scaleLevel - 1].Resolution;

            // Get the current zoom duration and update zoom duration to zero
            TimeSpan zoomDuration = AssociatedObject.ZoomDuration;

            AssociatedObject.ZoomDuration = TimeSpan.FromSeconds(0);

            // Zoom to the resolution of the specified scale level
            AssociatedObject.Zoom(targetResolution);

            // Restore the zoom duration to what it was before zooming
            AssociatedObject.ZoomDuration = zoomDuration;
        }
Esempio n. 32
0
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            if (IsInDesignMode)
            {
                // Code runs in Blend --> create design time data.
            }
            else
            {
                // Code runs "for real"
                ConfigService config = new ConfigService();
                this.myModel = config.LoadJSON();

                this.SearchRelayCommand = new RelayCommand <int>(Search);
                this.ZoomRelayCommand   = new RelayCommand(Zoom);
                // added

                Messenger.Default.Register <Esri.ArcGISRuntime.Controls.MapView>(this, (mapView) =>
                {
                    this.mapView = mapView;

                    this.mapView.MapGrid = new LatLonMapGrid(LatLonMapGridLabelStyle.DegreesMinutesSeconds);

                    this.mapView.InteractionOptions.PanOptions.IsEnabled         = true;
                    this.mapView.InteractionOptions.PanOptions.IsDragEnabled     = true;
                    this.mapView.InteractionOptions.PanOptions.IsFlickEnabled    = true;
                    this.mapView.InteractionOptions.PanOptions.IsKeyboardEnabled = true;

                    this.mapView.InteractionOptions.ZoomOptions.IsEnabled             = true;
                    this.mapView.InteractionOptions.ZoomOptions.IsDoubleTappedEnabled = false;
                    this.mapView.InteractionOptions.ZoomOptions.IsMouseWheelEnabled   = true;
                    this.mapView.InteractionOptions.ZoomOptions.IsPinchEnabled        = true;
                    this.mapView.InteractionOptions.ZoomOptions.IsTwoFingerTapEnabled = true;
                    this.mapView.InteractionOptions.ZoomOptions.IsKeyboardEnabled     = true;

                    Uri uriBasemap = new Uri(this.BasemapUri);
                    ArcGISTiledMapServiceLayer basemapLayer = new ArcGISTiledMapServiceLayer(uriBasemap);

                    Uri uriUSA = new Uri(this.USAUri);
                    ArcGISDynamicMapServiceLayer dynamicMapLayer = new ArcGISDynamicMapServiceLayer(uriUSA);

                    this.mapView.Map.Layers.Add(basemapLayer);
                    this.mapView.Map.Layers.Add(dynamicMapLayer);


                    this.SetInitialExtent();
                });
            }
        }
Esempio n. 33
0
        private async void TryLoadOnlineLayers()
        {
            try
            {
                // create an online tiled map service layer, an online feature layer
                var basemapLayer = new ArcGISTiledMapServiceLayer(new Uri(basemapUrl));
                var operationalLayer = new FeatureLayer(new Uri(operationalUrl));

                // give the feature layer an ID so it can be found later
                operationalLayer.ID = "Sightings";

                // initialize the layers
                await basemapLayer.InitializeAsync();
                await operationalLayer.InitializeAsync();

                // see if there was an exception when initializing the layers, if so throw an exception
                if (basemapLayer.InitializationException != null || operationalLayer.InitializationException != null)
                {
                    // unable to load one or more of the layers, throw an exception
                    throw new Exception("Could not initialize layers");
                }

                // add layers
                MyMapView.Map.Layers.Add(basemapLayer);
                MyMapView.Map.Layers.Add(operationalLayer);
            }
            catch (ArcGISWebException arcGisExp)
            {
                //token required?
                MessageBox.Show("Unable to load online layers: credentials may be required", "Load Error");
            }

            catch (System.Net.Http.HttpRequestException httpExp)
            {
                // not connected? server down? wrong URI?
                MessageBox.Show("Unable to load online layers: check your connection and verify service URLs", "Load Error");


            }

            catch (Exception exp)
            {
                // other problems ...
                MessageBox.Show("Unable to load online layers: " + exp.Message, "Load Error");


            }
        }
Esempio n. 34
0
        public override Client.TiledMapServiceLayer CreateBaseMapLayer(BaseMapInfo baseMapInfo)
        {
            ArcGISTiledMapServiceLayer agsLayer = new ArcGISTiledMapServiceLayer()
            {
                Url = baseMapInfo.Url
            };

            // Apply proxy if necessary
            if (baseMapInfo.UseProxy)
            {
                agsLayer.ProxyURL = ProxyUrl;
                LayerExtensions.SetUsesProxy(agsLayer, true);
            }

            return(agsLayer);
        }
Esempio n. 35
0
        public void ArcGISTiledMapServiceLayer_TileLoaded(object sender, ESRI.ArcGIS.Client.TiledLayer.TileLoadEventArgs e)
        {
            if (isNoDataTile(e.ImageStream, MyMap.SpatialReference.WKID))
            {
                ArcGISTiledMapServiceLayer layer = sender as ArcGISTiledMapServiceLayer;

                // Create writeable bitmap of the same size as layer tile
                WriteableBitmap bmp = new WriteableBitmap(layer.TileInfo.Width, layer.TileInfo.Height);

                // Set image source to writeable bitmap.  Writeable bitmap
                e.ImageSource = bmp;

                // Start the resampling process
                ResampleNoDataTile(bmp, 1, e.Level, e.Row, e.Column, layer.TileInfo.Width, layer.TileInfo.Height, layer.Url);
            }
        }
Esempio n. 36
0
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            if (IsInDesignMode)
            {
                // Code runs in Blend --> create design time data.
            }
            else
            {
                // Code runs "for real"
                ConfigService config = new ConfigService();
                this.myModel = config.LoadJSON();

                this.SearchRelayCommand = new RelayCommand<int>(Search);


                Messenger.Default.Register<Esri.ArcGISRuntime.Controls.MapView>(this, (mapView) =>
                {
                    this.mapView = mapView;


                    Uri uriBasemap = new Uri(this.BasemapUri);
                    ArcGISTiledMapServiceLayer basemapLayer = new ArcGISTiledMapServiceLayer(uriBasemap);
                    basemapLayer.InitializeAsync();
                    this.mapView.Map.Layers.Add(basemapLayer);

                    this.graphicsLayerCity = new Esri.ArcGISRuntime.Layers.GraphicsLayer();
                    this.graphicsLayerCity.ID = "City Results";
                    this.graphicsLayerCity.InitializeAsync();

                    this.graphicsLayerCounty = new Esri.ArcGISRuntime.Layers.GraphicsLayer();
                    this.graphicsLayerCounty.ID = "County Results";
                    this.graphicsLayerCounty.InitializeAsync();

                    this.graphicsLayerState = new Esri.ArcGISRuntime.Layers.GraphicsLayer();
                    this.graphicsLayerState.ID = "State Results";
                    this.graphicsLayerState.InitializeAsync();

                    this.mapView.Map.Layers.Add(this.graphicsLayerCity);
                    this.mapView.Map.Layers.Add(this.graphicsLayerState);
                    this.mapView.Map.Layers.Add(this.graphicsLayerCounty);
                    
                    

                   
                });     
            }
        }
 private void Menu_ItemSelected(object sender, EventArgs e)
 {
     ArcGISTiledMapServiceLayer arcgisLayer = MyMap.Layers["AGOLayer"] as ArcGISTiledMapServiceLayer;
     ApplicationBarMenuItem menuItem = sender as ApplicationBarMenuItem;
     switch (menuItem.Text) 
     {
         case "Aerial":
             arcgisLayer.Url = "http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer";
             break;
         case "Road":
             arcgisLayer.Url = "http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer";
             break;
         case "Topo":
             arcgisLayer.Url = "http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer";
             break;
     }            
 }
        protected override async Task InitializeAsync()
        {
            // Create map with layers and set startup location
            var map = new Map()
            {
                InitialExtent = new Envelope(-13636132.3698584, 4546349.82732426, -13633579.1021618, 4547513.1599185, SpatialReferences.WebMercator)
            };

            Map = map;

            // Basemap layer from ArcGIS Online hosted service
            var basemap = new ArcGISTiledMapServiceLayer()
            {
                ID          = "Basemap",
                DisplayName = "Basemap",
                ServiceUri  = "http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer"
            };

            // Initialize layer in Try - Catch
            Exception exceptionToHandle = null;

            try
            {
                await basemap.InitializeAsync();

                map.Layers.Add(basemap);
                await CreateOperationalLayersAsync();

                IsInitialized = true;
            }
            catch (Exception exception)
            {
                // Exception is thrown ie if layer url is not found - ie. {"Error code '400' : 'Invalid URL'"}
                exceptionToHandle = exception;
            }

            if (exceptionToHandle != null)
            {
                // Initialization failed, show message and return
                await MessageService.Instance.ShowMessage(string.Format(
                                                              "Could not create basemap. Error = {0}", exceptionToHandle.ToString()),
                                                          "An error occured");

                return;
            }
        }
Esempio n. 39
0
        public ExMap(MapView esriMapView)
        {
            _mapView = esriMapView;

            ArcGISTiledMapServiceLayer layer = new ArcGISTiledMapServiceLayer();

            layer.ServiceUri = "http://server.arcgisonline.com/arcgis/rest/services/ESRI_StreetMap_World_2D/MapServer";

            _myLocationLayer        = new GraphicsLayer();
            _redliningGraphicsLayer = new GraphicsLayer();

            _mapView.Map.Layers.Add(layer);
            _mapView.Map.Layers.Add(_redliningGraphicsLayer);
            _mapView.Map.Layers.Add(_myLocationLayer);

            _mapView.ExtentChanged       += _mapView_ExtentChanged;
            _mapView.NavigationCompleted += _mapView_NavigationCompleted;

            //////////Init DrawControl//////////
            //_drawControl = new DrawControl(_mapView);
            //_drawMode = GeoDrawMode.None;
            //_drawControl.SetDrawMode(DrawMode.None);
            //_drawControl.DrawCompletedEvent += _drawControl_DrawCompletedEvent;

            ///////Init default Draw Symbols////////
            PointMarkerSymbol = new SimpleMarkerSymbol();

            PointMarkerSymbol.Color = Colors.Red;
            PointMarkerSymbol.Size  = 15;
            PointMarkerSymbol.Style = SimpleMarkerStyle.Circle;

            PolygonFillSymbol               = new SimpleFillSymbol();
            PolygonFillSymbol.Outline       = new SimpleLineSymbol();
            PolygonFillSymbol.Outline.Color = Colors.Red;
            PolygonFillSymbol.Outline.Width = 3;
            PolygonFillSymbol.Color         = Color.FromArgb(100, 255, 0, 0);

            LineSymbol       = new SimpleLineSymbol();
            LineSymbol.Color = Colors.Red;
            LineSymbol.Width = 5;
            LineSymbol.Style = SimpleLineStyle.Solid;

            TextDrawsymbol      = new TextSymbol();
            TextDrawsymbol.Text = "Text";
            TextDrawsymbol.Font = new SymbolFont("Arial", 15);
        }
Esempio n. 40
0
        public GeoMap(Map esriMap)
        {
            _map = esriMap;

            ArcGISTiledMapServiceLayer layer = new ArcGISTiledMapServiceLayer();

            layer.Url = "http://server.arcgisonline.com/arcgis/rest/services/ESRI_StreetMap_World_2D/MapServer";

            _myLocationLayer        = new GraphicsLayer();
            _redliningGraphicsLayer = new GraphicsLayer();

            _map.Layers.Add(layer);
            _map.Layers.Add(_redliningGraphicsLayer);
            _map.Layers.Add(_myLocationLayer);

            _map.ExtentChanged += _map_ExtentChanged;

            ////////Init DrawControl//////////
            _drawControl = new DrawControl(_map);
            _drawMode    = GeoDrawMode.None;
            _drawControl.SetDrawMode(DrawMode.None);
            _drawControl.DrawCompletedEvent += _drawControl_DrawCompletedEvent;

            ///////Init default Draw Symbols////////
            PointMarkerSymbol = new SimpleMarkerSymbol();

            PointMarkerSymbol.Color = new SolidColorBrush(Colors.Red);
            PointMarkerSymbol.Size  = 15;
            PointMarkerSymbol.Style = SimpleMarkerSymbol.SimpleMarkerStyle.Circle;

            PolygonFillSymbol                 = new SimpleFillSymbol();
            PolygonFillSymbol.BorderBrush     = new SolidColorBrush(Colors.Red);
            PolygonFillSymbol.BorderThickness = 3;
            PolygonFillSymbol.Fill            = new SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 255, 0, 0));

            LineSymbol       = new SimpleLineSymbol();
            LineSymbol.Color = new SolidColorBrush(Colors.Red);
            LineSymbol.Width = 5;
            LineSymbol.Style = SimpleLineSymbol.LineStyle.Solid;

            TextDrawsymbol          = new TextSymbol();
            TextDrawsymbol.Text     = "Text";
            TextDrawsymbol.FontSize = 15;
        }
Esempio n. 41
0
        public UIElement CreateMap()
        {
            _map = new Map {UseAcceleratedDisplay = false,
                            Extent = new Envelope(-2014711, 15, 156956, 12175318),
                            WrapAround = true};

            var baseMap = new ArcGISTiledMapServiceLayer
                              {
                                  ID = "BaseMap",
                                  Url =
                                      "http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer"
                              };
            baseMap.Initialized += BaseMapInitialized;
            _map.Layers.Add(baseMap);

            _flagsGraphicsLayer = new GraphicsLayer { ID = "FlagsGraphicsLayer"};
            _map.Layers.Add(_flagsGraphicsLayer);

            return _map;
        }
		protected override async Task InitializeAsync()
        {
            // Create map with layers and set startup location
            var map = new Map()
                {
                    InitialExtent = new Envelope(-13636132.3698584, 4546349.82732426, -13633579.1021618, 4547513.1599185, SpatialReferences.WebMercator)
                };
            Map = map;

            // Basemap layer from ArcGIS Online hosted service
            var basemap = new ArcGISTiledMapServiceLayer()
            {
                ID = "Basemap",
                DisplayName = "Basemap",
				ServiceUri = "http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer"
            };

            // Initialize layer in Try - Catch 
            Exception exceptionToHandle = null;
            try
            {
                await basemap.InitializeAsync();
                map.Layers.Add(basemap);
                await CreateOperationalLayersAsync();
				IsInitialized = true;
            }
            catch (Exception exception)
            {
                // Exception is thrown ie if layer url is not found - ie. {"Error code '400' : 'Invalid URL'"} 
                exceptionToHandle = exception;
            }

            if (exceptionToHandle != null)
            {
                // Initialization failed, show message and return
                await MessageService.Instance.ShowMessage(string.Format(
                    "Could not create basemap. Error = {0}", exceptionToHandle.ToString()), 
                    "An error occured");
                return;
            }
        }
Esempio n. 43
0
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            if (IsInDesignMode)
            {
                // Code runs in Blend --> create design time data.
            }
            else
            {
                // Code runs "for real"
                ConfigService config = new ConfigService();
                this.myModel = config.LoadJSON();

                this.SearchRelayCommand = new RelayCommand<int>(Search);
                this.ZoomRelayCommand = new RelayCommand(Zoom);
                //this.LayerLoadedCommand = new RelayCommand<LayerLoadedEventArgs>(e => MyMapView_LayerLoaded(e));
                
                Messenger.Default.Register<Esri.ArcGISRuntime.Controls.SceneView>(this, (sceneView) =>
                {
                    this.sceneView = sceneView;

                    Uri uriBasemap = new Uri("http://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer");
                    ArcGISTiledMapServiceLayer basemapLayer = new ArcGISTiledMapServiceLayer(uriBasemap);

                    Uri uriUSA = new Uri(this.USAUri);
                    ArcGISDynamicMapServiceLayer dynamicMapLayer = new ArcGISDynamicMapServiceLayer(uriUSA);

                    this.sceneView.Scene.Layers.Add(basemapLayer);
                    this.sceneView.Scene.Layers.Add(dynamicMapLayer);


                    //DrawSphere();

                    //DrawModel();

                    this.camera = this.sceneView.Camera;

                });
            }
        }
Esempio n. 44
0
 /// <summary>
 /// Add new dynamic base layer at a specific position
 /// </summary>
 /// <param name="layerUrl">URL of the rest mapservice</param>
 /// <param name="visible">Visible or not</param>
 /// <param name="layerName">Layername allocated</param>
 /// <param name="index">Position in the map</param>
 public void AddNewDynamicLayer(string layerUrl, bool visible, string layerName, int index,ArcGISServiceType serviceType)
 {
     if (serviceType == ArcGISServiceType.Dynamic)
     {
         ArcGISDynamicMapServiceLayer mapLayer = new ArcGISDynamicMapServiceLayer()
         {
             Url = layerUrl,
             DisableClientCaching = true,
             ID = layerName,
             Visible = visible
         };
         mapLayer.Initialized += InitializedDynamicLayer;
         mapLayer.InitializationFailed += layer_InitializationFailed;
         if (index < 0)
             mapControl.Layers.Add(mapLayer);
         else
             mapControl.Layers.Insert(index, mapLayer);
     }
     else if (serviceType == ArcGISServiceType.Image)
     {
         ArcGISTiledMapServiceLayer mapLayer = new ArcGISTiledMapServiceLayer()
         {
             Url = layerUrl,
             ID = layerName,
             Visible = visible
         };
         mapLayer.Initialized += InitializedDynamicLayer;
         mapLayer.InitializationFailed += layer_InitializationFailed;
         if (index < 0)
             mapControl.Layers.Add(mapLayer);
         else
             mapControl.Layers.Insert(index, mapLayer);
     }
 }
Esempio n. 45
0
        /// <summary>
        /// Add a new layer
        /// </summary>
        /// <param name="id">Layer ID</param>
        /// <param name="url">URL of the layer</param>
        /// <returns></returns>
        public Layer AddLayer(string id, string url)
        {
            ArcGISTiledMapServiceLayer newLayer = new ArcGISTiledMapServiceLayer();
            newLayer.Url = url;
            newLayer.Visible = true;
            newLayer.Opacity = 1;
            newLayer.ID = id;

            layers.Add(newLayer);
            if (MapLayerAdded != null)
                MapLayerAdded(newLayer.ID);

            return newLayer;
        }
Esempio n. 46
0
        /// <summary>
        /// Create a clone of a layer
        /// </summary>
        /// <param name="originalLayer">Layer to be cloned</param>
        /// <returns></returns>
        /*public Layer CloneLayer(Layer originalLayer)
        {
            switch (originalLayer.GetType().Name)
            {
                case "ArcGISTiledMapServiceLayer":
                    ArcGISTiledMapServiceLayer cloneLayer = new ArcGISTiledMapServiceLayer();
                    cloneLayer.Url = (originalLayer as ArcGISTiledMapServiceLayer).Url;
                    cloneLayer.ID = (originalLayer as ArcGISTiledMapServiceLayer).ID;
                    cloneLayer.Opacity = (originalLayer as ArcGISTiledMapServiceLayer).Opacity;
                    return cloneLayer;
                case "ArcGISDynamicMapServiceLayer":
                    ArcGISDynamicMapServiceLayer cloneLayer2 = new ArcGISDynamicMapServiceLayer();
                    cloneLayer2.Url = (originalLayer as ArcGISDynamicMapServiceLayer).Url;
                    cloneLayer2.ID = (originalLayer as ArcGISDynamicMapServiceLayer).ID;
                    cloneLayer2.Opacity = (originalLayer as ArcGISDynamicMapServiceLayer).Opacity;
                    return cloneLayer2;
                case "GraphicsLayer":
                    GraphicsLayer cloneLayer3 = new GraphicsLayer();
                    cloneLayer3.ID = (originalLayer as GraphicsLayer).ID;
                    cloneLayer3.Opacity = (originalLayer as GraphicsLayer).Opacity;
                    return cloneLayer3;
                default:
                    return null;

            }
        }*/
        public Layer CloneLayer(Layer originalLayer)
        {
            if (typeof(ClonableLayer).IsAssignableFrom(originalLayer.GetType()))
            {
                // If the layer implements its own clone function, use this.
                return ((ClonableLayer)originalLayer).CloneLayer();
            }
            else if (originalLayer is ArcGISTiledMapServiceLayer)
            {
                ArcGISTiledMapServiceLayer cloneLayer = new ArcGISTiledMapServiceLayer();
                cloneLayer.Url = (originalLayer as ArcGISTiledMapServiceLayer).Url;
                cloneLayer.ID = (originalLayer as ArcGISTiledMapServiceLayer).ID;
                cloneLayer.Opacity = (originalLayer as ArcGISTiledMapServiceLayer).Opacity;
                cloneLayer.Visible = originalLayer.Visible;
                return cloneLayer;
            }
            else if (originalLayer is ArcGISDynamicMapServiceLayer)
            {
                ArcGISDynamicMapServiceLayer cloneLayer = new ArcGISDynamicMapServiceLayer();
                cloneLayer.Url = (originalLayer as ArcGISDynamicMapServiceLayer).Url;
                cloneLayer.ID = (originalLayer as ArcGISDynamicMapServiceLayer).ID;
                cloneLayer.Opacity = (originalLayer as ArcGISDynamicMapServiceLayer).Opacity;
                cloneLayer.Visible = originalLayer.Visible;
                return cloneLayer;
            }
            else if (originalLayer is FeatureLayer)
            {
                FeatureLayer cloneLayer = new FeatureLayer();
                cloneLayer.Url = (originalLayer as FeatureLayer).Url;
                cloneLayer.ID = (originalLayer as FeatureLayer).ID;
                cloneLayer.Opacity = (originalLayer as FeatureLayer).Opacity;
                cloneLayer.Visible = originalLayer.Visible;
                return cloneLayer;
            }
            else if (originalLayer is GraphicsLayer)
            {
                GraphicsLayer cloneLayer = new GraphicsLayer();
                cloneLayer.ID = (originalLayer as GraphicsLayer).ID;
                cloneLayer.Opacity = (originalLayer as GraphicsLayer).Opacity;
                cloneLayer.Visible = originalLayer.Visible;
                DeepCopyGraphics((originalLayer as GraphicsLayer), cloneLayer);
                return cloneLayer;
            }
            else
                return null;
        }
Esempio n. 47
0
        /// <summary>
        /// Initializes the layer by creating the appropriate ESRI.ArcGIS.Client.Layer and 
        /// holding onto it (_internalLayer).
        /// </summary>
        public void InitializeAsync(Map map, object userState, EventHandler<LayerInitializedEventArgs> callback)
        {
            if (_internalLayer != null)
                return;


            ConnectionStatus = LayerConnectionStatus.NotConnected;

            // determine the layer type - TODO - change this when the web map format supports Bing and OSM
            //
            TileLayer.LayerType bingLayerType = TileLayer.LayerType.Aerial;
            switch (LayerDescription.LayerType)
            {
                case "BingMapsAerial":
                    bingLayerType = TileLayer.LayerType.Aerial;
                    Type = LayerType.BingLayer;
                    break;
                case "BingMapsRoad":
                    bingLayerType = TileLayer.LayerType.Road;
                    Type = LayerType.BingLayer;
                    break;
                case "BingMapsHybrid":
                    bingLayerType = TileLayer.LayerType.AerialWithLabels;
                    Type = LayerType.BingLayer;
                    break;
                case "OpenStreetMap":
                    Type = LayerType.OpenStreetMapLayer;
                    break;
                default:
                    if (LayerDescription.Service is ImageService)
                        Type = LayerType.ArcGISImageServiceLayer;
                    else if (LayerDescription.Service is FeatureLayerService)
                        Type = LayerType.ArcGISFeatureServiceLayer;
                    else
                    {
                        bool tiled = LayerDescription.Service is MapService && ((MapService)LayerDescription.Service).IsTiled &&
                          (map.SpatialReference == null || map.SpatialReference.Equals(((MapService)LayerDescription.Service).SpatialReference));
                        Type = tiled ? LayerType.ArcGISTiledMapServiceLayer : LayerType.ArcGISDynamicMapServiceLayer;

                        // if the service's spatial reference is different from the map's spatial reference, always set the layer type to be
                        // ArcGISDynamicMapServiceLayer
                        if (map != null && LayerDescription.Service != null)
                            if (!SpatialReference.AreEqual(LayerDescription.Service.SpatialReference, map.SpatialReference, true))
                                Type = LayerType.ArcGISDynamicMapServiceLayer;
                    }
                    break;
            }

            // now create the appropriate ESRI.ArcGIS.Client.Layer
            //
            string proxy = (LayerDescription.Service != null && LayerDescription.Service.RequiresProxy) ? ArcGISOnlineEnvironment.ConfigurationUrls.ProxyServerEncoded : null;

            if (Type == LayerType.ArcGISTiledMapServiceLayer)
            {
                ArcGISTiledMapServiceLayer tiledLayer = new ArcGISTiledMapServiceLayer() { Url = this.Url, ProxyURL = proxy };
                _internalLayer = tiledLayer;
                MapService mapService = LayerDescription.Service as MapService;
                if (mapService != null && mapService.TileInfo != null && mapService.TileInfo.LODs != null)
                {
                    double maxResolution = 0;
                    double minResolution = 0;
                    foreach (LODInfo lod in mapService.TileInfo.LODs)
                    {
                        if (lod.Resolution > maxResolution)
                            maxResolution = lod.Resolution;
                        if (minResolution <= 0 || minResolution > lod.Resolution)
                            minResolution = lod.Resolution;
                    }
                    if (maxResolution > 0)
                        tiledLayer.MaximumResolution = maxResolution * 4;
                    if (minResolution > 0)
                        tiledLayer.MinimumResolution = minResolution / 4;
                }
            }
            else if (Type == LayerType.ArcGISDynamicMapServiceLayer)
                _internalLayer = new ArcGISDynamicMapServiceLayer() { Url = this.Url, ProxyURL = proxy };
            else if (Type == LayerType.ArcGISImageServiceLayer)
            {
                int[] bandIds = ((ImageService)LayerDescription.Service).BandCount < 4 ? null : new int[] { 0, 1, 2 };
                _internalLayer = new ArcGISImageServiceLayer() { Url = this.Url, ProxyURL = proxy, ImageFormat = ArcGISImageServiceLayer.ImageServiceImageFormat.PNG8, BandIds = bandIds };
            }
            else if (Type == LayerType.ArcGISFeatureServiceLayer)
            {
                _internalLayer = new FeatureLayer() { 
                    Url = this.Url, 
                    ProxyUrl = proxy, 
                    Mode = LayerDescription.QueryMode, 
                    OutFields = new ESRI.ArcGIS.Client.Tasks.OutFields() { "*" },
                    Renderer = new ESRI.ArcGIS.Mapping.Core.Symbols.HiddenRenderer()
               };
            }
            else if (Type == LayerType.OpenStreetMapLayer)
                _internalLayer = new OpenStreetMapLayer();
            else if (Type == LayerType.BingLayer)
            {
                TileLayer tileLayer = new TileLayer() { LayerStyle = bingLayerType };
                tileLayer.Token = ArcGISOnlineEnvironment.BingToken;
                tileLayer.ServerType = ServerType.Production;

                _internalLayer = tileLayer;
            }

            _internalLayer.Visible = LayerDescription.Visible;
            _internalLayer.Opacity = LayerDescription.Opacity;

            if (!string.IsNullOrEmpty(LayerDescription.Title))
                _internalLayer.SetValue(ESRI.ArcGIS.Client.Extensibility.MapApplication.LayerNameProperty, LayerDescription.Title);

            if (LayerDescription.IsReference)
                ESRI.ArcGIS.Mapping.Core.LayerExtensions.SetIsReferenceLayer(_internalLayer, true);

            // remember the map's spatial reference in order to determine after initialization
            // if the layer will work properly
            //
            if (map != null)
                _mapSpatialReference = map.SpatialReference;

            _internalLayer.Initialized += _internalLayer_Initialized;
            _internalLayer.InitializationFailed += _internalLayer_InitializationFailed;
            _initializationCallState = new CallState() { Callback = callback, UserState = userState };
            _internalLayer.Initialize();
        }
Esempio n. 48
0
        private void AddOnlineBaseMap()
        {
            if (Projects.UseGeographicMap)
            {
                ArcGISTiledMapServiceLayer baseLayer =
                    new ArcGISTiledMapServiceLayer();
                baseLayer.ID = "BaseLayer";
                baseLayer.ServiceUri = "http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer";
                baseLayer.IsVisible = true;

                Map.Layers.Insert(0, baseLayer);
            }
        }
        // Initializes the Layer property
        private void initializeLayer()
        {
            Layer layer = null;

            // Create the layer based on the type of service encapsulated by the search result
            if (Service is MapService)
            {
                MapService mapService = (MapService)Service;
                if (mapService.IsTiled &&
                mapService.SpatialReference.WKID == MapApplication.Current.Map.SpatialReference.WKID)
                    layer = new ArcGISTiledMapServiceLayer() { Url = Service.Url, ProxyURL = ProxyUrl };
                else
                    layer = new ArcGISDynamicMapServiceLayer() { Url = Service.Url, ProxyURL = ProxyUrl };
            }
            else if (Service is ImageService)
            {
                layer = new ArcGISImageServiceLayer() { Url = Service.Url, ProxyURL = ProxyUrl };
            }
            else if (Service is FeatureLayerService || (Service is FeatureService && ((FeatureService)Service).Layers.Count() == 1))
            {
                string url = Service is FeatureService ? string.Format("{0}/0", Service.Url) : Service.Url;
                layer = new FeatureLayer() 
                { 
                    Url = url, 
                    ProxyUrl = ProxyUrl,
                    OutFields = new OutFields() { "*" }
                };
            }

            // Initialize the layer's ID and display name
            if (layer != null)
            {
                string id = Guid.NewGuid().ToString("N");
                string name = propertyExists("Title") ? Result.Title : id;

                layer.ID = id;
                MapApplication.SetLayerName(layer, name);
            }
            Layer = layer;
        }
        // When map service item selected in Listbox, choose appropriate type and add to the map
        void webclient_DownloadStringCompleted(object sender, ArcGISWebClient.DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null)
                    throw new Exception(e.Error.Message);

                // Get the service url from the user object
                string svcUrl = e.UserState as string;

                //only available in Silverlight or .Net 4.5
                // Abstract JsonValue holds json response
                // JsonValue serviceInfo = JsonObject.Parse(e.Result);

                string[] jsonPairs = e.Result.Split(',');
                string mapCachePair = jsonPairs.Where(json => json.Contains("singleFusedMapCache")).FirstOrDefault();
                string[] mapCacheKeyAndValue = mapCachePair.Split(':');
                bool isTiledMapService = Boolean.Parse(mapCacheKeyAndValue[1]);

                // Use "singleFusedMapCache" to determine if a tiled or dynamic layer should be added to the map
                //bool isTiledMapService = Boolean.Parse(serviceInfo["singleFusedMapCache"].ToString());

                Layer lyr = null;

                if (isTiledMapService)
                    lyr = new ArcGISTiledMapServiceLayer() { Url = svcUrl };
                else
                    lyr = new ArcGISDynamicMapServiceLayer() { Url = svcUrl };

                if (lyr != null)
                {
                    lyr.InitializationFailed += (a, b) =>
                    {
                        throw new Exception(lyr.InitializationFailure.Message);
                    };
                    MyMap.Layers.Add(lyr);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        // When map service item selected in Listbox, choose appropriate type and add to the map
        void webclient_DownloadStringCompleted(object sender, ArcGISWebClient.DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null)
                    throw new Exception(e.Error.Message);

                // Get the service url from the user object
                string svcUrl = e.UserState as string;

                // Abstract JsonValue holds json response
                JsonValue serviceInfo = JsonObject.Parse(e.Result);
                // Use "singleFusedMapCache" to determine if a tiled or dynamic layer should be added to the map
                bool isTiledMapService = Boolean.Parse(serviceInfo["singleFusedMapCache"].ToString());

                Layer lyr = null;

                if (isTiledMapService)
                    lyr = new ArcGISTiledMapServiceLayer() { Url = svcUrl };
                else
                    lyr = new ArcGISDynamicMapServiceLayer() { Url = svcUrl };

                if (lyr != null)
                {
                    lyr.InitializationFailed += (a, b) =>
                    {
                        throw new Exception(lyr.InitializationFailure.Message);
                    };
                    MyMap.Layers.Add(lyr);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
		/// <summary>
		/// Initializes layers and tasks
		/// </summary>
        protected override async Task InitializeAsync()
        {
            // Create map with layers and set startup location
            var map = new Map()
                {
                    InitialExtent = new Envelope(-13636132.3698584, 4546349.82732426, -13633579.1021618, 4547513.1599185, SpatialReferences.WebMercator)
                };
            Map = map;

            // Basemap layer from ArcGIS Online hosted service
            var basemap = new ArcGISTiledMapServiceLayer()
            {
                ID = "Basemap",
                DisplayName = "Basemap",
				ServiceUri = "http://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer"
			};

            // Initialize layer in Try - Catch 
            Exception exceptionToHandle = null;
            try
            {
                await basemap.InitializeAsync();
                map.Layers.Add(basemap);

                // Create graphics layer for start and endpoints
                CreateEndpointLayer();
                CreateRouteLayer();

                // Create geocoding and routing tasks
				_locatorTask = new LocalLocatorTask(@"../../../../Data/Locators/SanFrancisco/SanFranciscoLocator.loc");
				_routeTask = new LocalRouteTask(@"../../../../Data/Networks/RuntimeSanFrancisco.geodatabase", "Routing_ND");
				IsInitialized = true;
			}
            catch (Exception exception)
            {
                // Exception is thrown ie if layer url is not found - ie. {"Error code '400' : 'Invalid URL'"} 
                exceptionToHandle = exception;
            }

            if (exceptionToHandle != null)
            {
                // Initialization failed, show message and return
                await MessageService.Instance.ShowMessage(string.Format(
                    "Could not create basemap. Error = {0}", exceptionToHandle.ToString()),
                    "An error occured");
            }
        }
Esempio n. 53
0
        public void RemoveMapLayerTest()
        {
            ArcGisMap_Accessor target = new ArcGisMap_Accessor();

            int layersInitialCount = target.Map.Layers.Count;

            ArcGISTiledMapServiceLayer tiledServiceLayer = new ArcGISTiledMapServiceLayer();
            tiledServiceLayer.ID = "Imagery";
            target.RemoveMapLayer(tiledServiceLayer);

            int layersFinalCount = target.Map.Layers.Count;

            Assert.AreEqual(layersInitialCount, layersFinalCount + 1);
        }
Esempio n. 54
0
        private void ConfigureApplication(ref Configuration xmlConfiguation)
        {
            Title = xmlConfiguation.Title;
              Width = xmlConfiguation.Width;
              Height = xmlConfiguation.Height;

              ParcelLines.MaxHeight = _xmlConfiguation.MaxGridHeight;

              // insert layer before [graphical] layers defined in xaml
              Int32 layerIndex = 0;
              String lastUnit = "";
              foreach (LayerDefinition definition in xmlConfiguation.DisplayLayers)
              {
            if (definition.Type == "dynamic")
            {
              ArcGISDynamicMapServiceLayer dynamicMS = new ArcGISDynamicMapServiceLayer();
              dynamicMS.Url = definition.Url;
              dynamicMS.ID = definition.Id;
              dynamicMS.InitializationFailed += Layer_InitializationFailed;
              ParcelMap.Layers.Insert(layerIndex++, dynamicMS);
              if ((dynamicMS.Units != null) && (dynamicMS.Units != "") && !xmlConfiguation.HasSpatialReferenceUnit)
            lastUnit = dynamicMS.Units;
            }

            if (definition.Type == "feature")
            {
              FeatureLayer featureMS = new FeatureLayer();
              featureMS.Url = definition.Url + "/" + definition.Id.ToString();
              featureMS.ID = definition.Id;
              featureMS.InitializationFailed += Layer_InitializationFailed;
              featureMS.Mode = FeatureLayer.QueryMode.OnDemand;
              ParcelMap.Layers.Insert(layerIndex++, featureMS);
              // FOOBAR FeatureLayer does not support unit?
            }

            if (definition.Type == "tiled")
            {
              ArcGISTiledMapServiceLayer tiledMS = new ArcGISTiledMapServiceLayer();
              tiledMS.Url = definition.Url;
              tiledMS.ID = definition.Id;
              tiledMS.InitializationFailed += Layer_InitializationFailed;
              ParcelMap.Layers.Insert(layerIndex++, tiledMS);
              if ((tiledMS.Units != null) && (tiledMS.Units != "") && !xmlConfiguation.HasSpatialReferenceUnit)
            lastUnit = tiledMS.Units;
            }

            if (definition.Type == "image")
            {
              ArcGISImageServiceLayer imageS = new ArcGISImageServiceLayer();
              imageS.Url = definition.Url;
              imageS.ID = definition.Id;
              imageS.InitializationFailed += Layer_InitializationFailed;
              ParcelMap.Layers.Insert(layerIndex++, imageS);
            }
              }

              if (!xmlConfiguation.HasSpatialReferenceUnit)
            xmlConfiguation.MapSpatialReferenceUnits = lastUnit;

              ESRI.ArcGIS.Client.Geometry.Envelope extent = null;
              if (xmlConfiguation.IsExtentSet())
            extent = new ESRI.ArcGIS.Client.Geometry.Envelope(xmlConfiguation.XMin, xmlConfiguation.YMin, xmlConfiguation.XMax, xmlConfiguation.YMax);
              else
            // Map will not zoom to, etc with out some value set.
            // Ideally we would like to set the extent to the full extent of the first
            // layer, but since they layer has hot been drawn yet null is returned.
            extent = new ESRI.ArcGIS.Client.Geometry.Envelope(100, 100, 100, 100);

              // if zero, the first inserted layer is used
              if ((xmlConfiguation.SpatialReferenceWKT != null) && (xmlConfiguation.SpatialReferenceWKT != ""))
            extent.SpatialReference = new ESRI.ArcGIS.Client.Geometry.SpatialReference(xmlConfiguation.SpatialReferenceWKT);
              else if (xmlConfiguation.SpatialReferenceWKID != 0)
            extent.SpatialReference = new ESRI.ArcGIS.Client.Geometry.SpatialReference(xmlConfiguation.SpatialReferenceWKID);

              ParcelMap.Extent = extent;

              ParcelData parcelData = ParcelGridContainer.DataContext as ParcelData;
              parcelData.Configuration = xmlConfiguation;

              QueryLabel.Text = xmlConfiguation.QueryLabel;
        }
Esempio n. 55
0
        /// <summary>
        /// Initialize the default list of map layers
        /// </summary>
        public void InitializeDefaultMapLayers()
        {
            if (defaultLayerTypes == null || defaultLayerTypes.Count() == 0)
            {
                initializeDefaultLayerTypes();
            }

            ArcGISTiledMapServiceLayer tiledServiceLayer;

            // loop on the default layer types and create them
            foreach (MapLayerDef layerType in defaultLayerTypes)
            {
                switch (layerType.LayerType)
                {
                    case MapLayerDef.MapLayerType.StreetMap:
                        tiledServiceLayer = new ArcGISTiledMapServiceLayer();
                        tiledServiceLayer.ID = layerType.LayerID;;
                        tiledServiceLayer.Opacity = 1;
                        //tiledServiceLayer.Visible = false;
                        tiledServiceLayer.Url = layerType.LayerURL;
                        AddLayer(tiledServiceLayer);
                        break;

                    case MapLayerDef.MapLayerType.SatelliteImagery:
                        tiledServiceLayer = new ArcGISTiledMapServiceLayer();
                        tiledServiceLayer.ID = layerType.LayerID;
                        tiledServiceLayer.Opacity = 1;
                        tiledServiceLayer.Visible = true;
                        tiledServiceLayer.Url = layerType.LayerURL;
                        AddLayer(tiledServiceLayer);
                        break;

                    case MapLayerDef.MapLayerType.ShadedRelief:
                        tiledServiceLayer = new ArcGISTiledMapServiceLayer();
                        tiledServiceLayer.ID = layerType.LayerID;
                        tiledServiceLayer.Opacity = 1;
                        tiledServiceLayer.Visible = true;
                        tiledServiceLayer.Url = layerType.LayerURL;
                        AddLayer(tiledServiceLayer);
                        break;

                    case MapLayerDef.MapLayerType.OnlinePublishedMap:
                        tiledServiceLayer = new ArcGISTiledMapServiceLayer();
                        tiledServiceLayer.Visible = true;
                        tiledServiceLayer.Opacity = 1;
                        tiledServiceLayer.ID = layerType.LayerID;
                        tiledServiceLayer.Url = layerType.LayerURL;

                        AddLayer(tiledServiceLayer);
                        break;

                    case MapLayerDef.MapLayerType.OfflineAnnotationLayer:
                        GraphicsLayer _annotationsLayer = new GraphicsLayer();
                        _annotationsLayer.Visible = true;
                        _annotationsLayer.Opacity = 1;
                        _annotationsLayer.ID = layerType.LayerID;

                        AddLayer(_annotationsLayer);
                        annotationsLayerAdded = true;
                        break;

                    case MapLayerDef.MapLayerType.OnlinePointAnnotationsLayer:
                        _pointAnnotationLayer = new FeatureLayer();
                        _pointAnnotationLayer.Visible = true;
                        _pointAnnotationLayer.Opacity = 1;
                        _pointAnnotationLayer.ID = layerType.LayerID;
                        _pointAnnotationLayer.Url = layerType.LayerURL;
                        _pointAnnotationLayer.AutoSave = true;

                        AddLayer(_pointAnnotationLayer);
                        onlineAnnotationLayersAdded = true;

                        break;

                    case MapLayerDef.MapLayerType.OnlineLineAnnotationsLayer:

                        _lineAnnotationLayer = new FeatureLayer();
                        _lineAnnotationLayer.Visible = true;
                        _lineAnnotationLayer.Opacity = 1;
                        _lineAnnotationLayer.ID = layerType.LayerID;
                        _lineAnnotationLayer.Url = layerType.LayerURL;
                        _lineAnnotationLayer.AutoSave = true;

                        AddLayer(_lineAnnotationLayer);
                        onlineAnnotationLayersAdded = true;
                        break;

                    case MapLayerDef.MapLayerType.OnlinePolygonAnnotationsLayer:
                        _polygonAnnotationLayer = new FeatureLayer();
                        _polygonAnnotationLayer.Visible = true;
                        _polygonAnnotationLayer.Opacity = 1;
                        _polygonAnnotationLayer.ID = layerType.LayerID;
                        _polygonAnnotationLayer.Url = layerType.LayerURL;

                        AddLayer(_polygonAnnotationLayer);
                        onlineAnnotationLayersAdded = true;

                        break;
                }
            }

            if (onlineAnnotationLayersAdded)
            {
                //Create a timer that will request a server update in three seconds, to allow time to store new features remotely.
                UpdateTimer = new DispatcherTimer();
                UpdateTimer.IsEnabled = false;
                UpdateTimer.Interval = new TimeSpan(0, 0, 3);
                UpdateTimer.Tick += UpdateAnnotationLayersTimer;
            }

            GraphicsLayer graphicsLayer = new GraphicsLayer();
            graphicsLayer.ID = "BookmarksLayer";
            AddLayer(graphicsLayer);
            bookmarkLayerAdded = true;

            if (MapLayersInitialized != null)
                MapLayersInitialized();
        }
        public Layer CloneLayer(Layer layer)
        {
            if (layer == null)
                return null;

            ICustomLayer customLayer = layer as ICustomLayer;
            if (customLayer != null)
                return customLayer.CloneLayer();

            ArcGISDynamicMapServiceLayer dynamicMapServiceLayer = layer as ArcGISDynamicMapServiceLayer;
            if (dynamicMapServiceLayer != null)
            {
                ArcGISDynamicMapServiceLayer newLayer = new ArcGISDynamicMapServiceLayer()
                {
                    ImageFormat = dynamicMapServiceLayer.ImageFormat,
                    ProxyURL = dynamicMapServiceLayer.ProxyURL,
                    Token = dynamicMapServiceLayer.Token,
                    Url = dynamicMapServiceLayer.Url,
                    DisableClientCaching = dynamicMapServiceLayer.DisableClientCaching,
                    LayerDefinitions = dynamicMapServiceLayer.LayerDefinitions,
                    VisibleLayers = dynamicMapServiceLayer.VisibleLayers,
                };
                copyBaseLayerAttributes(layer, newLayer);
                return newLayer;
            }

            ArcGISTiledMapServiceLayer tiledMapServiceLayer = layer as ArcGISTiledMapServiceLayer;
            if (tiledMapServiceLayer != null)
            {
                ArcGISTiledMapServiceLayer newLayer = new ArcGISTiledMapServiceLayer()
                {
                    ProxyURL = tiledMapServiceLayer.ProxyURL,
                    Token = tiledMapServiceLayer.Token,
                    Url = tiledMapServiceLayer.Url,
                };
                copyBaseLayerAttributes(layer, newLayer);
                return newLayer;
            }

            TileLayer tileLayer = layer as TileLayer;
            if (tileLayer != null)
            {
                TileLayer newLayer = new TileLayer()
                {
                    Culture = tileLayer.Culture,
                    LayerStyle = tileLayer.LayerStyle,
                    ServerType = tileLayer.ServerType,
                    Token = tileLayer.Token,
                };
                copyBaseLayerAttributes(layer, newLayer);
                return newLayer;
            }

            FeatureLayer featureLayer = layer as FeatureLayer;
            if (featureLayer != null)
            {
                FeatureLayer newLayer = new FeatureLayer()
                {
                    AutoSave = featureLayer.AutoSave,
                    Clusterer = featureLayer.Clusterer,
                    Color = featureLayer.Color,
                    DisableClientCaching = featureLayer.DisableClientCaching,
                    FeatureSymbol = featureLayer.FeatureSymbol,
                    Geometry = featureLayer.Geometry,
                    MapTip = featureLayer.MapTip,
                    Mode = featureLayer.Mode,
                    ObjectIDs = featureLayer.ObjectIDs,
                    OnDemandCacheSize = featureLayer.OnDemandCacheSize,
                    ProxyUrl = featureLayer.ProxyUrl,
                    Renderer = featureLayer.Renderer,
                    SelectionColor = featureLayer.SelectionColor,
                    Text = featureLayer.Text,
                    Token = featureLayer.Token,
                    Url = featureLayer.Url,
                    Where = featureLayer.Where,
                };
                foreach (string outfields in featureLayer.OutFields)
                    newLayer.OutFields.Add(outfields);
                copyBaseLayerAttributes(layer, newLayer);
                return newLayer;
            }

            GraphicsLayer graphicsLayer = layer as GraphicsLayer;
            if (graphicsLayer != null)
            {
                GraphicsLayer newLayer = new GraphicsLayer()
                {
                    Clusterer = graphicsLayer.Clusterer,
                    MapTip = graphicsLayer.MapTip,
                    Renderer = graphicsLayer.Renderer,
                    IsHitTestVisible = graphicsLayer.IsHitTestVisible,
                };
                copyBaseLayerAttributes(layer, tiledMapServiceLayer);
                return newLayer;
            }

            return null;
        }
        public override void CreateLayerAsync(Resource resource, SpatialReference mapSpatialReference, object userState)
        {
            if(resource == null)
                return;

            ESRI.ArcGIS.Client.Layer layer = null;

            switch (resource.ResourceType)
            {
                case ResourceType.MapServer:
                case ResourceType.FeatureServer:
                    {
                        string url = resource.Url;
                        if (resource.ResourceType == ResourceType.FeatureServer)
                        {
                            int i = url.LastIndexOf(string.Format("/{0}", ResourceType.FeatureServer.ToString()));
                            if (i >= 0)
                            {
                                url = url.Remove(i);
                                url = string.Format("{0}/{1}", url, ResourceType.MapServer.ToString());
                            }
                        }

                        _service = ServiceFactory.CreateService(ResourceType.MapServer, url, resource.ProxyUrl);
                        if (_service != null)
                        {
                            _service.ServiceDetailsDownloadFailed += (o, e) =>
                            {
                                OnCreateLayerFailed(e);
                            };
                            _service.ServiceDetailsDownloadCompleted += (o, e) =>
                            {
                                MapService mapService = o as MapService;
                                if (mapService.ServiceInfo == null)
                                {
                                    OnCreateLayerFailed(new ExceptionEventArgs(new Exception(Resources.Strings.ExceptionUnableToRetrieveMapServiceDetails), e.UserState));
                                    return;
                                }

                                if (mapService.ServiceInfo.TileInfo != null && mapService.ServiceInfo.SingleFusedMapCache)
                                {
                                    #region Create tiled layer
                                    if (mapSpatialReference != null && !mapSpatialReference.Equals(mapService.ServiceInfo.SpatialReference))
                                    {
                                        OnCreateLayerFailed(new ExceptionEventArgs(new Exception(Resources.Strings.ExceptionCachedMapServiceSpatialReferenceDoesNotMatch), e.UserState));
                                        return;
                                    }
                                    layer = new ArcGISTiledMapServiceLayer()
                                    {
                                        Url = url,
                                        ProxyURL = getCleanProxyUrl(mapService.ProxyUrl),
                                    };

                                    if (mapService.ServiceInfo.TileInfo.LODs != null)
                                    {
                                        double maxResolution = 0;
                                        double minResolution = 0;
                                        foreach (LODInfo lod in mapService.ServiceInfo.TileInfo.LODs)
                                        {
                                            if (lod.Resolution > maxResolution)
                                                maxResolution = lod.Resolution;
                                            if (minResolution <= 0 || minResolution > lod.Resolution)
                                                minResolution = lod.Resolution;
                                        }
                                        if (maxResolution > 0 )
                                            layer.MaximumResolution = maxResolution * 4;
                                        if (minResolution > 0)
                                            layer.MinimumResolution = minResolution / 4;
                                    }
                                    #endregion
                                }
                                else
                                {
                                    #region create dynamic layer
                                    layer = new ArcGISDynamicMapServiceLayer()
                                    {
                                        Url = url,
                                        ProxyURL = getCleanProxyUrl(mapService.ProxyUrl),
                                    };
                                    #endregion
                                }

                                //Set layer's attached properties
                                if (layer != null)
                                {
                                    layer.SetValue(MapApplication.LayerNameProperty, resource.DisplayName);
                                    layer.SetValue(Core.LayerExtensions.DisplayUrlProperty, url);
                                    if (!string.IsNullOrEmpty(resource.ProxyUrl))
                                        Core.LayerExtensions.SetUsesProxy(layer, true);
                                    layer.ID = Guid.NewGuid().ToString("N");
                                }

                                OnCreateLayerCompleted(new CreateLayerCompletedEventArgs() { Layer = layer, UserState = e.UserState });

                            };

                            _service.GetServiceDetails(null);
                        }

                    } break;

                case ResourceType.ImageServer:
                    {
                        layer = new ArcGISImageServiceLayer()
                        {
                            Url = resource.Url,
                            ProxyURL = getCleanProxyUrl(resource.ProxyUrl),
                            ID = Guid.NewGuid().ToString("N"),
                        };

                        //Set layer's attached properties
                        layer.SetValue(MapApplication.LayerNameProperty, resource.DisplayName);
                        layer.SetValue(Core.LayerExtensions.DisplayUrlProperty, resource.Url);
                        if (!string.IsNullOrEmpty(resource.ProxyUrl))
                            Core.LayerExtensions.SetUsesProxy(layer, true);

                        // Need to declare handler separate from lambda expression to avoid erroneous
                        // "use of unassigned variable" build error
                        EventHandler<EventArgs> initialized = null;

                        // Need to populate the layer's metadata to handle initialization of image format
                        // and band IDs
                        initialized = (o, e) =>
                        {
                            layer.Initialized -= initialized;
                            ArcGISImageServiceLayer imageLayer = (ArcGISImageServiceLayer)layer;
                            if (imageLayer.Version < 10)
                            {
                                // Pre v10, band IDs must be specified explicitly.  But no more than 
                                // 3 can be used.  Just take up to the first 3 by default.
                                List<int> bandIDs = new List<int>();
                                for (int i = 0; i < imageLayer.BandCount; i++)
                                {
                                    bandIDs.Add(i);
                                    if (i == 2)
                                        break;
                                }

                                imageLayer.BandIds = bandIDs.ToArray();

                                // Use png format to support transparency
                                imageLayer.ImageFormat = ArcGISImageServiceLayer.ImageServiceImageFormat.PNG8;
                            }
                            else
                            {
                                // At v10 and later, band IDs do not need to be specified, and jpg/png
                                // format introduces some intelligence about which format is best
                                imageLayer.ImageFormat = 
                                    ArcGISImageServiceLayer.ImageServiceImageFormat.JPGPNG;
                            }

                            OnCreateLayerCompleted(new CreateLayerCompletedEventArgs() { Layer = layer, UserState = userState });
                        };

                        EventHandler<EventArgs> initFailed = null;
                        initFailed = (o, e) =>
                        {
                            layer.InitializationFailed -= initFailed;
                            OnCreateLayerCompleted(new CreateLayerCompletedEventArgs() { Layer = layer, UserState = userState });
                        };

                        layer.Initialized += initialized;
                        layer.InitializationFailed += initFailed;
                        layer.Initialize();
                    }
                    break;
                case ResourceType.Layer:
                case ResourceType.EditableLayer:
                    {
                        featureLayer = new Layer(resource.Url, resource.ProxyUrl);
                        featureLayer.GetLayerDetailsFailed += (o, e) =>
                        {
                            OnCreateLayerFailed(e);
                        };
                        featureLayer.GetLayerDetailsCompleted += (o, e) =>
                        {
                            if (e.LayerDetails == null)
                            {
                                OnCreateLayerFailed(new ExceptionEventArgs(new Exception(Resources.Strings.ExceptionUnableToRetrieveLayerDetails), e.UserState));
                                return;
                            }
                            if (Utility.RasterLayer.Equals(e.LayerDetails.Type))
                            {
                                OnCreateLayerFailed(new ExceptionEventArgs(new Exception(Resources.Strings.ExceptionRasterLayersNotSupported), e.UserState));
                                return;
                            }
                            else if (Utility.ImageServerLayer.Equals(e.LayerDetails.Type))
                            {
                                OnCreateLayerFailed(new ExceptionEventArgs(new Exception(Resources.Strings.ExceptionImageServerLayersNotSupported), e.UserState));
                                return;
                            }

                            if (Utility.CapabilitiesSupportsQuery(e.LayerDetails.Capabilities) == false)
                            {
                                OnCreateLayerFailed(new ExceptionEventArgs(new Exception(Resources.Strings.ExceptionLayerDoesNotSupportQuery), e.UserState));
                                return;
                            }

                            GeometryType GeometryType = GeometryType.Unknown;
                            switch (e.LayerDetails.GeometryType)
                            {
                                case "esriGeometryPoint":
                                    GeometryType = GeometryType.Point;
                                    break;
                                case "esriGeometryMultipoint":
                                    GeometryType = GeometryType.MultiPoint;
                                    break;
                                case "esriGeometryPolyline":
                                    GeometryType = GeometryType.Polyline;
                                    break;
                                case "esriGeometryPolygon":
                                    GeometryType = GeometryType.Polygon;
                                    break;
                            }
                            FeatureLayer newFeatureLayer = new FeatureLayer()
                            {
                                Url = featureLayer.Uri,
                                ProxyUrl = getCleanProxyUrl(featureLayer.ProxyUrl),
                                ID = Guid.NewGuid().ToString("N"),
                                Mode = FeatureLayer.QueryMode.OnDemand,
                                Renderer = new ESRI.ArcGIS.Mapping.Core.Symbols.HiddenRenderer()
                            };
                            newFeatureLayer.SetValue(MapApplication.LayerNameProperty, resource.DisplayName);
                            newFeatureLayer.SetValue(Core.LayerExtensions.DisplayUrlProperty, resource.Url);
                            newFeatureLayer.SetValue(Core.LayerExtensions.GeometryTypeProperty, GeometryType);
                            if (!string.IsNullOrEmpty(resource.ProxyUrl))
                                Core.LayerExtensions.SetUsesProxy(newFeatureLayer, true);
                            if (e.LayerDetails.Fields != null)
                            {
                                Collection<ESRI.ArcGIS.Mapping.Core.FieldInfo> fields = FieldInfosFromFields(e.LayerDetails.Fields);
                                newFeatureLayer.SetValue(Core.LayerExtensions.FieldsProperty, fields);
                                Core.LayerExtensions.SetDisplayField(newFeatureLayer, e.LayerDetails.DisplayField);
                            }
                            newFeatureLayer.OutFields.Add("*"); // Get all fields at configuration time
                            OnCreateLayerCompleted(new CreateLayerCompletedEventArgs() { Layer = newFeatureLayer, UserState = e.UserState, GeometryType = GeometryType });
                        };
                        featureLayer.GetLayerDetails(userState);
                    } break;

                default:
                    throw new Exception(string.Format(Resources.Strings.ExceptionCannotCreateLayerForResourceType, resource.ResourceType.ToString()));
            }
            
        }