Ejemplo n.º 1
0
        private async void Initialize()
        {
            // Load the scene with a basemap and a terrain surface.
            MySceneView.Scene = new Scene(Basemap.CreateImagery());
            MySceneView.Scene.BaseSurface.ElevationSources.Add(new ArcGISTiledElevationSource(new Uri("https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")));

            // Get the URL to the data.
            string filePath = DataManager.GetDataFolder("f10b1d37fdd645c9bc9b189fb546307c", "Esri_tour.kmz");
            Uri    kmlUrl   = new Uri(filePath);

            // Create the KML dataset and layer.
            KmlDataset dataset = new KmlDataset(kmlUrl);
            KmlLayer   layer   = new KmlLayer(dataset);

            // Add the layer to the map.
            MySceneView.Scene.OperationalLayers.Add(layer);

            try
            {
                // Load the dataset.
                await dataset.LoadAsync();

                // Find the first KML tour.
                FindKmlTour(dataset.RootNodes);

                // Handle absence of tour gracefully.
                if (_tourController.Tour == null)
                {
                    throw new InvalidOperationException("No tour found. Can't enable touring for a KML file with no tours.");
                }

                // Listen for changes to the tour status.
                _tourController.Tour.PropertyChanged += Tour_PropertyChanged;

                // Enable the play button.
                PlayButton.IsEnabled = true;

                // Hide the status bar.
                LoadingStatusBar.IsVisible = false;
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
                await Application.Current.MainPage.DisplayAlert("Error", e.ToString(), "OK");
            }
        }
        private async void MyMapView_Drop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

                KmlLayer kmlLayer = new KmlLayer(new Uri(files[0]));
                await kmlLayer.InitializeAsync();

                //Add the kml layer
                MyMapView.Map.Layers.Add(kmlLayer);

                //Zoom to the kml layer if available
                if (kmlLayer.RootFeature.Viewpoint != null)
                    await MyMapView.SetViewAsync(kmlLayer.RootFeature.Viewpoint);
            }
        }
Ejemplo n.º 3
0
        private void Initialize()
        {
            // Set up the basemap.
            _myMapView.Map = new Map(Basemap.CreateDarkGrayCanvasVector());

            // Create the dataset.
            KmlDataset dataset = new KmlDataset(new Uri("https://www.wpc.ncep.noaa.gov/kml/noaa_chart/WPC_Day1_SigWx.kml"));

            // Create the layer from the dataset.
            _forecastLayer = new KmlLayer(dataset);

            // Add the layer to the map.
            _myMapView.Map.OperationalLayers.Add(_forecastLayer);

            // Zoom to the extent of the United States.
            _myMapView.SetViewpoint(new Viewpoint(_usEnvelope));
        }
        private async void Initialize()
        {
            // Load the scene with a basemap and a terrain surface.
            _mySceneView.Scene = new Scene(Basemap.CreateImagery());
            _mySceneView.Scene.BaseSurface.ElevationSources.Add(new ArcGISTiledElevationSource(new Uri("https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")));

            // Get the URL to the data.
            string filePath = DataManager.GetDataFolder("f10b1d37fdd645c9bc9b189fb546307c", "Esri_tour.kmz");
            Uri    kmlUrl   = new Uri(filePath);

            // Create the KML dataset and layer.
            KmlDataset dataset = new KmlDataset(kmlUrl);
            KmlLayer   layer   = new KmlLayer(dataset);

            // Add the layer to the map.
            _mySceneView.Scene.OperationalLayers.Add(layer);

            try
            {
                // Load the dataset.
                await dataset.LoadAsync();

                // Find the first KML tour.
                FindKmlTour(dataset.RootNodes);

                // Handle absence of tour gracefully.
                if (_tourController.Tour == null)
                {
                    throw new InvalidOperationException("No tour found. Can't enable touring for a KML file with no tours.");
                }

                // Listen for changes to the tour status.
                _tourController.Tour.PropertyChanged += Tour_PropertyChanged;

                // Enable the play button.
                _playButton.Enabled = true;

                // Hide the activity indicator.
                _loadingIndicator.StopAnimating();
            }
            catch (Exception e)
            {
                new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show();
            }
        }
        private async void LayerPicker_SelectionChanged(object sender, EventArgs e)
        {
            // Clear existing layers.
            MySceneView.Scene.OperationalLayers.Clear();

            // Get the name of the selected layer.
            string name = _sources[LayerPicker.SelectedIndex];

            try
            {
                // Create the layer using the chosen constructor.
                KmlLayer layer;
                switch (name)
                {
                case "URL":
                default:
                    layer = new KmlLayer(new Uri("https://www.wpc.ncep.noaa.gov/kml/noaa_chart/WPC_Day1_SigWx.kml"));
                    break;

                case "Local file":
                    string filePath = DataManager.GetDataFolder("324e4742820e46cfbe5029ff2c32cb1f", "US_State_Capitals.kml");
                    layer = new KmlLayer(new Uri(filePath));
                    break;

                case "Portal item":
                    ArcGISPortal portal = await ArcGISPortal.CreateAsync();

                    PortalItem item = await PortalItem.CreateAsync(portal, "9fe0b1bfdcd64c83bd77ea0452c76253");

                    layer = new KmlLayer(item);
                    break;
                }

                // Add the selected layer to the map.
                MySceneView.Scene.OperationalLayers.Add(layer);

                // Zoom to the extent of the United States.
                await MySceneView.SetViewpointAsync(new Viewpoint(_usEnvelope));
            }
            catch (Exception ex)
            {
                await((Page)Parent).DisplayAlert("Error", ex.ToString(), "OK");
            }
        }
        private async void DataChoiceButton_Clicked(object sender, PopupMenu.MenuItemClickEventArgs e)
        {
            // Clear existing layers.
            _mySceneView.Scene.OperationalLayers.Clear();

            // Get the name of the selected layer.
            string name = e.Item.TitleCondensedFormatted.ToString();

            try
            {
                // Create the layer using the chosen constructor.
                KmlLayer layer;
                switch (name)
                {
                case "URL":
                default:
                    layer = new KmlLayer(new Uri("https://www.wpc.ncep.noaa.gov/kml/noaa_chart/WPC_Day1_SigWx_latest.kml"));
                    break;

                case "Local file":
                    string filePath = DataManager.GetDataFolder("324e4742820e46cfbe5029ff2c32cb1f", "US_State_Capitals.kml");
                    layer = new KmlLayer(new Uri(filePath));
                    break;

                case "Portal item":
                    ArcGISPortal portal = await ArcGISPortal.CreateAsync();

                    PortalItem item = await PortalItem.CreateAsync(portal, "9fe0b1bfdcd64c83bd77ea0452c76253");

                    layer = new KmlLayer(item);
                    break;
                }

                // Add the selected layer to the map.
                _mySceneView.Scene.OperationalLayers.Add(layer);

                // Zoom to the extent of the United States.
                await _mySceneView.SetViewpointAsync(new Viewpoint(_usEnvelope));
            }
            catch (Exception ex)
            {
                new AlertDialog.Builder(this).SetMessage(ex.ToString()).SetTitle("Error").Show();
            }
        }
Ejemplo n.º 7
0
        private async void MyMapView_Drop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

                KmlLayer kmlLayer = new KmlLayer(new Uri(files[0]));
                await kmlLayer.InitializeAsync();

                //Add the kml layer
                MyMapView.Map.Layers.Add(kmlLayer);

                //Zoom to the kml layer if available
                if (kmlLayer.RootFeature.Viewpoint != null)
                {
                    await MyMapView.SetViewAsync(kmlLayer.RootFeature.Viewpoint);
                }
            }
        }
 private async void DownloadKmlFile(string url)
 {
     await Task.Factory.StartNew(() =>
     {
         using (var Client = new HttpClient())
         {
             var response = Client.GetAsync(url).Result;
             if (response.IsSuccessStatusCode)
             {
                 var kmlLayer = new KmlLayer(googleMap, response.Content.ReadAsStreamAsync().Result, this);
                 this.RunOnUiThread(() =>
                 {
                     kmlLayer.AddLayerToMap();
                     MoveCameraToKml(kmlLayer);
                 });
             }
         }
     }).ConfigureAwait(false);
 }
        public void CloseLayer()
        {
            KmlLayer shapeLayer = myMap.Layers[layerId.ToString()] as KmlLayer;

            if (shapeLayer != null)
            {
                myMap.Layers.Remove(shapeLayer);
            }
            GraphicsLayer dotLayer = myMap.Layers[layerId.ToString() + "_dotLayer"] as GraphicsLayer;

            if (dotLayer != null)
            {
                myMap.Layers.Remove(dotLayer);
            }
            if (LegendStackPanel != null)
            {
                LegendStackPanel.Children.Clear();
            }
        }
Ejemplo n.º 10
0
        private async void Initialize()
        {
            // Add a basemap.
            _mySceneView.Scene = new Scene(Basemap.CreateImageryWithLabels());
            _mySceneView.Scene.BaseSurface.ElevationSources.Add(new ArcGISTiledElevationSource(new Uri("https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")));

            // Get the URL to the data.
            Uri kmlUrl = new Uri(DataManager.GetDataFolder("da301cb122874d5497f8a8f6c81eb36e", "esri_test_data.kmz"));

            // Create the KML dataset and layer.
            KmlDataset dataset = new KmlDataset(kmlUrl);
            KmlLayer   layer   = new KmlLayer(dataset);

            // Add the layer to the map.
            _mySceneView.Scene.OperationalLayers.Add(layer);

            try
            {
                await dataset.LoadAsync();

                // Build the ViewModel from the expanded list of layer infos.
                foreach (KmlNode node in dataset.RootNodes)
                {
                    // LayerDisplayVM is a custom type made for this sample to serve as the ViewModel; it is not a part of ArcGIS Runtime.
                    LayerDisplayVM nodeVm = new LayerDisplayVM(node, null);
                    _viewModelList.Add(nodeVm);
                    LayerDisplayVM.BuildLayerInfoList(nodeVm, _viewModelList);
                }

                // Construct the layer list source.
                _layerListSource = new LayerListSource(_viewModelList, this);

                // Set the source for the table view (layer list).
                _myDisplayList.Source = _layerListSource;

                // Force an update of the list display.
                _myDisplayList.ReloadData();
            }
            catch (Exception e)
            {
                new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show();
            }
        }
        private async void Initialize()
        {
            // Add a basemap.
            _mySceneView.Scene = new Scene(Basemap.CreateImageryWithLabels());
            _mySceneView.Scene.BaseSurface.ElevationSources.Add(new ArcGISTiledElevationSource(new Uri("https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")));

            // Get the URL to the data.
            Uri kmlUrl = new Uri(DataManager.GetDataFolder("da301cb122874d5497f8a8f6c81eb36e", "esri_test_data.kmz"));

            // Create the KML dataset and layer.
            KmlDataset dataset = new KmlDataset(kmlUrl);
            KmlLayer   layer   = new KmlLayer(dataset);

            // Add the layer to the map.
            _mySceneView.Scene.OperationalLayers.Add(layer);

            try
            {
                await dataset.LoadAsync();

                // Build the ViewModel from the expanded list of layer infos.
                foreach (KmlNode node in dataset.RootNodes)
                {
                    // LayerDisplayVM is a custom type made for this sample to serve as the ViewModel; it is not a part of ArcGIS Runtime.
                    LayerDisplayVM nodeVm = new LayerDisplayVM(node, null);
                    _viewModelList.Add(nodeVm);
                    LayerDisplayVM.BuildLayerInfoList(nodeVm, _viewModelList);
                }

                // Create an array adapter for the content display
                ArrayAdapter adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, _viewModelList.Select(item => item.Name).ToList());

                // Apply the adapter
                _myDisplayList.Adapter = adapter;

                // Subscribe to selection change notifications
                _myDisplayList.ItemClick += MyDisplayList_ItemClick;
            }
            catch (Exception e)
            {
                new AlertDialog.Builder(this).SetMessage(e.ToString()).SetTitle("Error").Show();
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Returns the bitmap image brush associated with the icon href for the point feature.
        /// </summary>
        /// <param name="IconHref">Value used to obtain image from remote server via HTTP or key for image dictionary.</param>
        /// <returns>
        /// A bitmap image brush or null if not found.
        /// </returns>
        private ImageBrush GetIconImage(string IconHref)
        {
            Uri imageUri = KmlLayer.GetUri(IconHref, _baseUri);

            // If the imageUri is OK then use it. Otherwise return null
            // so that a SimpleMarkerSymbol is created.
            if (imageUri != null
#if SILVERLIGHT
                && (imageUri.Scheme == "http" || imageUri.Scheme == "https")
#endif
                )
            {
                // Since this is accessing a remote server which may be down or otherwise inaccessible, use
                // exception handling to consume the error and fail quietly, falling through to fallback logic
                // and returning null otherwise.
                try
                {
#if SILVERLIGHT
                    // Create bitmap image, set creation options to None so image creation is not delayed
                    // and use URI to get image.
                    BitmapImage bi = new BitmapImage();
                    bi.SetValue(BitmapImageKeyProperty, IconHref);
                    bi.CreateOptions = BitmapCreateOptions.None;
                    bi.UriSource     = imageUri;
                    return(new ImageBrush {
                        ImageSource = bi
                    });
#else
                    BitmapImage bi = new BitmapImage(imageUri);
                    bi.SetValue(BitmapImageKeyProperty, IconHref);
                    return(new ImageBrush {
                        ImageSource = bi
                    });
#endif
                }
                catch
                {
                }
            }

            return(null);
        }
Ejemplo n.º 13
0
        private async void Initialize()
        {
            // Set up the basemap.
            MyMapView.Map = new Map(Basemap.CreateDarkGrayCanvasVector());

            // Create the dataset.
            KmlDataset dataset = new KmlDataset(new Uri("https://www.wpc.ncep.noaa.gov/kml/noaa_chart/WPC_Day1_SigWx.kml"));

            // Create the layer from the dataset.
            _forecastLayer = new KmlLayer(dataset);

            // Add the layer to the map.
            MyMapView.Map.OperationalLayers.Add(_forecastLayer);

            // Zoom to the extent of the United States.
            await MyMapView.SetViewpointAsync(new Viewpoint(_usEnvelope));

            // Listen for taps to identify features.
            MyMapView.GeoViewTapped += MyMapView_GeoViewTapped;
        }
        private void Initialize()
        {
            // Create a scene for the sceneview.
            Scene myScene = new Scene(Basemap.CreateImagery());

            _mySceneView.Scene = myScene;

            // Create a geometry for the ground overlay.
            Envelope overlayGeometry = new Envelope(-123.066227926904, 44.04736963555683, -123.0796942287304, 44.03878298600624, SpatialReferences.Wgs84);

            // Create a KML Icon for the overlay image.
            KmlIcon overlayImage = new KmlIcon(_imageryUri);

            // Create the KML ground overlay.
            KmlGroundOverlay overlay = new KmlGroundOverlay(overlayGeometry, overlayImage);

            // Set the rotation of the ground overlay.
            overlay.Rotation = -3.046024799346924;

            // Create a KML dataset with the ground overlay as the root node.
            KmlDataset dataset = new KmlDataset(overlay);

            // Create a KML layer for the scene view.
            KmlLayer layer = new KmlLayer(dataset);

            // Add the layer to the map.
            _mySceneView.Scene.OperationalLayers.Add(layer);

            // Move the viewpoint to the ground overlay.
            _mySceneView.SetViewpoint(new Viewpoint(overlay.Geometry, new Camera(overlay.Geometry.Extent.GetCenter(), 1250, 45, 60, 0)));

            // Add an event handler for the on-screen slider.
            _slider.ProgressChanged += (s, e) =>
            {
                // Change the color of the KML ground overlay image to edit the alpha-value. (Other color values are left as-is in the original image.)
                overlay.Color = System.Drawing.Color.FromArgb(e.Progress, 0, 0, 0);

                // Display the value.
                _valueLabel.Text = e.Progress.ToString();
            };
        }
        private async void Initialize()
        {
            // Set up the basemap.
            MySceneView.Scene = new Scene(Basemap.CreateImageryWithLabels());

            // Create the dataset.
            KmlDataset dataset = new KmlDataset(new Uri("https://www.arcgis.com/sharing/rest/content/items/600748d4464442288f6db8a4ba27dc95/data"));

            // Listen for network link control messages.
            // These should be shown to the user.
            dataset.NetworkLinkControlMessage += Dataset_NetworkLinkControlMessage;

            // Create the layer from the dataset.
            KmlLayer fileLayer = new KmlLayer(dataset);

            // Add the layer to the map.
            MySceneView.Scene.OperationalLayers.Add(fileLayer);

            // Zoom in to center the map on Germany.
            await MySceneView.SetViewpointAsync(new Viewpoint(new MapPoint(8.150526, 50.472421, SpatialReferences.Wgs84), 20000000));
        }
        private async void DataChoiceButtonOnValueChanged(object sender, EventArgs e)
        {
            // Clear existing layers.
            _mySceneView.Scene.OperationalLayers.Clear();

            // Get the name of the selected layer.
            string name = _sources[_dataChoiceButton.SelectedSegment];

            // Create the layer using the chosen constructor.
            KmlLayer layer;

            switch (name)
            {
            case "URL":
            default:
                layer = new KmlLayer(new Uri("https://www.wpc.ncep.noaa.gov/kml/noaa_chart/WPC_Day1_SigWx.kml"));
                break;

            case "Local file":
                string filePath = DataManager.GetDataFolder("324e4742820e46cfbe5029ff2c32cb1f", "US_State_Capitals.kml");
                layer = new KmlLayer(new Uri(filePath));
                break;

            case "Portal item":
                ArcGISPortal portal = await ArcGISPortal.CreateAsync();

                PortalItem item = await PortalItem.CreateAsync(portal, "9fe0b1bfdcd64c83bd77ea0452c76253");

                layer = new KmlLayer(item);
                break;
            }

            // Add the selected layer to the map.
            _mySceneView.Scene.OperationalLayers.Add(layer);

            // Zoom to the extent of the United States.
            await _mySceneView.SetViewpointAsync(new Viewpoint(_usEnvelope));
        }
Ejemplo n.º 17
0
        private void ResetKml()
        {
            // Clear any existing layers from the map.
            MyMapView.Map.OperationalLayers.Clear();

            // Reset the most recently placed placemark.
            _currentPlacemark = null;

            // Create a new KML document.
            _kmlDocument = new KmlDocument()
            {
                Name = "KML Sample Document"
            };

            // Create a KML dataset using the KML document.
            _kmlDataset = new KmlDataset(_kmlDocument);

            // Create the KML layer using the KML dataset.
            _kmlLayer = new KmlLayer(_kmlDataset);

            // Add the KML layer to the map.
            MyMapView.Map.OperationalLayers.Add(_kmlLayer);
        }
Ejemplo n.º 18
0
        public void RenderServerImage(string url, int[] visibleLayers)
        {
            this.url = url;

            KmlLayer shapeLayer = myMap.Layers[layerId.ToString()] as KmlLayer;

            if (shapeLayer != null)
            {
                myMap.Layers.Remove(shapeLayer);
            }

            shapeLayer              = new KmlLayer();
            shapeLayer.ID           = layerId.ToString();
            shapeLayer.Url          = new Uri(url);
            shapeLayer.Initialized += new EventHandler <EventArgs>(shapeLayer_Initialized);
            if (visibleLayers != null)
            {
                //shapeLayer.VisibleLayers = visibleLayers;
            }
            myMap.Layers.Add(shapeLayer);

            myMap.Extent = shapeLayer.FullExtent;
        }
        private async void Initialize()
        {
            // Add a basemap.
            MySceneView.Scene = new Scene(Basemap.CreateImageryWithLabels());
            MySceneView.Scene.BaseSurface.ElevationSources.Add(new ArcGISTiledElevationSource(new Uri("https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")));

            // Get the URL to the data.
            Uri kmlUrl = new Uri(DataManager.GetDataFolder("da301cb122874d5497f8a8f6c81eb36e", "esri_test_data.kmz"));

            // Create the KML dataset and layer.
            KmlDataset dataset = new KmlDataset(kmlUrl);
            KmlLayer   layer   = new KmlLayer(dataset);

            // Add the layer to the map.
            MySceneView.Scene.OperationalLayers.Add(layer);

            try
            {
                await dataset.LoadAsync();

                // Build the ViewModel from the expanded list of layer infos.
                foreach (KmlNode node in dataset.RootNodes)
                {
                    // LayerDisplayVM is a custom type made for this sample to serve as the ViewModel; it is not a part of ArcGIS Runtime.
                    LayerDisplayVM nodeVm = new LayerDisplayVM(node, null);
                    _viewModelList.Add(nodeVm);
                    LayerDisplayVM.BuildLayerInfoList(nodeVm, _viewModelList);
                }

                // Update the list of layers, using the root node from the list.
                LayerTreeView.ItemsSource = _viewModelList;
            }
            catch (Exception e)
            {
                await new MessageDialog2(e.ToString(), "Error").ShowAsync();
            }
        }
Ejemplo n.º 20
0
        private async void ViewTapped(object sender, GeoViewInputEventArgs e)
        {
            GeoView  view     = (GeoView)sender;
            KmlLayer kmlLayer = null;

            if (view is SceneView)
            {
                kmlLayer = ((SceneView)sender).Scene.OperationalLayers.OfType <KmlLayer>().FirstOrDefault();
            }
            else if (view is MapView)
            {
                kmlLayer = ((MapView)sender).Map.OperationalLayers.OfType <KmlLayer>().FirstOrDefault();
            }
            if (kmlLayer == null)
            {
                return;
            }
            var result = await view.IdentifyLayerAsync(kmlLayer, e.Position, 2, false);

            var feature = result.GeoElements?.OfType <KmlGeoElement>().FirstOrDefault()?.KmlNode;

            HighlightFeature(feature);
            ShowMapTip(feature, e.Location);
        }
Ejemplo n.º 21
0
 private void DownloadKmlFile(string mUrl)
 {
     try
     {
         Stream @is = new URL(mUrl).OpenStream();
         ByteArrayOutputStream buffer = new ByteArrayOutputStream();
         int    nRead;
         byte[] data = new byte[16384];
         while ((nRead = @is.Read(data, 0, data.Length)) != -1)
         {
             buffer.Write(data, 0, nRead);
         }
         buffer.Flush();
         try
         {
             using (var stream = new MemoryStream(buffer.ToByteArray()))
             {
                 KmlLayer kmlLayer = new KmlLayer(mMap, stream, this);//,
                 //new MarkerManager(mMap),
                 //new PolygonManager(mMap),
                 //new PolylineManager(mMap),
                 //new GroundOverlayManager(mMap),
                 //getImagesCache());
                 addKmlToMap(kmlLayer);
             }
         }
         catch (XmlPullParserException e)
         {
             e.PrintStackTrace();
         }
     }
     catch (Java.IO.IOException e)
     {
         e.PrintStackTrace();
     }
 }
        private void MoveCameraToKml(KmlLayer kmlLayer)
        {
            //Retrieve the first container in the KML layer
            KmlContainer container = kmlLayer.Containers.ToEnumerable <KmlContainer>().FirstOrDefault();

            //Retrieve a nested container within the first container
            container = container.Containers.ToEnumerable <KmlContainer>().FirstOrDefault();
            //Retrieve the first placemark in the nested container
            KmlPlacemark placemark = container.Placemarks.ToEnumerable <KmlPlacemark>().FirstOrDefault();
            //Retrieve a polygon object in a placemark
            KmlPolygon polygon = (KmlPolygon)placemark.Geometry;

            //Create LatLngBounds of the outer coordinates of the polygon
            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            foreach (LatLng latLng in polygon.OuterBoundaryCoordinates)
            {
                builder.Include(latLng);
            }

            int width  = Resources.DisplayMetrics.WidthPixels;
            int height = Resources.DisplayMetrics.HeightPixels;

            googleMap.MoveCamera(CameraUpdateFactory.NewLatLngBounds(builder.Build(), width, height, 1));
        }
Ejemplo n.º 23
0
        protected override void startDemo(bool isRestore)
        {
            if (!isRestore)
            {
                getMap().MoveCamera(CameraUpdateFactory.NewLatLngZoom(new LatLng(51.403186, -0.126446), 10));
            }

            // Shared object managers - used to support multiple layer types on the map simultaneously
            // [START maps_multilayer_demo_init1]
            MarkerManager markerManager = new MarkerManager(getMap());
            //GroundOverlayManager groundOverlayManager = new GroundOverlayManager(getMap());
            //PolygonManager polygonManager = new PolygonManager(getMap());
            //PolylineManager polylineManager = new PolylineManager(getMap());
            // [END maps_multilayer_demo_init1]

            // Add clustering
            // [START maps_multilayer_demo_init2]
            ClusterManager clusterManager = new ClusterManager(this, getMap(), markerManager);

            // [END maps_multilayer_demo_init2]
            getMap().SetOnCameraIdleListener(clusterManager);
            addClusterItems(clusterManager);

            // Add GeoJSON from resource
            try
            {
                var geoJsonOnFeatureClickListener = new GeoJsonOnFeatureClickListener(this);
                // GeoJSON polyline
                // [START maps_multilayer_demo_init3]
                GeoJsonLayer geoJsonLineLayer = new GeoJsonLayer(getMap(), Resource.Raw.south_london_line_geojson, this);//, markerManager, polygonManager, polylineManager, groundOverlayManager);
                // [END maps_multilayer_demo_init3]
                // Make the line red
                GeoJsonLineStringStyle geoJsonLineStringStyle = new GeoJsonLineStringStyle();
                geoJsonLineStringStyle.Color = Color.Red;
                foreach (GeoJsonFeature f in geoJsonLineLayer.Features.ToEnumerable())
                {
                    f.LineStringStyle = geoJsonLineStringStyle;
                }
                geoJsonLineLayer.AddLayerToMap();
                geoJsonLineLayer.SetOnFeatureClickListener(geoJsonOnFeatureClickListener);

                // GeoJSON polygon
                GeoJsonLayer geoJsonPolygonLayer = new GeoJsonLayer(getMap(), Resource.Raw.south_london_square_geojson, this);//, markerManager, polygonManager, polylineManager, groundOverlayManager);
                // Fill it with red
                GeoJsonPolygonStyle geoJsonPolygonStyle = new GeoJsonPolygonStyle();
                geoJsonPolygonStyle.FillColor = Color.Red;
                foreach (GeoJsonFeature f in geoJsonPolygonLayer.Features.ToEnumerable())
                {
                    f.PolygonStyle = geoJsonPolygonStyle;
                }
                geoJsonPolygonLayer.AddLayerToMap();
                geoJsonPolygonLayer.SetOnFeatureClickListener(geoJsonOnFeatureClickListener);
            }
            catch (Java.IO.IOException e)
            {
                Log.Error(TAG, "GeoJSON file could not be read");
            }
            catch (JSONException e)
            {
                Log.Error(TAG, "GeoJSON file could not be converted to a JSONObject");
            }

            // Add KMLs from resources
            try
            {
                var kmlLayerOnFeatureClickListener = new KmlLayerOnFeatureClickListener(this);
                // KML Polyline
                // [START maps_multilayer_demo_init4]
                KmlLayer kmlPolylineLayer = new KmlLayer(getMap(), Resource.Raw.south_london_line_kml, this);//, markerManager, polygonManager, polylineManager, groundOverlayManager, null);
                // [END maps_multilayer_demo_init4]
                // [START maps_multilayer_demo_init6]
                kmlPolylineLayer.AddLayerToMap();
                kmlPolylineLayer.SetOnFeatureClickListener(kmlLayerOnFeatureClickListener);
                // [END maps_multilayer_demo_init6]

                // KML Polygon
                KmlLayer kmlPolygonLayer = new KmlLayer(getMap(), Resource.Raw.south_london_square_kml, this);//, markerManager, polygonManager, polylineManager, groundOverlayManager, null);
                kmlPolygonLayer.AddLayerToMap();
                kmlPolygonLayer.SetOnFeatureClickListener(kmlLayerOnFeatureClickListener);
            }
            catch (XmlPullParserException e)
            {
                e.PrintStackTrace();
            }
            catch (Java.IO.IOException e)
            {
                e.PrintStackTrace();
            }

            // Unclustered marker - instead of adding to the map directly, use the MarkerManager
            // [START maps_multilayer_demo_init5]
            MarkerManager.Collection markerCollection = markerManager.NewCollection();
            markerCollection.AddMarker(new MarkerOptions()
                                       .SetPosition(new LatLng(51.150000, -0.150032))
                                       .SetIcon(BitmapDescriptorFactory.DefaultMarker(BitmapDescriptorFactory.HueAzure))
                                       .SetTitle("Unclustered marker"));
            // [END maps_multilayer_demo_init5]
            // [START maps_multilayer_demo_init7]
            markerCollection.SetOnMarkerClickListener(this);
            // [END maps_multilayer_demo_init7]
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Createsground overlays and adds them to the element layer.
        /// </summary>
        /// <param name="layer">Element layer that will have overlays added to it.</param>
        /// <param name="images">Dictionary of images coming from kmz content or from previous parsing</param>
        /// <param name="map">The map the KML layer belongs to (useful to know the SR) </param>
        public void CreateGroundOverlays(ElementLayer layer, IDictionary <string, ImageBrush> images, Map map)
        {
            if (layer == null)
            {
                return;
            }

            // Process each metadata feature in the list
            foreach (GroundOverlayDescriptor feature in groundOverlays)
            {
                UIElement uiElement;

                if (!String.IsNullOrEmpty(feature.IconHref))
                {
                    ImageSource imageSource;

                    // If the image is provided in kmz content, use it
                    if (images.ContainsKey(feature.IconHref.ToLower()))
                    {
                        imageSource = images[feature.IconHref.ToLower()].ImageSource;
                    }
                    else
                    {
                        // Get the image using the HREF
                        imageSource = new BitmapImage(KmlLayer.GetUri(feature.IconHref, _baseUri));
                    }

                    // If feature color is White with an alpha channel, this can be managed with Opacity, else we need the to blend the color with the icon
                    double opacity;
                    bool   needBlendEffect;

                    if (feature.Color.R == byte.MaxValue && feature.Color.G == byte.MaxValue && feature.Color.B == byte.MaxValue)
                    {
                        opacity         = (double)feature.Color.A / byte.MaxValue;
                        needBlendEffect = false;
                    }
                    else
                    {
                        opacity         = 1.0;
                        needBlendEffect = true;
                    }

                    uiElement = new Image
                    {
                        Source  = imageSource,
                        Stretch = Stretch.Fill,
                        Opacity = opacity
                    };
                    if (needBlendEffect)
                    {
                        uiElement.Effect = new MultiplyBlendEffect {
                            BlendColor = feature.Color
                        };
                    }
                }
                else
                {
                    // Just add a rectangle
                    uiElement = new Rectangle {
                        Fill = new SolidColorBrush(feature.Color)
                    };
                }

                // Set the time extent
                if (feature.TimeExtent != null)
                {
                    ElementLayer.SetTimeExtent(uiElement, feature.TimeExtent);
                }

                // Set the rotation
                if (feature.Rotation != 0.0)
                {
                    uiElement.RenderTransformOrigin = new Point(0.5, 0.5);
                    uiElement.RenderTransform       = new RotateTransform {
                        Angle = -feature.Rotation
                    };                                                                                               // KML rotations are specified in a counterclockwise direction
                }

                // Set the envelope
                var elementLayerEnvelopeProperty = ElementLayer.EnvelopeProperty;
                var envelope = feature.Envelope;

                // If the map is based on WebMercatore coordinates, project the envelope (weird at small scale but acceptable at large scale)
                if (map != null && map.SpatialReference != null && IsWebMercator(map.SpatialReference) &&
                    envelope.SpatialReference != null && envelope.SpatialReference.WKID == 4326)                        // should always be the case
                {
                    envelope = (new Projection.WebMercator()).FromGeographic(envelope) as Envelope;
                }
                uiElement.SetValue(elementLayerEnvelopeProperty, envelope);

                // Add element to element layer
                layer.Children.Add(uiElement);
            }
        }
        void shapeLayer_Initialized(object sender, EventArgs e)
        {
            KmlLayer      shapeLayer    = ArcGIS_Map.Layers[LayerId.ToString()] as KmlLayer;
            GraphicsLayer graphicsLayer = GetGraphicsLayer(shapeLayer);

            if (graphicsLayer != null)
            {
                IDictionary <string, object> coreAttributes = graphicsLayer.Graphics[0].Attributes;
                Dictionary <string, object>  allAttributes  = new Dictionary <string, object>();

                foreach (KeyValuePair <string, object> attr in coreAttributes)
                {
                    allAttributes.Add(attr.Key, attr.Value);
                }

                AddSchemaDataAttributes(_kmlURL, graphicsLayer.Graphics);

                if (graphicsLayer.Graphics[0].Attributes.ContainsKey("extendedData"))
                {
                    List <KmlExtendedData> eds = (List <KmlExtendedData>)graphicsLayer.Graphics[0].Attributes["extendedData"];

                    foreach (KmlExtendedData ed in eds)
                    {
                        allAttributes.Add(ed.Name, ed.Value);
                    }
                }

                if (FeatureLoaded != null)
                {
                    FeatureLoaded(_kmlURL, allAttributes);
                }
            }

            double xmin = graphicsLayer.Graphics[0].Geometry.Extent.XMin;
            double xmax = graphicsLayer.Graphics[0].Geometry.Extent.XMax;
            double ymin = graphicsLayer.Graphics[0].Geometry.Extent.YMin;
            double ymax = graphicsLayer.Graphics[0].Geometry.Extent.YMax;

            foreach (Graphic g in graphicsLayer.Graphics)
            {
                if (g.Geometry.Extent.XMin < xmin)
                {
                    xmin = g.Geometry.Extent.XMin;
                }

                if (g.Geometry.Extent.YMin < ymin)
                {
                    ymin = g.Geometry.Extent.YMin;
                }

                if (g.Geometry.Extent.XMax > xmax)
                {
                    xmax = g.Geometry.Extent.XMax;
                }

                if (g.Geometry.Extent.YMax > ymax)
                {
                    ymax = g.Geometry.Extent.YMax;
                }
            }

            ArcGIS_Map.Extent = new Envelope(
                ESRI.ArcGIS.Client.Bing.Transform.GeographicToWebMercator(new MapPoint(xmin - 0.5, ymax + 0.5)),
                ESRI.ArcGIS.Client.Bing.Transform.GeographicToWebMercator(new MapPoint(xmax + 0.5, ymin - 0.5))
                );
        }
Ejemplo n.º 26
0
 public static string GetVisibleLayerIDs(KmlLayer layer)
 {
     return((string)layer.GetValue(VisibleLayerIDsProperty));
 }
Ejemplo n.º 27
0
        internal void SetKml(KmlLayer kmlLayer, Stream kmlStream, string layerKey)
        {
            AddingKmlItemDelegate addingItemProc = null;

            if (_runtime)
            {
                // TODO: maybe allow non-custom (i.e. report's main) data source here too?
                var layerData = string.IsNullOrEmpty(kmlLayer.ItemFilterExpr) ?
                                null :
                                MakeCustomData(kmlLayer.RecordSource);

                try
                {
                    addingItemProc = delegate(ref string itemName, out Color? stroke, out Color? fill, out bool trackCoords)
                    {
                        stroke      = null;
                        fill        = null;
                        trackCoords = false;

                        DataRowReportScriptContext context = null;
                        if (layerData != null)
                        {
                            try
                            {
                                // quote item name with ' doubling single quotes if any:
                                var filter = s_kmlItemNameRegex.Replace(kmlLayer.ItemFilterExpr,
                                                                        string.Format(CultureInfo.InvariantCulture, "'{0}'", itemName.Replace("'", "''")));
                                DataRow[] res = layerData.Select(filter);
                                if (res.Length > 0)
                                {
                                    context = new DataRowReportScriptContext(res[0]);
                                }
                                else // provide empty (dbnull) context values so that expressions still evaluate to something reasonable:
                                {
                                    context = new DataRowReportScriptContext(layerData.NewRow(), layerData.Columns);
                                }
                            }
                            catch
                            {
                                // eat select errors
                            }
                        }
                        if (context == null)
                        {
                            context = new DataRowReportScriptContext(null, null);
                        }
                        context.AddConstant(KmlLayer.varItemName, itemName);
                        bool itemVisible = Maps.Util.GetBool(ParentReport.Evaluate(kmlLayer.ItemVisibleExpr, context), true);
                        if (itemVisible)
                        {
                            var itemStyle = EvalStyleExpr <KmlItemStyle>(kmlLayer.ItemStyleExpr, KmlItemStyles, ExternalKmlItemStyle, kmlLayer.ItemStyle, context);
                            stroke      = Maps.Util.IsColorEmpty(itemStyle.StrokeColor) ? (Color?)null : itemStyle.StrokeColor;
                            fill        = Maps.Util.IsColorEmpty(itemStyle.FillColor) ? (Color?)null : itemStyle.FillColor;
                            itemName    = string.IsNullOrEmpty(itemStyle.ItemNameExpr) ? itemName : Maps.Util.GetString(ParentReport.Evaluate(itemStyle.ItemNameExpr, context));
                            trackCoords = Maps.Util.GetBool(ParentReport.Evaluate(kmlLayer.ItemTrackExpr, context), true);
                        }
                        return(itemVisible);
                    };
                }
                finally
                {
                    if (layerData != null)
                    {
                        layerData.Dispose();
                    }
                }
            }

            InitMapper();
            _c1mapper.UpdateKmlLayer(layerKey, kmlStream, addingItemProc);
        }
        sealed override public object[] Load(string boundrySourceLocation)
        {
            if (!string.IsNullOrEmpty(boundrySourceLocation))
            {
                _kmlURL = boundrySourceLocation;
                KmlLayer shapeLayer = ArcGIS_Map.Layers[LayerId.ToString()] as KmlLayer;

                if (shapeLayer != null)
                {
                    ArcGIS_Map.Layers.Remove(shapeLayer);
                }

                shapeLayer              = new KmlLayer();
                shapeLayer.ID           = LayerId.ToString();
                shapeLayer.Url          = new Uri(boundrySourceLocation);
                shapeLayer.Initialized += new EventHandler <EventArgs>(shapeLayer_Initialized);
                ArcGIS_Map.Layers.Add(shapeLayer);

                ArcGIS_Map.Extent = shapeLayer.FullExtent;

                //KmlLayer shapeLayer = ArcGIS_Map.Layers[_layerId.ToString()] as KmlLayer;
                GraphicsLayer graphicsLayer = GetGraphicsLayer(shapeLayer);

                if (graphicsLayer != null)
                {
                    IDictionary <string, object> coreAttributes = graphicsLayer.Graphics[0].Attributes;
                    Dictionary <string, object>  allAttributes  = new Dictionary <string, object>();

                    foreach (KeyValuePair <string, object> attr in coreAttributes)
                    {
                        allAttributes.Add(attr.Key, attr.Value);
                    }

                    AddSchemaDataAttributes(_kmlURL, graphicsLayer.Graphics);

                    if (graphicsLayer.Graphics[0].Attributes.ContainsKey("extendedData"))
                    {
                        List <KmlExtendedData> eds = (List <KmlExtendedData>)graphicsLayer.Graphics[0].Attributes["extendedData"];

                        foreach (KmlExtendedData ed in eds)
                        {
                            allAttributes.Add(ed.Name, ed.Value);
                        }
                    }

                    if (FeatureLoaded != null)
                    {
                        FeatureLoaded(_kmlURL, allAttributes);
                    }


                    double xmin = graphicsLayer.Graphics[0].Geometry.Extent.XMin;
                    double xmax = graphicsLayer.Graphics[0].Geometry.Extent.XMax;
                    double ymin = graphicsLayer.Graphics[0].Geometry.Extent.YMin;
                    double ymax = graphicsLayer.Graphics[0].Geometry.Extent.YMax;

                    foreach (Graphic g in graphicsLayer.Graphics)
                    {
                        if (g.Geometry.Extent.XMin < xmin)
                        {
                            xmin = g.Geometry.Extent.XMin;
                        }

                        if (g.Geometry.Extent.YMin < ymin)
                        {
                            ymin = g.Geometry.Extent.YMin;
                        }

                        if (g.Geometry.Extent.XMax > xmax)
                        {
                            xmax = g.Geometry.Extent.XMax;
                        }

                        if (g.Geometry.Extent.YMax > ymax)
                        {
                            ymax = g.Geometry.Extent.YMax;
                        }
                    }

                    ArcGIS_Map.Extent = new Envelope(
                        ESRI.ArcGIS.Client.Bing.Transform.GeographicToWebMercator(new MapPoint(xmin - 0.5, ymax + 0.5)),
                        ESRI.ArcGIS.Client.Bing.Transform.GeographicToWebMercator(new MapPoint(xmax + 0.5, ymin - 0.5))
                        );
                }

                if (graphicsLayer == null)
                {
                    return(new object[] { boundrySourceLocation, null });
                }
                else
                {
                    return(new object[] { boundrySourceLocation, graphicsLayer.Graphics[0].Attributes });
                }
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 29
0
 /// <summary>
 /// This function loads a KML layer to the map. 
 /// </summary>
 /// <param name="path">The path of the .kml file.</param>
 /// <param name="zoomTo">Whether we should zoom to the new area (true) or not (false).</param>
 /// <param name="relativePath">Specifies if the path is relative (true) or absolute (false).</param>
 public void LoadKml(string path, bool zoomTo, bool relativePath)
 {
     Debug.WriteLine("Path: " + path);
     try
     {
         Uri dataPath = new Uri(path, relativePath ? UriKind.Relative : UriKind.Absolute);
         KmlLayer kmllayer = new KmlLayer(dataPath);
         kmllayer.ID = path;
         this.idToZoomOn = zoomTo ? path : string.Empty;
         Map.Layers.Add(kmllayer);
     }
     catch
     {
         Debug.WriteLine(string.Format("(MainWindows{LoadKml}) Could not load KML with path {0}", path));
     }
 }