Example #1
1
      static public void Test(SpatialReference srs)
      {
         string wkt = srs.GetWKT(SpatialReference.WKTModeFlag.eCompoundOK, false);

         // BUG: need to have one to test
         Debug.Assert(wkt == "");

         return;
      }
		private string[] _subDomains; // for being able to access it from a background thread

		/// <summary>
		/// Initializes a new instance of the <see cref="WebTiledLayer"/> class.
		/// </summary>
		public WebTiledLayer()
		{
			//This default layer's spatial reference
			SpatialReference = new SpatialReference(Wkid);
			//Full extent fo the layer
			base.FullExtent = new Envelope(-CornerCoordinate, -CornerCoordinate, CornerCoordinate, CornerCoordinate)
			{
				SpatialReference = SpatialReference
			};
			//Set up tile information. Each tile is 256x256px, 19 levels.
			TileInfo = new TileInfo
			{
				Height = 256,
				Width = 256,
				Origin = new MapPoint(-CornerCoordinate, CornerCoordinate) { SpatialReference = SpatialReference },
				SpatialReference = SpatialReference,
				Lods = new Lod[19]
			};
			//Set the resolutions for each level. Each level is half the resolution of the previous one.
			double resolution = CornerCoordinate * 2 / 256;
			for (int i = 0; i < TileInfo.Lods.Length; i++)
			{
				TileInfo.Lods[i] = new Lod { Resolution = resolution };
				resolution /= 2;
			}
		}
        /// <summary>
        /// Converter for converting a geometry from one projection to another.
        /// The input geometry must have a spatial reference defined, and the converter parameter
        /// must but the Well-Known ID or the Well-Known text for the output spatial reference.
        /// </summary>
        /// <seealso cref="Esri.ArcGISRuntime.Geometry.GeometryEngine"/>

        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value is Esri.ArcGISRuntime.Geometry.Geometry)
            {
                SpatialReference sref = null;
                if (parameter is SpatialReference)
                    sref = (SpatialReference)value;
                else if (parameter is int)
                {
                    sref = new SpatialReference((int)parameter);
                }
                else if (parameter is string)
                {
                    int wkid = -1;
                    if (int.TryParse((string)parameter, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out wkid))
                        sref = new SpatialReference(wkid);
                    else
                        sref = new SpatialReference((string)parameter);
                }
                if (sref != null)
                {
                    var geom = (Esri.ArcGISRuntime.Geometry.Geometry)value;
                    if (geom.Extent!=null&& !double.IsNaN(geom.Extent.XMin))
                        return GeometryEngine.Project(geom, sref);
                }
            }
            return value;
        }
        public void ProjectGraphics(IList<Graphic> graphics, SpatialReference outputSpatialReference, object userState = null)
        {
            if (string.IsNullOrEmpty(GeometryServiceUrl))
                GeometryServiceUrl = FallbackGeometryServer;

            projectGraphicsAsync(GeometryServiceUrl, graphics, outputSpatialReference, geomService_GraphicsProjectCompleted, userState);
        }
    public static void ProjectEnvelopeAsync(Envelope envelope, SpatialReference spatialReference, EventHandler<GeometryEventArgs> callback)
    {
      if (envelope.SpatialReference.WKID == spatialReference.WKID)
      {
        callback(null, new GeometryEventArgs() { Geometry = envelope });
        return;
      }

      if ((envelope.SpatialReference.WKID == WKIDs.WebMercator || envelope.SpatialReference.WKID == WKIDs.WebMercatorAuxiliarySphere) && spatialReference.WKID == WKIDs.Geographic)
      {
        MapPoint p1 = new MapPoint(Math.Max(envelope.XMin, -19977660), Math.Max(envelope.YMin, -43076226));
        MapPoint p2 = new MapPoint(Math.Min(envelope.XMax, 19998531), Math.Min(envelope.YMax, 33656597));
        Envelope output = new Envelope(ESRI.ArcGIS.Client.Bing.Transform.WebMercatorToGeographic(p1),
                                       ESRI.ArcGIS.Client.Bing.Transform.WebMercatorToGeographic(p2));
        output.SpatialReference = spatialReference;
        callback(null, new GeometryEventArgs() { Geometry = output });
        return;
      }
      
      if (envelope.SpatialReference.WKID == WKIDs.Geographic && (spatialReference.WKID == WKIDs.WebMercator || spatialReference.WKID == WKIDs.WebMercatorAuxiliarySphere))
      {
        MapPoint p1 = new MapPoint(envelope.XMin, envelope.YMin);
        MapPoint p2 = new MapPoint(envelope.XMax, envelope.YMax);
        Envelope output = new Envelope(ESRI.ArcGIS.Client.Bing.Transform.GeographicToWebMercator(p1),
                                       ESRI.ArcGIS.Client.Bing.Transform.GeographicToWebMercator(p2));
        output.SpatialReference = spatialReference;
        callback(null, new GeometryEventArgs() { Geometry = output });
        return;
      }

      ProjectAsync(envelope, spatialReference, callback);
    }
Example #6
0
        public dsStaticSubLayer()
        {
            //RenderingMode = GraphicsLayerRenderingMode.Static;
            MouseLeftButtonDown += dsStaticSubLayer_MouseLeftButtonDown;

            //AppState.ViewDef.MapControl.MapGesture += MapControlMapGesture;
            SpatialReference = new SpatialReference(4326);
        }
Example #7
0
        public static Graphic ToGraphic(this string wkt, SpatialReference sourceSpatialReference = null, SpatialReference targetSpatialReference = null)
        {
            if (string.IsNullOrWhiteSpace(wkt) || !wkt.StartsWith("POLYGON ((")) return null;

            const string coordinatePrefix = "POLYGON ((";
            const string coordinateSuffix = "))";

            if (sourceSpatialReference == null)
            {
                sourceSpatialReference = new SpatialReference(4326);
            }

            if (targetSpatialReference == null)
            {
                targetSpatialReference = new SpatialReference(4326);
            }

            var src = ProjectionInfo.FromEpsgCode(sourceSpatialReference.WKID);
            var dest = ProjectionInfo.FromEpsgCode(targetSpatialReference.WKID);
            var sr = targetSpatialReference;

            var strCoordinates = wkt.Substring(coordinatePrefix.Length, wkt.Length - coordinateSuffix.Length - coordinatePrefix.Length);
            var coordinatePairs = strCoordinates.Split(',');
            var coordinates = coordinatePairs.Select(pair =>
            {
                var coordinate = pair.Split(' ');
                if (coordinate.Length != 2) throw new ArgumentException(string.Format("Cannot parse coordinate from WKT: {0}", pair));

                return new {X = float.Parse(coordinate[0], CultureInfo.InvariantCulture), Y = float.Parse(coordinate[1], CultureInfo.InvariantCulture)};
//                return new {X = float.Parse(coordinate[0], CultureInfo.InvariantCulture) + 155000, Y = float.Parse(coordinate[1], CultureInfo.InvariantCulture)+463000};
            });

            var polygon = new Polygon();
            polygon.SpatialReference = sr;
            if (src == dest)
            {
                var pointCollection = new PointCollection(coordinates.Select(c => new MapPoint(c.X, c.Y)));
                polygon.Rings.Add(pointCollection);
            }
            else
            {
                var points = coordinates.SelectMany(c => new double[2] {c.X, c.Y}).ToArray();
                Reproject.ReprojectPoints(points, null, src, dest, 0, points.Length / 2);
                var pointCollection = new PointCollection(Enumerable.Range(0, points.Length / 2).Select(i => new MapPoint(points[i * 2], points[(i * 2) + 1], sr)));
                polygon.Rings.Add(pointCollection);
            }

            var graphic = new Graphic();
            graphic.Geometry = polygon;
            graphic.Symbol = new SimpleFillSymbol
            {
                BorderBrush = new SolidColorBrush(Colors.Black),
                BorderThickness = 4,
                Fill = new SolidColorBrush(Colors.Blue) { Opacity = 0.8f }
            };

            return graphic;
        }
    /// <summary>
    /// Projects a single geometry to the specified spatial reference.
    /// </summary>
    private static void ProjectAsync(Geometry geometry, SpatialReference spatialReference, EventHandler<GeometryEventArgs> callback)
    {
      CallbackHelper helper = new CallbackHelper(callback);

      ESRI.ArcGIS.Client.Tasks.GeometryService geometryService = new ESRI.ArcGIS.Client.Tasks.GeometryService(Url);

      geometryService.ProjectCompleted += helper.geometryService_ProjectCompleted;
      geometryService.ProjectAsync(new List<Graphic>(new Graphic[] { new Graphic() { Geometry = geometry } }), spatialReference);
    }
 protected void WriteSpatialReferenceAsAttribute(string propertyName, SpatialReference sRef)
 {
     if (sRef == null)
         return;
     if (!string.IsNullOrEmpty(sRef.WKT))
         writer.WriteAttributeString(propertyName, sRef.WKT);
     else if (sRef.WKID != default(int))
         writer.WriteAttributeString(propertyName, sRef.WKID.ToString(CultureInfo.InvariantCulture));
 }
Example #10
0
        //private string _url = "http://openflights.svn.sourceforge.net/viewvc/openflights/openflights/data/airports.dat";

        public override void Initialize()
        {
            //ID = "Rain Radar Europe";
            base.Initialize();
            SpatialReference = new SpatialReference(4326);
            RainRadarUpdate = new DispatcherTimer();
            RainRadarUpdate.Interval = new TimeSpan(0, 1, 0);
            RainRadarUpdate.Tick += RainRadarUpdate_Tick;
        }
Example #11
0
        static void CreateIndexes(DataSource OGRDataSource, string MSSQLConnectionString)
        {
            // Create coordinate transformation
            SpatialReference sourceSRS = new SpatialReference("");
            sourceSRS.ImportFromEPSG(4326);
            SpatialReference targetSRS = new SpatialReference("");
            targetSRS.ImportFromEPSG(900913);
            CoordinateTransformation transform = new CoordinateTransformation(sourceSRS, targetSRS);

            for (int iLayer = 0; iLayer < OGRDataSource.GetLayerCount(); iLayer++)
            {
                Layer OGRLayer = OGRDataSource.GetLayerByIndex(iLayer);
                string layerName = OGRLayer.GetName();

                // Get extent in EPSG:900913
                Envelope extent = new Envelope();
                OGRLayer.GetExtent(extent,0);
                double[] ll = new double[] { extent.MinX, extent.MinY };
                double[] ur = new double[] { extent.MaxX, extent.MaxY };
                transform.TransformPoint(ll);
                transform.TransformPoint(ur);

                using (SqlConnection con = new SqlConnection(MSSQLConnectionString))
                {
                    con.Open();
                    try
                    {
                        // Create primary key/clustered index
                        string pkSQL = string.Format("ALTER TABLE [{0}] ADD CONSTRAINT [PK_{0}] PRIMARY KEY CLUSTERED([id] ASC)  WITH (SORT_IN_TEMPDB = ON);", layerName);
                        using (SqlCommand pkCmd = new SqlCommand(pkSQL, con))
                        {
                            log(TraceLevel.Info, string.Format("Creating clustured index pk_{0} on table {0}...", layerName));
                            pkCmd.CommandTimeout = 0;
                            pkCmd.ExecuteNonQuery();
                        }

                        // Create spatial index
                        OGRLayer.GetExtent(extent, 0);
                        string sidxSQL = string.Format("CREATE SPATIAL INDEX sidx_{0}_ogr_geometry ON [{0}](ogr_geometry) WITH (BOUNDING_BOX = ( {1}, {2}, {3}, {4} ), SORT_IN_TEMPDB = ON );", layerName, ll[0], ll[1], ur[0], ur[1]);
                        using (SqlCommand sidxCmd = new SqlCommand(sidxSQL, con))
                        {
                            log(TraceLevel.Info, string.Format("Creating spatial index sidx_{0}_ogr_geometry on table {0}...", layerName));
                            sidxCmd.CommandTimeout = 0;
                            sidxCmd.ExecuteNonQuery();
                        }
                    }
                    catch (Exception e)
                    {
                        log(TraceLevel.Error, e.Message);
                        Environment.Exit(1);
                    }
                }
            }
        }
		private Envelope _projectedEnvelope; // last projected envelope

		public void GetRegionAsync(SpatialReference spatialReference, IProjectionService projectionService, Action<Envelope> callback)
		{
			Envelope region = null;
			if (spatialReference != null && Envelope != null)
			{
				if (spatialReference.Equals(Envelope.SpatialReference))
					region = Envelope;
				else if (_projectedEnvelope != null && spatialReference.Equals(_projectedEnvelope.SpatialReference))
					region = _projectedEnvelope;
				
				if (region == null && projectionService != null)
				{
					EventHandler<Tasks.GraphicsEventArgs> handler = null;
					if (projectionService.IsBusy)
					{
						// ProjectionService is busy --> Wait for the end of the current projection and retry
						handler = (s, e) =>
						{
							projectionService.ProjectCompleted -= handler;
							GetRegionAsync(spatialReference, projectionService, callback);
						};
						projectionService.ProjectCompleted += handler;
					}
					else
					{
						// Project the envelope asynchronously
						handler = (s, e) =>
						          	{
						          		projectionService.ProjectCompleted -= handler;
						          		if (e.Results.Any())
						          		{
						          			var envelope = e.Results.First().Geometry.Extent;
						          			// Check the SR since the projection service can return the geometry unchanged
						          			_projectedEnvelope = envelope != null && spatialReference.Equals(envelope.SpatialReference)
						          			                     	? envelope
						          			                     	: null;
						          			callback(_projectedEnvelope);
						          		}
						          		else
						          		{
						          			callback(null);
						          		}
						          	};

						projectionService.ProjectCompleted += handler;
						Graphic g = new Graphic {Geometry = Envelope};
						projectionService.ProjectAsync(new [] { g }, spatialReference);
					}
					return;
				}
			}
			callback(region);
		}
 private BufferParameters CreateBufferParameters(SpatialReference spRef, double Distance, LinearUnit Unit)
 {
   BufferParameters bufferParameters = new BufferParameters()
   {
     Unit = Unit,
     BufferSpatialReference = spRef,
     OutSpatialReference = spRef,
     UnionResults = false, //We want a separate buffer for each SourceFeatures, so UnionResults = false
   };
   bufferParameters.Distances.AddRange(new List<double> { Distance });
   bufferParameters.Features.AddRange(SourceFeatures);
   return bufferParameters;
 }
Example #14
0
        public override void Initialize()
        {
            ID = "Airports";
            base.Initialize();
            SpatialReference = new SpatialReference(4326);
            DownloadAirports();
            this.Clusterer = new FlareClusterer()
                                 {
                                     MaximumFlareCount = 5,
                                     FlareBackground = Brushes.Blue,
                                     FlareForeground = Brushes.White
                                 };

        }
        private async void Close_OnClick(object sender, RoutedEventArgs e) {

            if (((Button)sender).Name == "OK" &&_vm.SelectedCoordSystemInfo != null) {
                //assign the Spatial Reference
                await QueuedTask.Run(() => {
                    try {
                        _sr = SpatialReferenceBuilder.CreateSpatialReference(_vm.SelectedCoordSystemInfo.WKID);
                    }
                    catch (Exception ex) {
                        System.Diagnostics.Debug.WriteLine(ex.ToString());
                    }
                });
            }
            Close();
        }
Example #16
0
        public override void Initialize()
        {
            if (LayerFile == null || !File.Exists(LayerFile)) return;
            var fileInfo = new FileInfo(LayerFile);
            if (fileInfo.Directory != null) ID = fileInfo.Directory.Name;

            Graphics = new GraphicsLayer();
            ChildLayers.Add(Graphics);
            Graphics.Initialize();

            ID = "Presenter Layer";
            base.Initialize();
            SpatialReference = new SpatialReference(4326);
            ChildLayers.Insert(0, el);
            UpdateLayer();
        }
        public void ProjectExtent(Envelope envelope, SpatialReference outputSpatialReference, object userState = null)
        {
            if (outputSpatialReference == null)
                throw new ArgumentNullException("outputSpatialReference");
            if (outputSpatialReference.Equals(envelope.SpatialReference))
            {
                OnProjectExtentCompleted(new ProjectExtentCompletedEventArgs() { Extent = envelope });
                return;
            }

            // Use client side transform (if possible)
            if (Geographic.Equals(envelope.SpatialReference) 
                && (WebMercator.Equals(outputSpatialReference) 
                || WebMercatorAuxillarySphere.Equals(outputSpatialReference) 
                || RevisedWebMercatorAuxSphere.Equals(outputSpatialReference)))
            {
                MapPoint p1 = new MapPoint(envelope.XMin, envelope.YMin);
                MapPoint p2 = new MapPoint(envelope.XMax, envelope.YMax);
                Envelope output = new Envelope(Transform.GeographicToWebMercator(p1),
                                               Transform.GeographicToWebMercator(p2));
                output.SpatialReference = outputSpatialReference;
                OnProjectExtentCompleted(new ProjectExtentCompletedEventArgs() { Extent = output });
                return;
            }
            else if (Geographic.Equals(outputSpatialReference) 
                && (WebMercator.Equals(envelope.SpatialReference) 
                || WebMercatorAuxillarySphere.Equals(envelope.SpatialReference) 
                || RevisedWebMercatorAuxSphere.Equals(envelope.SpatialReference)))
            {
                MapPoint p1 = new MapPoint(envelope.XMin, envelope.YMin);
                MapPoint p2 = new MapPoint(envelope.XMax, envelope.YMax);
                Envelope output = new Envelope(Transform.WebMercatorToGeographic(p1),
                                               Transform.WebMercatorToGeographic(p2));
                output.SpatialReference = outputSpatialReference;
                OnProjectExtentCompleted(new ProjectExtentCompletedEventArgs() { Extent = output });
                return;
            }

            if (string.IsNullOrEmpty(GeometryServiceUrl))
                GeometryServiceUrl = FallbackGeometryServer;

            List<Graphic> graphics = new List<Graphic>(1);
            graphics.Add(new Graphic() { Geometry = envelope});
            projectGraphicsAsync(GeometryServiceUrl, graphics, outputSpatialReference, geomService_ExtentProjectCompleted, userState);
        }
Example #18
0
        public override void Initialize()
        {
            //Full extent fo the layer
            FullExtent = new Envelope(-cornerCoordinate, -cornerCoordinate, cornerCoordinate, cornerCoordinate)
            {
                SpatialReference = new SpatialReference(WKID)
            };
            SpatialReference = new SpatialReference(WKID);
            TileInfo = new TileInfo
            {
                Height = 256,
                Width = 256,
                Origin = new MapPoint(-cornerCoordinate, cornerCoordinate) { SpatialReference = new SpatialReference(WKID) },
                Lods = new Lod[19]
            };

            var resolution = cornerCoordinate * 2 / 256;
            for (var i = 0; i < TileInfo.Lods.Length; i++)
            {
                TileInfo.Lods[i] = new Lod { Resolution = resolution };
                resolution /= 2;
            }
            base.Initialize();
        }
Example #19
0
 /// <summary>
 /// Projects the specified geometry.
 /// </summary>
 /// <param name="geometry">The geometry.</param>
 /// <param name="outSpatialReference">The out spatial reference.</param>
 /// <returns></returns>
 private static Geometry.Geometry Project(Geometry.Geometry geometry, SpatialReference outSpatialReference)
 {
     var toMercator = outSpatialReference.WKID != 4326;
     if (geometry != null && geometry.SpatialReference != null &&
         !geometry.SpatialReference.Equals(outSpatialReference))
     {
         Projection.WebMercator projector = new Projection.WebMercator();
         if (toMercator && geometry.SpatialReference.WKID == 4326)
             //Data is 4326 and must projected to webmercator
             return projector.FromGeographic(geometry);
         if (!toMercator && MercatorSref.Equals(geometry.SpatialReference))
             //Data is in webmercator and must be projected to 4326
             return projector.ToGeographic(geometry);
     }
     // Other cases : geometry without SR, geometry already in the right SR, unsupported SR -> return the input geometry
     return geometry;
 }
        // Raised when a property of the map changes.  Used to check whether map units have changed.
        private void Map_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            Map map = ((Map)sender);

            if (map.SpatialReference.WKID != _spatialRefWKID)
            {
                _gotMapUnits = false;
                _spatialRefWKID = map.SpatialReference.WKID;

                // Spatial reference has changed, so determine map units
                if (map.Layers.Count > 0)
                {
                    map.GetMapUnitsAsync(OnGetMapUnitsCompleted, OnGetMapUnitsFailed);
                }
                else
                {
                    NotifyCollectionChangedEventHandler collectionChanged = null;
                    collectionChanged = (o, args) =>
                    {
                        if (map.Layers.Count > 0)
                        {
                            map.Layers.CollectionChanged -= collectionChanged;
                            map.GetMapUnitsAsync(OnGetMapUnitsCompleted, OnGetMapUnitsFailed);
                        }
                    };
                    map.Layers.CollectionChanged += collectionChanged;
                }

                // handle case where map's spatial reference has changed while there are results.  Projection
                // of results will need to be changed to match that of the map.
                if (_results.Count > 0)                
                {
                    SpatialReference oldSRef = new SpatialReference(_spatialRefWKID);
                    if (oldSRef.IsWebMercator() && map.SpatialReference.IsGeographic())
                    {
                        // Transform result extents from Web Mercator to Geographic WGS 84
                        WebMercator mercator = new WebMercator();
                        foreach (LocatorResultViewModel result in _results)
                        {
                            result.Extent = (Envelope)mercator.ToGeographic(result.Extent);
                            AddressCandidate oldCandidate = result.Candidate;
                            MapPoint newLocation = (MapPoint)mercator.ToGeographic(result.Candidate.Location);
                            result.Candidate = new AddressCandidate(oldCandidate.Address, newLocation,
                                oldCandidate.Score, oldCandidate.Attributes);
                        }
                    }
                    else if (oldSRef.IsGeographic() && map.SpatialReference.IsWebMercator())
                    {
                        // Transform result exstents from Geographic WGS 84 to Web Mercator
                        WebMercator mercator = new WebMercator();
                        foreach (LocatorResultViewModel result in _results)
                        {
                            result.Extent = (Envelope)mercator.FromGeographic(result.Extent);
                            AddressCandidate oldCandidate = result.Candidate;
                            MapPoint newLocation = (MapPoint)mercator.FromGeographic(result.Candidate.Location);
                            result.Candidate = new AddressCandidate(oldCandidate.Address, newLocation,
                                oldCandidate.Score, oldCandidate.Attributes);
                        }
                    }
                    else if (!string.IsNullOrEmpty(GeometryServiceUrl))
                    {
                        // Use a geometry service to project the result extents                        

                        List<LocatorResultViewModel> resultsToProject = new List<LocatorResultViewModel>();
                        List<Graphic> extentsToProject = new List<Graphic>();
                        List<Graphic> locationsToProject = new List<Graphic>();
                        foreach (LocatorResultViewModel result in _results)
                        {
                            // Copy the results to a new collection (list) - necessary because the results
                            // could change during the project operation, so maintaining these in a separate
                            // collection ensures that the updated extents are applied to the proper results
                            resultsToProject.Add(result);
                            // Get the geometries to project.  Both extent and candidate location must be re-projected.
                            extentsToProject.Add(new Graphic() { Geometry = result.Extent });
                            locationsToProject.Add(new Graphic() { Geometry = result.Candidate.Location });
                        }

                        GeometryService geomService = new GeometryService(GeometryServiceUrl);
                        GeometryService geomService2 = new GeometryService(GeometryServiceUrl);
                        EventHandler<GraphicsEventArgs> projectExtentsCompleted = null;
                        EventHandler<GraphicsEventArgs> projectLocationsCompleted = null;
                        EventHandler<TaskFailedEventArgs> projectFailed = null;

                        // Update the result extents when the projection completes
                        projectExtentsCompleted = (o, args) =>
                        {
                            geomService.ProjectCompleted -= projectExtentsCompleted;
                            geomService.Failed -= projectFailed;

                            int count = args.Results.Count;
                            for (int i = 0; i < count; i++)
                                resultsToProject[i].Extent = (Envelope)args.Results[i].Geometry;
                        };

                        // Update the result locations when the projection completes
                        projectLocationsCompleted = (o, args) =>
                        {
                            geomService2.ProjectCompleted -= projectLocationsCompleted;
                            geomService2.Failed -= projectFailed;

                            int count = args.Results.Count;
                            LocatorResultViewModel result = null;
                            for (int i = 0; i < count; i++)
                            {
                                result = resultsToProject[i];
                                AddressCandidate oldCandidate = result.Candidate;
                                MapPoint newLocation = (MapPoint)args.Results[i].Geometry;
                                result.Candidate = new AddressCandidate(oldCandidate.Address, newLocation,
                                    oldCandidate.Score, oldCandidate.Attributes);
                            }
                        };

                        // Just clear the results and remove handlers if the projection fails
                        projectFailed = (o, args) =>
                        {
                            geomService.ProjectCompleted -= projectExtentsCompleted;
                            geomService.Failed -= projectFailed;

                            geomService2.ProjectCompleted -= projectLocationsCompleted;
                            geomService2.Failed -= projectFailed;

                            _results.Clear();
                        };

                        geomService.ProjectCompleted += projectExtentsCompleted;
                        geomService.Failed += projectFailed;

                        geomService2.ProjectCompleted += projectLocationsCompleted;
                        geomService2.Failed += projectFailed;

                        geomService.ProjectAsync(extentsToProject, map.SpatialReference);
                        geomService2.ProjectAsync(locationsToProject, map.SpatialReference);
                    }
                }
            }
        }
Example #21
0
 private static void ProjectGroundOverlays(ElementLayer layer, SpatialReference sref)
 {
     var proj = new Projection.WebMercator();
     var webMercatorSR = new SpatialReference(102100);
     var wgs84SR = new SpatialReference(4326);
     foreach (UIElement elt in layer.Children)
     {
         var envelope = elt.GetValue(ElementLayer.EnvelopeProperty) as Envelope;
         if (envelope != null)
         {
             if (webMercatorSR.Equals(envelope.SpatialReference) && wgs84SR.Equals(sref))
             {
                 var env = proj.ToGeographic(envelope) as Envelope;
                 elt.SetValue(ElementLayer.EnvelopeProperty, env);
             }
             else if (wgs84SR.Equals(envelope.SpatialReference) && webMercatorSR.Equals(sref))
             {
                 var env = proj.FromGeographic(envelope) as Envelope;
                 elt.SetValue(ElementLayer.EnvelopeProperty, env);
             }
         }
     }
 }
Example #22
0
    public static void Main(string[] args)
    {
        if (args.Length != 1)
        {
            usage();
        }

        Console.WriteLine("");

        try
        {
            /* -------------------------------------------------------------------- */
            /*      Register driver(s).                                             */
            /* -------------------------------------------------------------------- */
            Gdal.AllRegister();

            /* -------------------------------------------------------------------- */
            /*      Open dataset.                                                   */
            /* -------------------------------------------------------------------- */
            Dataset ds = Gdal.Open(args[0], Access.GA_ReadOnly);

            if (ds == null)
            {
                Console.WriteLine("Can't open " + args[0]);
                System.Environment.Exit(-1);
            }

            Console.WriteLine("Raster dataset parameters:");
            Console.WriteLine("  Projection: " + ds.GetProjectionRef());
            Console.WriteLine("  RasterCount: " + ds.RasterCount);
            Console.WriteLine("  RasterSize (" + ds.RasterXSize + "," + ds.RasterYSize + ")");

            /* -------------------------------------------------------------------- */
            /*      Get driver                                                      */
            /* -------------------------------------------------------------------- */
            Driver drv = ds.GetDriver();

            if (drv == null)
            {
                Console.WriteLine("Can't get driver.");
                System.Environment.Exit(-1);
            }

            Console.WriteLine("Using driver " + drv.LongName);

            /* -------------------------------------------------------------------- */
            /*      Get metadata                                                    */
            /* -------------------------------------------------------------------- */
            string[] metadata = ds.GetMetadata("");
            if (metadata.Length > 0)
            {
                Console.WriteLine("  Metadata:");
                for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                {
                    Console.WriteLine("    " + iMeta + ":  " + metadata[iMeta]);
                }
                Console.WriteLine("");
            }

            /* -------------------------------------------------------------------- */
            /*      Report "IMAGE_STRUCTURE" metadata.                              */
            /* -------------------------------------------------------------------- */
            metadata = ds.GetMetadata("IMAGE_STRUCTURE");
            if (metadata.Length > 0)
            {
                Console.WriteLine("  Image Structure Metadata:");
                for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                {
                    Console.WriteLine("    " + iMeta + ":  " + metadata[iMeta]);
                }
                Console.WriteLine("");
            }

            /* -------------------------------------------------------------------- */
            /*      Report subdatasets.                                             */
            /* -------------------------------------------------------------------- */
            metadata = ds.GetMetadata("SUBDATASETS");
            if (metadata.Length > 0)
            {
                Console.WriteLine("  Subdatasets:");
                for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                {
                    Console.WriteLine("    " + iMeta + ":  " + metadata[iMeta]);
                }
                Console.WriteLine("");
            }

            /* -------------------------------------------------------------------- */
            /*      Report geolocation.                                             */
            /* -------------------------------------------------------------------- */
            metadata = ds.GetMetadata("GEOLOCATION");
            if (metadata.Length > 0)
            {
                Console.WriteLine("  Geolocation:");
                for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                {
                    Console.WriteLine("    " + iMeta + ":  " + metadata[iMeta]);
                }
                Console.WriteLine("");
            }

            /* -------------------------------------------------------------------- */
            /*      Report corners.                                                 */
            /* -------------------------------------------------------------------- */
            Console.WriteLine("Corner Coordinates:");
            Console.WriteLine("  Upper Left (" + GDALInfoGetPosition(ds, 0.0, 0.0) + ")");
            Console.WriteLine("  Lower Left (" + GDALInfoGetPosition(ds, 0.0, ds.RasterYSize) + ")");
            Console.WriteLine("  Upper Right (" + GDALInfoGetPosition(ds, ds.RasterXSize, 0.0) + ")");
            Console.WriteLine("  Lower Right (" + GDALInfoGetPosition(ds, ds.RasterXSize, ds.RasterYSize) + ")");
            Console.WriteLine("  Center (" + GDALInfoGetPosition(ds, ds.RasterXSize / 2, ds.RasterYSize / 2) + ")");
            Console.WriteLine("");

            /* -------------------------------------------------------------------- */
            /*      Report projection.                                              */
            /* -------------------------------------------------------------------- */
            string projection = ds.GetProjectionRef();
            if (projection != null)
            {
                SpatialReference srs = new SpatialReference(null);
                if (srs.ImportFromWkt(ref projection) == 0)
                {
                    string wkt;
                    srs.ExportToPrettyWkt(out wkt, 0);
                    Console.WriteLine("Coordinate System is:");
                    Console.WriteLine(wkt);
                }
                else
                {
                    Console.WriteLine("Coordinate System is:");
                    Console.WriteLine(projection);
                }
            }

            /* -------------------------------------------------------------------- */
            /*      Report GCPs.                                                    */
            /* -------------------------------------------------------------------- */
            if (ds.GetGCPCount( ) > 0)
            {
                Console.WriteLine("GCP Projection: ", ds.GetGCPProjection());
                GCP[] GCPs = ds.GetGCPs();
                for (int i = 0; i < ds.GetGCPCount(); i++)
                {
                    Console.WriteLine("GCP[" + i + "]: Id=" + GCPs[i].Id + ", Info=" + GCPs[i].Info);
                    Console.WriteLine("          (" + GCPs[i].GCPPixel + "," + GCPs[i].GCPLine + ") -> ("
                                      + GCPs[i].GCPX + "," + GCPs[i].GCPY + "," + GCPs[i].GCPZ + ")");
                    Console.WriteLine("");
                }
                Console.WriteLine("");

                double[] transform = new double[6];
                Gdal.GCPsToGeoTransform(GCPs, transform, 0);
                Console.WriteLine("GCP Equivalent geotransformation parameters: ", ds.GetGCPProjection());
                for (int i = 0; i < 6; i++)
                {
                    Console.WriteLine("t[" + i + "] = " + transform[i].ToString());
                }
                Console.WriteLine("");
            }

            /* -------------------------------------------------------------------- */
            /*      Get raster band                                                 */
            /* -------------------------------------------------------------------- */
            for (int iBand = 1; iBand <= ds.RasterCount; iBand++)
            {
                Band band = ds.GetRasterBand(iBand);
                Console.WriteLine("Band " + iBand + " :");
                Console.WriteLine("   DataType: " + Gdal.GetDataTypeName(band.DataType));
                Console.WriteLine("   ColorInterpretation: " + Gdal.GetColorInterpretationName(band.GetRasterColorInterpretation()));
                ColorTable ct = band.GetRasterColorTable();
                if (ct != null)
                {
                    Console.WriteLine("   Band has a color table with " + ct.GetCount() + " entries.");
                }

                Console.WriteLine("   Description: " + band.GetDescription());
                Console.WriteLine("   Size (" + band.XSize + "," + band.YSize + ")");
                int BlockXSize, BlockYSize;
                band.GetBlockSize(out BlockXSize, out BlockYSize);
                Console.WriteLine("   BlockSize (" + BlockXSize + "," + BlockYSize + ")");
                double val;
                int    hasval;
                band.GetMinimum(out val, out hasval);
                if (hasval != 0)
                {
                    Console.WriteLine("   Minimum: " + val.ToString());
                }
                band.GetMaximum(out val, out hasval);
                if (hasval != 0)
                {
                    Console.WriteLine("   Maximum: " + val.ToString());
                }
                band.GetNoDataValue(out val, out hasval);
                if (hasval != 0)
                {
                    Console.WriteLine("   NoDataValue: " + val.ToString());
                }
                band.GetOffset(out val, out hasval);
                if (hasval != 0)
                {
                    Console.WriteLine("   Offset: " + val.ToString());
                }
                band.GetScale(out val, out hasval);
                if (hasval != 0)
                {
                    Console.WriteLine("   Scale: " + val.ToString());
                }

                for (int iOver = 0; iOver < band.GetOverviewCount(); iOver++)
                {
                    Band over = band.GetOverview(iOver);
                    Console.WriteLine("      OverView " + iOver + " :");
                    Console.WriteLine("         DataType: " + over.DataType);
                    Console.WriteLine("         Size (" + over.XSize + "," + over.YSize + ")");
                    Console.WriteLine("         PaletteInterp: " + over.GetRasterColorInterpretation().ToString());
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Application error: " + e.Message);
        }
    }
Example #23
0
        public void Request(IServiceRequestContext context)
        {
            if (context == null || context.ServiceRequest == null)
            {
                return;
            }

            if (_mapServer == null)
            {
                return;
            }

            MiscParameterDescriptor parameters = new MiscParameterDescriptor();

            if (!parameters.ParseParameters(context.ServiceRequest.Request.Split('&')))
            {
                _mapServer.Log("Invalid Parameters", loggingMethod.error, context.ServiceRequest.Request);
                return;
            }

            using (IServiceMap map = context.ServiceMap) // _mapServer[context];
            {
                if (map == null)
                {
                    _mapServer.Log("Invalid Map", loggingMethod.error, context.ServiceRequest.Request);
                    return;
                }

                QueryFilter filter = parameters.BBOX != null ? new SpatialFilter() : new QueryFilter();
                filter.SubFields = "*";
                if (parameters.BBOX != null)
                {
                    ((SpatialFilter)filter).Geometry = parameters.BBOX;
                }
                if (!String.IsNullOrEmpty(parameters.SRS))
                {
                    ISpatialReference sRef = SpatialReference.FromID(parameters.SRS);
                    filter.FeatureSpatialReference = sRef;
                    if (filter is SpatialFilter)
                    {
                        ((SpatialFilter)filter).FilterSpatialReference = sRef;
                    }
                }
                // Get Layers
                List <ILayer> queryLayers = new List <ILayer>();
                foreach (string l in parameters.LAYERS)
                {
                    if (l == String.Empty || l[0] != 'c')
                    {
                        continue;
                    }

                    MapServerHelper.Layers layers = MapServerHelper.FindMapLayers(map, _useTOC, l.Substring(1, l.Length - 1));
                    if (layers == null)
                    {
                        continue;
                    }

                    foreach (ILayer layer in layers)
                    {
                        queryLayers.Add(layer);
                    }
                }

                StringBuilder sb = new StringBuilder();
                sb.Append("{'type':'FeatureCollection','features':[");
                foreach (ILayer layer in queryLayers)
                {
                    if (layer is IFeatureLayer && ((IFeatureLayer)layer).FeatureClass != null)
                    {
                        using (IFeatureCursor cursor = ((IFeatureLayer)layer).FeatureClass.Search(filter) as IFeatureCursor)
                        {
                            string json = gView.Framework.OGC.GeoJson.GeoJson.ToGeoJsonFeatures(cursor, parameters.MaxFeatures);
                            sb.Append(json);
                        }
                    }
                }
                sb.Append("]}");

                context.ServiceRequest.Response = sb.ToString();
            }
        }
Example #24
0
        public DynamicLayersInXAML()
        {
            this.InitializeComponent();

            MyMapView.Map.InitialViewpoint = new Viewpoint(new Envelope(-3170138, -1823795, 2850785, 1766663, SpatialReference.Create(102009)));

            (MyMapView.Map.Layers["USA"] as ArcGISDynamicMapServiceLayer).VisibleLayers = new System.Collections.ObjectModel.ObservableCollection <int> {
                0, 2, 4
            };
        }
Example #25
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList <Curve>(0, boundary);

            string IMG_file = string.Empty;

            DA.GetData <string>(1, ref IMG_file);

            RESTful.GdalConfiguration.ConfigureGdal();
            OSGeo.GDAL.Gdal.AllRegister();

            Dataset datasource = Gdal.Open(IMG_file, Access.GA_ReadOnly);

            OSGeo.GDAL.Driver drv = datasource.GetDriver();


            if (datasource == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The vector datasource was unreadable by this component. It may not a valid file type for this component or otherwise null/empty.");
                return;
            }

            ///Get info about image
            string        srcInfo     = string.Empty;
            List <string> infoOptions = new List <string> {
                "-stats"
            };

            srcInfo = Gdal.GDALInfo(datasource, new GDALInfoOptions(infoOptions.ToArray()));


            ///Get the spatial reference of the input raster file and set to WGS84 if not known
            ///Set up transform from source to WGS84
            OSGeo.OSR.SpatialReference sr = new SpatialReference(Osr.SRS_WKT_WGS84);
            if (datasource.GetProjection() == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Coordinate Reference System (CRS) is missing.  CRS set automatically set to WGS84.");
            }

            else
            {
                sr = new SpatialReference(datasource.GetProjection());

                if (sr.Validate() != 0)
                {
                    ///Check if SRS needs to be converted from ESRI format to WKT to avoid error:
                    ///"No translation for Lambert_Conformal_Conic to PROJ.4 format is known."
                    ///https://gis.stackexchange.com/questions/128266/qgis-error-6-no-translation-for-lambert-conformal-conic-to-proj-4-format-is-kn
                    SpatialReference srEsri = sr;
                    srEsri.MorphFromESRI();
                    string projEsri = string.Empty;
                    srEsri.ExportToWkt(out projEsri);

                    ///If no SRS exists, check Ground Control Points SRS
                    SpatialReference srGCP   = new SpatialReference(datasource.GetGCPProjection());
                    string           projGCP = string.Empty;
                    srGCP.ExportToWkt(out projGCP);

                    if (!string.IsNullOrEmpty(projEsri))
                    {
                        datasource.SetProjection(projEsri);
                        sr = srEsri;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) morphed form ESRI format.");
                    }
                    else if (!string.IsNullOrEmpty(projGCP))
                    {
                        datasource.SetProjection(projGCP);
                        sr = srGCP;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) set from Ground Control Points (GCPs).");
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) is unknown or unsupported.  SRS assumed to be WGS84." +
                                          "Try setting the SRS with the GdalWarp component using -t_srs EPSG:4326 for the option input.");
                        sr.SetWellKnownGeogCS("WGS84");
                    }
                }

                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Data source SRS: EPSG:" + sr.GetAttrValue("AUTHORITY", 1));
                }
            }

            //OSGeo.OSR.SpatialReference sr = new SpatialReference(ds.GetProjection());
            OSGeo.OSR.SpatialReference dst = new OSGeo.OSR.SpatialReference("");
            dst.SetWellKnownGeogCS("WGS84");
            OSGeo.OSR.CoordinateTransformation coordTransform = new OSGeo.OSR.CoordinateTransformation(sr, dst);
            OSGeo.OSR.CoordinateTransformation revTransform   = new OSGeo.OSR.CoordinateTransformation(dst, sr);

            double[] adfGeoTransform = new double[6];
            double[] invTransform    = new double[6];
            datasource.GetGeoTransform(adfGeoTransform);
            Gdal.InvGeoTransform(adfGeoTransform, invTransform);

            int width  = datasource.RasterXSize;
            int height = datasource.RasterYSize;

            ///Dataset bounding box
            double oX = adfGeoTransform[0] + adfGeoTransform[1] * 0 + adfGeoTransform[2] * 0;
            double oY = adfGeoTransform[3] + adfGeoTransform[4] * 0 + adfGeoTransform[5] * 0;
            double eX = adfGeoTransform[0] + adfGeoTransform[1] * width + adfGeoTransform[2] * height;
            double eY = adfGeoTransform[3] + adfGeoTransform[4] * width + adfGeoTransform[5] * height;

            ///Transform to WGS84
            double[] extMinPT = new double[3] {
                oX, eY, 0
            };
            double[] extMaxPT = new double[3] {
                eX, oY, 0
            };
            coordTransform.TransformPoint(extMinPT);
            coordTransform.TransformPoint(extMaxPT);
            Point3d dsMin = new Point3d(extMinPT[0], extMinPT[1], extMinPT[2]);
            Point3d dsMax = new Point3d(extMaxPT[0], extMaxPT[1], extMaxPT[2]);

            Rectangle3d dsbox = new Rectangle3d(Plane.WorldXY, Heron.Convert.WGSToXYZ(dsMin), Heron.Convert.WGSToXYZ(dsMax));

            double pixelWidth  = dsbox.Width / width;
            double pixelHeight = dsbox.Height / height;

            ///Declare trees
            GH_Structure <GH_Point>   pointcloud = new GH_Structure <GH_Point>();
            GH_Structure <GH_Integer> rCount     = new GH_Structure <GH_Integer>();
            GH_Structure <GH_Integer> cCount     = new GH_Structure <GH_Integer>();
            GH_Structure <GH_Mesh>    tMesh      = new GH_Structure <GH_Mesh>();

            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path = new GH_Path(i);

                Curve clippingBoundary = boundary[i];

                if (!clip)
                {
                    clippingBoundary = dsbox.ToNurbsCurve();
                }

                string clippedTopoFile = "/vsimem/topoclipped.tif";

                if (!(dsbox.BoundingBox.Contains(clippingBoundary.GetBoundingBox(true).Min) && (dsbox.BoundingBox.Contains(clippingBoundary.GetBoundingBox(true).Max))) && clip)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more boundaries may be outside the bounds of the topo dataset.");
                }

                ///Offsets to mesh/boundary based on pixel size
                Point3d clipperMinPreAdd  = clippingBoundary.GetBoundingBox(true).Corner(true, false, true);
                Point3d clipperMinPostAdd = new Point3d(clipperMinPreAdd.X, clipperMinPreAdd.Y, clipperMinPreAdd.Z);
                Point3d clipperMin        = Heron.Convert.XYZToWGS(clipperMinPostAdd);

                Point3d clipperMaxPreAdd = clippingBoundary.GetBoundingBox(true).Corner(false, true, true);
                ///add/subtract pixel width if desired to get closer to boundary
                //Point3d clipperMaxPostAdd = new Point3d(clipperMaxPreAdd.X + pixelWidth, clipperMaxPreAdd.Y - pixelHeight, clipperMaxPreAdd.Z);
                Point3d clipperMaxPostAdd = new Point3d(clipperMaxPreAdd.X, clipperMaxPreAdd.Y, clipperMaxPreAdd.Z);
                Point3d clipperMax        = Heron.Convert.XYZToWGS(clipperMaxPostAdd);

                double lonWest  = clipperMin.X;
                double lonEast  = clipperMax.X;
                double latNorth = clipperMin.Y;
                double latSouth = clipperMax.Y;

                var translateOptions = new[]
                {
                    "-of", "GTiff",
                    "-a_nodata", "0",
                    "-projwin_srs", "WGS84",
                    "-projwin", $"{lonWest}", $"{latNorth}", $"{lonEast}", $"{latSouth}"
                };

                using (Dataset clippedDataset = Gdal.wrapper_GDALTranslate(clippedTopoFile, datasource, new GDALTranslateOptions(translateOptions), null, null))
                {
                    Band band = clippedDataset.GetRasterBand(1);
                    width  = clippedDataset.RasterXSize;
                    height = clippedDataset.RasterYSize;
                    clippedDataset.GetGeoTransform(adfGeoTransform);
                    Gdal.InvGeoTransform(adfGeoTransform, invTransform);

                    rCount.Append(new GH_Integer(height), path);
                    cCount.Append(new GH_Integer(width), path);
                    Mesh           mesh  = new Mesh();
                    List <Point3d> verts = new List <Point3d>();
                    //var vertsParallel = new System.Collections.Concurrent.ConcurrentDictionary<double[][], Point3d>(Environment.ProcessorCount, ((Urow - 1) * (Lrow - 1)));

                    double[] bits = new double[width * height];
                    band.ReadRaster(0, 0, width, height, bits, width, height, 0, 0);

                    for (int col = 0; col < width; col++)
                    {
                        for (int row = 0; row < height; row++)
                        {
                            // equivalent to bits[col][row] if bits is 2-dimension array
                            double pixel = bits[col + row * width];
                            if (pixel < -10000)
                            {
                                pixel = 0;
                            }

                            double gcol = adfGeoTransform[0] + adfGeoTransform[1] * col + adfGeoTransform[2] * row;
                            double grow = adfGeoTransform[3] + adfGeoTransform[4] * col + adfGeoTransform[5] * row;

                            ///convert to WGS84
                            double[] wgsPT = new double[3] {
                                gcol, grow, pixel
                            };
                            coordTransform.TransformPoint(wgsPT);
                            Point3d pt = new Point3d(wgsPT[0], wgsPT[1], wgsPT[2]);

                            verts.Add(Heron.Convert.WGSToXYZ(pt));
                        }

                        /*Parallel.For(Urow, Lrow - 1, rowP =>
                         *  {
                         *      // equivalent to bits[col][row] if bits is 2-dimension array
                         *      double pixel = bits[col + rowP * width];
                         *      if (pixel < -10000)
                         *      {
                         *          pixel = 0;
                         *      }
                         *
                         *      double gcol = adfGeoTransform[0] + adfGeoTransform[1] * col + adfGeoTransform[2] * rowP;
                         *      double grow = adfGeoTransform[3] + adfGeoTransform[4] * col + adfGeoTransform[5] * rowP;
                         *
                         *      Point3d pt = new Point3d(gcol, grow, pixel);
                         *      vertsParallel[] = Heron.Convert.ToXYZ(pt);
                         *  });
                         * */
                    }

                    //Create meshes
                    //non Parallel
                    mesh.Vertices.AddVertices(verts);
                    //Parallel
                    //mesh.Vertices.AddVertices(vertsParallel.Values);

                    for (int u = 1; u < cCount[path][0].Value; u++)
                    {
                        for (int v = 1; v < rCount[path][0].Value; v++)
                        {
                            mesh.Faces.AddFace(v - 1 + (u - 1) * (height), v - 1 + u * (height), v - 1 + u * (height) + 1, v - 1 + (u - 1) * (height) + 1);
                            //(k - 1 + (j - 1) * num2, k - 1 + j * num2, k - 1 + j * num2 + 1, k - 1 + (j - 1) * num2 + 1)
                        }
                    }

                    //mesh.Flip(true, true, true);
                    tMesh.Append(new GH_Mesh(mesh), path);

                    band.Dispose();
                }
                Gdal.Unlink("/vsimem/topoclipped.tif");
            }
            DA.SetDataTree(0, tMesh);
            DA.SetData(1, dsbox);
            DA.SetData(2, srcInfo);
        }
        void findNearbyToolWindow_FindNearby(object sender, FindNearbyEventArgs e)
        {
            if (Layer == null)
            {
                return;
            }

            GraphicsLayer graphicsLayer = Layer as GraphicsLayer;

            if (graphicsLayer == null)
            {
                return;
            }

            if (graphicsLayer.SelectionCount < 1)
            {
                findNearbyToolWindow.StopBusyIndicator();
                MessageBoxDialog.Show(Resources.Strings.MsgNoFeaturesSelected, Resources.Strings.ErrorCaption, MessageBoxButton.OK);
                return;
            }

            BufferParameters bufferParams = new BufferParameters();

            switch (e.LinearUnit)
            {
            case LinearUnit.Miles:
                bufferParams.Unit = ESRI.ArcGIS.Client.Tasks.LinearUnit.StatuteMile;
                break;

            case LinearUnit.Meters:
                bufferParams.Unit = ESRI.ArcGIS.Client.Tasks.LinearUnit.Meter;
                break;

            case LinearUnit.Kilometers:
                bufferParams.Unit = ESRI.ArcGIS.Client.Tasks.LinearUnit.Kilometer;
                break;
            }
            bufferParams.UnionResults        = true;
            bufferParams.OutSpatialReference = Map.SpatialReference;
            SpatialReference gcs = new SpatialReference(4326);

            bufferParams.BufferSpatialReference = gcs;
            bufferParams.Geodesic = true;
            bufferParams.Distances.Add(e.Distance);

            // Check the spatial reference of the first graphic
            Graphic firstGraphic = graphicsLayer.SelectedGraphics.ElementAt(0);
            bool    isInGcs      = firstGraphic.Geometry != null &&
                                   firstGraphic.Geometry.SpatialReference != null &&
                                   firstGraphic.Geometry.SpatialReference.Equals(gcs);

            // In order to perform geodesic buffering we need to pass geometries in GCS to the geom service
            if (isInGcs)
            {
                foreach (Graphic selectedGraphic in graphicsLayer.SelectedGraphics)
                {
                    bufferParams.Features.Add(selectedGraphic);
                }

                buffer(GeometryServiceUrl, bufferParams, e);
            }
            else
            {
                GeometryServiceOperationHelper helper = new GeometryServiceOperationHelper(GeometryServiceUrl);
                helper.ProjectGraphicsCompleted += (o, args) => {
                    foreach (Graphic selectedGraphic in args.Graphics)
                    {
                        bufferParams.Features.Add(selectedGraphic);
                    }
                    buffer(GeometryServiceUrl, bufferParams, e);
                };
                helper.ProjectGraphics(graphicsLayer.SelectedGraphics.ToList(), new SpatialReference(4326));
            }
        }
 public static Geometry FromWellKnownBinary(this byte[] data, SpatialReference spatialReference = null)
 {
     return(new WkbConverter().Read(data, spatialReference));
 }
 /// <summary>
 /// Gets whether a spatial reference instance is in a Web Mercator projection
 /// </summary>
 /// <param name="sref"></param>
 /// <returns></returns>
 internal static bool IsWebMercator(this SpatialReference sref)
 {
     return(sref != null && sref.WKID == 3857 || sref.WKID == 102113 || sref.WKID == 102100);
 }
        private Geometry GetExtentOfGraphicsOverlay(GraphicsOverlay inputGraphicsOverlay, double expansionFactor, SpatialReference spatialReferenceType)
        {
            // Get all of the graphics contained in the graphics overlay.
            GraphicCollection inputGraphicCollection = inputGraphicsOverlay.Graphics;

            // Create a new envelope builder using the same spatial reference as the graphics.
            EnvelopeBuilder unionEnvelopeBuilder = new EnvelopeBuilder(spatialReferenceType);

            // Loop through each graphic in the graphic collection.
            foreach (Graphic oneGraphic in inputGraphicCollection)
            {
                // Union the extent of each graphic in the envelope builder.
                unionEnvelopeBuilder.UnionOf(oneGraphic.Geometry.Extent);
            }

            // Expand the envelope builder by the expansion factor.
            unionEnvelopeBuilder.Expand(expansionFactor);

            // Return the unioned extent plus the expansion factor.
            return(unionEnvelopeBuilder.Extent);
        }
Example #30
0
        public FeatureClassV3(Dataset dataset, string name)
        {
            _dataset = dataset;
            _name    = name;

            using (var dataSource = OSGeo_v3.OGR.Ogr.Open(_dataset.ConnectionString, 0))
                using (var ogrLayer = dataSource.GetLayerByName(_name))
                {
                    OSGeo_v3.OGR.FeatureDefn defn = ogrLayer.GetLayerDefn();
                    _name = defn.GetName();
                    if (dataset.ConnectionString.ToLower().EndsWith(".dxf"))
                    {
                        try
                        {
                            System.IO.FileInfo fi = new System.IO.FileInfo(dataset.ConnectionString);
                            _name = fi.Name;
                        }
                        catch { }
                    }
                    _fields = new Fields();
                    for (int i = 0; i < defn.GetFieldCount(); i++)
                    {
                        OSGeo_v3.OGR.FieldDefn fdefn = defn.GetFieldDefn(i);
                        Field field = new Field(fdefn.GetName());

                        switch (fdefn.GetFieldTypeName(fdefn.GetFieldType()).ToLower())
                        {
                        case "integer":
                            if (_idFieldName == String.Empty)
                            {
                                _idFieldName = field.name;
                            }

                            field.type = FieldType.integer;
                            break;

                        case "real":
                            field.type = FieldType.Double;
                            break;

                        case "string":
                            field.type = FieldType.String;
                            field.size = fdefn.GetWidth();
                            break;
                        }
                        _fields.Add(field);
                    }

                    using (var spatialRef = defn.GetGeomFieldDefn(0)?.GetSpatialRef())
                    {
                        if (spatialRef != null)
                        {
                            string proj4;
                            spatialRef.ExportToProj4(out proj4);
                            if (!String.IsNullOrEmpty(proj4))
                            {
                                var sRef = new SpatialReference(spatialRef.GetName());
                                sRef.Parameters = proj4.Split(' ');

                                this.SpatialReference = sRef;
                            }
                        }
                    }

                    _countFeatures = ogrLayer.GetFeatureCount(1);
                    OSGeo_v3.OGR.Envelope env = new OSGeo_v3.OGR.Envelope();
                    ogrLayer.GetExtent(env, 1);
                    _envelope = new Envelope(env.MinX, env.MinY, env.MaxX, env.MaxY);

                    switch (defn.GetGeomType())
                    {
                    case OSGeo_v3.OGR.wkbGeometryType.wkbPoint:
                        _geomType = geometryType.Point;
                        break;

                    case OSGeo_v3.OGR.wkbGeometryType.wkbLineString:
                    case OSGeo_v3.OGR.wkbGeometryType.wkbMultiLineString:
                        _geomType = geometryType.Polyline;
                        break;

                    case OSGeo_v3.OGR.wkbGeometryType.wkbPolygon:
                    case OSGeo_v3.OGR.wkbGeometryType.wkbMultiPolygon:
                        _geomType = geometryType.Polygon;
                        break;
                    }
                }
        }
Example #31
0
        private void Initialize()
        {
            // Create a spatial reference that's suitable for creating planar buffers in north central Texas (State Plane).
            SpatialReference statePlaneNorthCentralTexas = new SpatialReference(32038);

            // Define a polygon that represents the valid area of use for the spatial reference.
            // This information is available at https://developers.arcgis.com/net/latest/wpf/guide/pdf/projected_coordinate_systems_rt100_3_0.pdf
            List <MapPoint> spatialReferenceExtentCoords = new List <MapPoint>
            {
                new MapPoint(-103.070, 31.720, SpatialReferences.Wgs84),
                new MapPoint(-103.070, 34.580, SpatialReferences.Wgs84),
                new MapPoint(-94.000, 34.580, SpatialReferences.Wgs84),
                new MapPoint(-94.00, 31.720, SpatialReferences.Wgs84)
            };

            _spatialReferenceArea = new Polygon(spatialReferenceExtentCoords);
            _spatialReferenceArea = GeometryEngine.Project(_spatialReferenceArea, statePlaneNorthCentralTexas) as Polygon;

            // Create a map that uses the North Central Texas state plane spatial reference.
            Map bufferMap = new Map(statePlaneNorthCentralTexas);

            // Add some base layers (counties, cities, and highways).
            Uri usaLayerSource           = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/USA/MapServer");
            ArcGISMapImageLayer usaLayer = new ArcGISMapImageLayer(usaLayerSource);

            bufferMap.Basemap.BaseLayers.Add(usaLayer);

            // Use a new EnvelopeBuilder to expand the spatial reference extent 120%.
            EnvelopeBuilder envBuilder = new EnvelopeBuilder(_spatialReferenceArea.Extent);

            envBuilder.Expand(1.2);

            // Set the map's initial extent to the expanded envelope.
            Envelope startingEnvelope = envBuilder.ToGeometry();

            bufferMap.InitialViewpoint = new Viewpoint(startingEnvelope);

            // Assign the map to the MapView.
            MyMapView.Map = bufferMap;

            // Create a graphics overlay to show the buffer polygon graphics.
            GraphicsOverlay bufferGraphicsOverlay = new GraphicsOverlay
            {
                // Give the overlay an ID so it can be found later.
                Id = "buffers"
            };

            // Create a graphic to show the spatial reference's valid extent (envelope) with a dashed red line.
            SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, Color.Red, 5);
            Graphic          spatialReferenceExtentGraphic = new Graphic(_spatialReferenceArea, lineSymbol);

            // Add the graphic to a new overlay.
            GraphicsOverlay spatialReferenceGraphicsOverlay = new GraphicsOverlay();

            spatialReferenceGraphicsOverlay.Graphics.Add(spatialReferenceExtentGraphic);

            // Add the graphics overlays to the MapView.
            MyMapView.GraphicsOverlays.Add(bufferGraphicsOverlay);
            MyMapView.GraphicsOverlays.Add(spatialReferenceGraphicsOverlay);

            // Wire up the MapView's GeoViewTapped event handler.
            MyMapView.GeoViewTapped += MyMapView_GeoViewTapped;
        }
Example #32
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            ///Gather GHA inputs
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList <Curve>("Boundary", boundary);

            string shpFileLoc = "";

            DA.GetData <string>("Vector Data Location", ref shpFileLoc);


            bool cropIt = true;

            DA.GetData <Boolean>("Crop file", ref cropIt);

            string userSRStext = "WGS84";

            DA.GetData <string>(2, ref userSRStext);


            ///GDAL setup
            ///Some preliminary testing has been done to read SHP, GeoJSON, OSM, KML, MVT, GML and GDB
            ///It can be spotty with KML, MVT and GML and doesn't throw informative errors.  Likely has to do with getting a valid CRS and
            ///TODO: resolve errors with reading KML, MVT, GML.

            RESTful.GdalConfiguration.ConfigureOgr();
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver     drv = OSGeo.OGR.Ogr.GetDriverByName("ESRI Shapefile");
            OSGeo.OGR.DataSource ds  = OSGeo.OGR.Ogr.Open(shpFileLoc, 0);

            if (ds == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The vector datasource was unreadable by this component. It may not a valid file type for this component or otherwise null/empty.");
                return;
            }

            List <OSGeo.OGR.Layer> layerset = new List <OSGeo.OGR.Layer>();
            List <int>             fc       = new List <int>();

            for (int iLayer = 0; iLayer < ds.GetLayerCount(); iLayer++)
            {
                OSGeo.OGR.Layer layer = ds.GetLayerByIndex(iLayer);

                if (layer == null)
                {
                    Console.WriteLine("Couldn't fetch advertised layer " + iLayer);
                    System.Environment.Exit(-1);
                }
                else
                {
                    layerset.Add(layer);
                }
            }

            ///Declare trees
            GH_Structure <GH_String>    layname = new GH_Structure <GH_String>();
            GH_Structure <GH_Integer>   fcs     = new GH_Structure <GH_Integer>();
            GH_Structure <GH_Rectangle> recs    = new GH_Structure <GH_Rectangle>();
            GH_Structure <GH_String>    sRefs   = new GH_Structure <GH_String>();
            GH_Structure <GH_String>    fnames  = new GH_Structure <GH_String>();
            GH_Structure <GH_String>    fset    = new GH_Structure <GH_String>();
            GH_Structure <GH_Point>     gset    = new GH_Structure <GH_Point>();

            GH_Structure <GH_Point>     gsetUser = new GH_Structure <GH_Point>();
            GH_Structure <GH_Rectangle> recsUser = new GH_Structure <GH_Rectangle>();


            ///Loop through each layer. Layers usually occur in Geodatabase GDB format. SHP usually has only one layer.
            for (int iLayer = 0; iLayer < ds.GetLayerCount(); iLayer++)
            {
                OSGeo.OGR.Layer layer = ds.GetLayerByIndex(iLayer);

                if (layer == null)
                {
                    Console.WriteLine("Couldn't fetch advertised layer " + iLayer);
                    System.Environment.Exit(-1);
                }

                long count        = layer.GetFeatureCount(1);
                int  featureCount = System.Convert.ToInt32(count);
                fcs.Append(new GH_Integer(featureCount), new GH_Path(iLayer));

                layname.Append(new GH_String(layer.GetName()), new GH_Path(iLayer));


                ///Get the spatial reference of the input vector file and set to WGS84 if not known
                OSGeo.OSR.SpatialReference sourceSRS = new SpatialReference(Osr.SRS_WKT_WGS84);
                string sRef = "";

                if (layer.GetSpatialRef() == null)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Coordinate Reference System (CRS) is missing.  CRS set automatically set to WGS84. Mapbox to 3857");
                    //sr.ImportFromXML(shpFileLoc);
                    //sr.ImportFromEPSG(3857);
                    //sr.SetWellKnownGeogCS("EPSG:3857");
                    sourceSRS.SetFromUserInput("WGS84"); ///this seems to work where SetWellKnownGeogCS doesn't

                    string pretty = "";
                    sourceSRS.ExportToPrettyWkt(out pretty, 0);
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, pretty);
                    //sr.SetWellKnownGeogCS("WGS84");
                    //sr.SetWellKnownGeogCS("EPSG:3857");
                    sRef = "Coordinate Reference System (CRS) is missing.  CRS set automatically set to WGS84.";
                }
                else
                {
                    if (layer.GetSpatialRef().Validate() != 0)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Coordinate Reference System (CRS) is unknown or unsupported.  CRS set automatically set to WGS84.");
                        sourceSRS.SetWellKnownGeogCS("WGS84");
                        sRef = "Coordinate Reference System (CRS) is unknown or unsupported.  SRS set automatically set to WGS84.";
                    }
                    else
                    {
                        sourceSRS = layer.GetSpatialRef();
                        sourceSRS.ExportToWkt(out sRef);
                        try
                        {
                            int sourceSRSInt = Int16.Parse(sourceSRS.GetAuthorityCode(null));
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Source Coordinate Reference System (CRS) from layer " + layer.GetName() + " is EPSG:" + sourceSRSInt + ".");
                        }
                        catch
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Failed to get Source Coordinate Reference System (CRS) from layer " + layer.GetName() + ".");
                        }
                    }
                }

                sRefs.Append(new GH_String(sRef), new GH_Path(iLayer));


                ///Set transform from input spatial reference to Rhino spatial reference
                ///TODO: look into adding a step for transforming to CRS set in SetCRS
                OSGeo.OSR.SpatialReference rhinoSRS = new OSGeo.OSR.SpatialReference("");
                rhinoSRS.SetWellKnownGeogCS("WGS84");

                ///TODO: verify the userSRS is valid
                ///TODO: use this as override of global SetSRS
                OSGeo.OSR.SpatialReference userSRS = new OSGeo.OSR.SpatialReference("");
                userSRS.SetFromUserInput(userSRStext);

                ///This transform moves and scales the points required in going from userSRS to XYZ and vice versa
                Transform userSRSToModel = Heron.Convert.GetUserSRSToModelTransform(userSRS);
                Transform modelToUserSRS = Heron.Convert.GetModelToUserSRSTransform(userSRS);

                OSGeo.OSR.CoordinateTransformation coordTransformSourceToRhino = new OSGeo.OSR.CoordinateTransformation(sourceSRS, rhinoSRS);
                OSGeo.OSR.CoordinateTransformation coordTransformRhinoToUser   = new OSGeo.OSR.CoordinateTransformation(rhinoSRS, userSRS);
                OSGeo.OSR.CoordinateTransformation coordTransformSourceToUser  = new OSGeo.OSR.CoordinateTransformation(sourceSRS, userSRS);

                OSGeo.OSR.CoordinateTransformation revTransformUserToRhino   = new OSGeo.OSR.CoordinateTransformation(userSRS, rhinoSRS);
                OSGeo.OSR.CoordinateTransformation revTransformRhinoToSource = new OSGeo.OSR.CoordinateTransformation(rhinoSRS, sourceSRS);
                OSGeo.OSR.CoordinateTransformation revTransformUserToSource  = new OSGeo.OSR.CoordinateTransformation(userSRS, sourceSRS);

                ///Get OGR envelope of the data in the layer in the sourceSRS
                OSGeo.OGR.Envelope ext = new OSGeo.OGR.Envelope();
                layer.GetExtent(ext, 1);
                Point3d extMinSource = new Point3d();
                Point3d extMaxSource = new Point3d();
                extMinSource.X = ext.MinX;
                extMinSource.Y = ext.MinY;
                extMaxSource.X = ext.MaxX;
                extMaxSource.Y = ext.MaxY;

                ///Get bounding box of data in layer for coordinate transformation in Rhino SRS
                double[] extMinPT = new double[3] {
                    extMinSource.X, extMinSource.Y, extMinSource.Z
                };
                double[] extMaxPT = new double[3] {
                    extMaxSource.X, extMaxSource.Y, extMaxSource.Z
                };

                ///Transform corners of extents from Source to Rhino SRS
                coordTransformSourceToRhino.TransformPoint(extMinPT);
                coordTransformSourceToRhino.TransformPoint(extMaxPT);

                ///Get extents in Rhino SRS
                Point3d     extPTmin = new Point3d(extMinPT[0], extMinPT[1], extMinPT[2]);
                Point3d     extPTmax = new Point3d(extMaxPT[0], extMaxPT[1], extMaxPT[2]);
                Rectangle3d rec      = new Rectangle3d(Plane.WorldXY, Heron.Convert.WGSToXYZ(extPTmin), Heron.Convert.WGSToXYZ(extPTmax));
                recs.Append(new GH_Rectangle(rec), new GH_Path(iLayer));

                if (boundary.Count == 0 && cropIt == true)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Define a boundary or set cropIt to False");
                }

                else if (boundary.Count == 0 && cropIt == false)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Clipping boundary has not been defined. File extents will be used instead");
                    boundary.Add(rec.ToNurbsCurve());
                }

                ///Get bounding box of data in layer for coordinate transformation in User SRS
                ///TODO: currently the extents are showing odd results that don't seem to be shifting properly
                double[] extMinPTUser = new double[3] {
                    extMinSource.X, extMinSource.Y, extMinSource.Z
                };
                double[] extMaxPTUser = new double[3] {
                    extMaxSource.X, extMaxSource.Y, extMaxSource.Z
                };

                ///Transform corners of extents from Source to userSRS
                coordTransformSourceToUser.TransformPoint(extMinPTUser);
                coordTransformSourceToUser.TransformPoint(extMaxPTUser);

                ///Get extents in userSRS
                Point3d     extPTminUser = new Point3d(extMinPTUser[0], extMinPTUser[1], extMinPTUser[2]);
                Point3d     extPTmaxUser = new Point3d(extMaxPTUser[0], extMaxPTUser[1], extMaxPTUser[2]);
                Rectangle3d recUser      = new Rectangle3d(Plane.WorldXY, Heron.Convert.UserSRSToXYZ(extPTminUser, userSRSToModel), Heron.Convert.UserSRSToXYZ(extPTmaxUser, userSRSToModel));
                recsUser.Append(new GH_Rectangle(recUser), new GH_Path(iLayer));


                ///Loop through input boundaries
                for (int i = 0; i < boundary.Count; i++)
                {
                    OSGeo.OGR.FeatureDefn def = layer.GetLayerDefn();

                    ///Get the field names
                    List <string> fieldnames = new List <string>();
                    for (int iAttr = 0; iAttr < def.GetFieldCount(); iAttr++)
                    {
                        OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iAttr);
                        fnames.Append(new GH_String(fdef.GetNameRef()), new GH_Path(i, iLayer));
                    }

                    ///Check if boundary is contained in extent
                    if (!rec.IsValid || ((rec.Height == 0) && (rec.Width == 0)))
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more vector datasource bounds are not valid.");
                        OSGeo.OGR.Feature feat;
                        int m = 0;

                        while ((feat = layer.GetNextFeature()) != null)
                        {
                            ///Loop through field values
                            for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                            {
                                OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m));
                                fdef.Dispose();
                            }
                            m++;
                            feat.Dispose();
                        }
                    }


                    else if (boundary[i] == null)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Clipping boundary " + i + " not set.");
                    }

                    else if (!boundary[i].IsValid)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Clipping boundary " + i + "  is not valid.");
                    }

                    else if (rec.IsValid && Curve.PlanarClosedCurveRelationship(rec.ToNurbsCurve(), boundary[i], Plane.WorldXY, Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance) == RegionContainment.Disjoint)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more boundaries may be outside the bounds of the vector datasource.");
                    }

                    else
                    {
                        ///Create bounding box for clipping geometry
                        Point3d  min   = Heron.Convert.XYZToWGS(boundary[i].GetBoundingBox(true).Min);
                        Point3d  max   = Heron.Convert.XYZToWGS(boundary[i].GetBoundingBox(true).Max);
                        double[] minpT = new double[3];
                        double[] maxpT = new double[3];

                        minpT[0] = min.X;
                        minpT[1] = min.Y;
                        minpT[2] = min.Z;
                        maxpT[0] = max.X;
                        maxpT[1] = max.Y;
                        maxpT[2] = max.Z;

                        revTransformRhinoToSource.TransformPoint(minpT);
                        revTransformRhinoToSource.TransformPoint(maxpT);

                        ///TODO: allow boundary to be converted to userSRS
                        //revTransformUserToRhino.TransformPoint(minpT);
                        //revTransformUserToRhino.TransformPoint(maxpT);

                        ///Convert to OGR geometry
                        ///TODO: add conversion from GH geometry to OGR to Convert class
                        OSGeo.OGR.Geometry ebbox = OSGeo.OGR.Geometry.CreateFromWkt("POLYGON((" + minpT[0] + " " + minpT[1] + ", " + minpT[0] + " " + maxpT[1] + ", " + maxpT[0] + " " + maxpT[1] + ", " + maxpT[0] + " " + minpT[1] + ", " + minpT[0] + " " + minpT[1] + "))");

                        ///Clip Shapefile
                        ///http://pcjericks.github.io/py-gdalogr-cookbook/vector_layers.html
                        ///TODO: allow for polyline/curve as clipper, not just bounding box
                        OSGeo.OGR.Layer clipped_layer = layer;

                        if (cropIt)
                        {
                            clipped_layer.SetSpatialFilter(ebbox);
                        }

                        ///Loop through geometry
                        OSGeo.OGR.Feature feat;
                        def = clipped_layer.GetLayerDefn();

                        int m = 0;
                        while ((feat = clipped_layer.GetNextFeature()) != null)
                        {
                            OSGeo.OGR.Geometry geom = feat.GetGeometryRef();
                            OSGeo.OGR.Geometry sub_geom;

                            OSGeo.OGR.Geometry geomUser = feat.GetGeometryRef().Clone();// geom.Clone();
                            OSGeo.OGR.Geometry sub_geomUser;

                            ///reproject geometry to WGS84
                            ///TODO: look into using the SetCRS global variable here
                            geom.Transform(coordTransformSourceToRhino);

                            geomUser.Transform(coordTransformSourceToUser);

                            if (feat.GetGeometryRef() != null)
                            {
                                ///Start get points if open polylines and points
                                for (int gpc = 0; gpc < geom.GetPointCount(); gpc++)
                                {
                                    ///Loop through geometry points for Rhino SRS
                                    double[] pT = new double[3];
                                    pT[0] = geom.GetX(gpc);
                                    pT[1] = geom.GetY(gpc);
                                    pT[2] = geom.GetZ(gpc);
                                    if (Double.IsNaN(geom.GetZ(gpc)))
                                    {
                                        pT[2] = 0;
                                    }

                                    Point3d pt3D = new Point3d();
                                    pt3D.X = pT[0];
                                    pt3D.Y = pT[1];
                                    pt3D.Z = pT[2];

                                    gset.Append(new GH_Point(Heron.Convert.WGSToXYZ(pt3D)), new GH_Path(i, iLayer, m));

                                    ///Loop through geometry points for User SRS
                                    double[] pTUser = new double[3];
                                    pTUser[0] = geomUser.GetX(gpc);
                                    pTUser[1] = geomUser.GetY(gpc);
                                    pTUser[2] = geomUser.GetZ(gpc);
                                    if (Double.IsNaN(geomUser.GetZ(gpc)))
                                    {
                                        pTUser[2] = 0;
                                    }

                                    Point3d pt3DUser = new Point3d();
                                    pt3DUser.X = pTUser[0];
                                    pt3DUser.Y = pTUser[1];
                                    pt3DUser.Z = pTUser[2];

                                    if ((userSRS.IsProjected() == 0) && (userSRS.IsLocal() == 0))
                                    {
                                        gsetUser.Append(new GH_Point(Heron.Convert.WGSToXYZ(pt3DUser)), new GH_Path(i, iLayer, m));
                                    }
                                    else
                                    {
                                        gsetUser.Append(new GH_Point(userSRSToModel * pt3DUser), new GH_Path(i, iLayer, m));
                                    }
                                    ///End loop through geometry points


                                    /// Get Feature Values
                                    if (fset.PathExists(new GH_Path(i, iLayer, m)))
                                    {
                                        fset.get_Branch(new GH_Path(i, iLayer, m)).Clear();
                                    }
                                    for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                                    {
                                        OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                        if (feat.IsFieldSet(iField))
                                        {
                                            fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m));
                                        }
                                        else
                                        {
                                            fset.Append(new GH_String("null"), new GH_Path(i, iLayer, m));
                                        }
                                    }
                                    ///End Get Feature Values
                                }
                                ///End getting points if open polylines or points



                                ///Start getting points if closed polylines and multipolygons
                                for (int gi = 0; gi < geom.GetGeometryCount(); gi++)
                                {
                                    sub_geom = geom.GetGeometryRef(gi);
                                    OSGeo.OGR.Geometry subsub_geom;
                                    //List<Point3d> geom_list = new List<Point3d>();

                                    sub_geomUser = geomUser.GetGeometryRef(gi);
                                    OSGeo.OGR.Geometry subsub_geomUser;

                                    if (sub_geom.GetGeometryCount() > 0)
                                    {
                                        for (int n = 0; n < sub_geom.GetGeometryCount(); n++)
                                        {
                                            subsub_geom     = sub_geom.GetGeometryRef(n);
                                            subsub_geomUser = sub_geomUser.GetGeometryRef(n);

                                            for (int ptnum = 0; ptnum < subsub_geom.GetPointCount(); ptnum++)
                                            {
                                                ///Loop through geometry points
                                                double[] pT = new double[3];
                                                pT[0] = subsub_geom.GetX(ptnum);
                                                pT[1] = subsub_geom.GetY(ptnum);
                                                pT[2] = subsub_geom.GetZ(ptnum);

                                                Point3d pt3D = new Point3d();
                                                pt3D.X = pT[0];
                                                pt3D.Y = pT[1];
                                                pt3D.Z = pT[2];

                                                gset.Append(new GH_Point(Heron.Convert.WGSToXYZ(pt3D)), new GH_Path(i, iLayer, m, gi, n));


                                                double[] pTUser = new double[3];
                                                pTUser[0] = subsub_geomUser.GetX(ptnum);
                                                pTUser[1] = subsub_geomUser.GetY(ptnum);
                                                pTUser[2] = subsub_geomUser.GetZ(ptnum);

                                                Point3d pt3DUser = new Point3d();
                                                pt3DUser.X = pTUser[0];
                                                pt3DUser.Y = pTUser[1];
                                                pt3DUser.Z = pTUser[2];

                                                if ((userSRS.IsProjected() == 0) && (userSRS.IsLocal() == 0))
                                                {
                                                    gsetUser.Append(new GH_Point(Heron.Convert.WGSToXYZ(pt3DUser)), new GH_Path(i, iLayer, m, gi, n));
                                                }
                                                else
                                                {
                                                    gsetUser.Append(new GH_Point(userSRSToModel * pt3DUser), new GH_Path(i, iLayer, m, gi, n));
                                                }

                                                ///End loop through geometry points
                                            }
                                            subsub_geom.Dispose();
                                            subsub_geomUser.Dispose();
                                        }
                                    }

                                    else
                                    {
                                        for (int ptnum = 0; ptnum < sub_geom.GetPointCount(); ptnum++)
                                        {
                                            ///Loop through geometry points
                                            double[] pT = new double[3];
                                            pT[0] = sub_geom.GetX(ptnum);
                                            pT[1] = sub_geom.GetY(ptnum);
                                            pT[2] = sub_geom.GetZ(ptnum);

                                            Point3d pt3D = new Point3d();
                                            pt3D.X = pT[0];
                                            pt3D.Y = pT[1];
                                            pt3D.Z = pT[2];

                                            gset.Append(new GH_Point(Heron.Convert.WGSToXYZ(pt3D)), new GH_Path(i, iLayer, m, gi));


                                            double[] pTUser = new double[3];
                                            pTUser[0] = sub_geomUser.GetX(ptnum);
                                            pTUser[1] = sub_geomUser.GetY(ptnum);
                                            pTUser[2] = sub_geomUser.GetZ(ptnum);

                                            Point3d pt3DUser = new Point3d();
                                            pt3DUser.X = pTUser[0];
                                            pt3DUser.Y = pTUser[1];
                                            pt3DUser.Z = pTUser[2];

                                            if ((userSRS.IsProjected() == 0) && (userSRS.IsLocal() == 0))
                                            {
                                                gsetUser.Append(new GH_Point(Heron.Convert.WGSToXYZ(pt3DUser)), new GH_Path(i, iLayer, m, gi));
                                            }
                                            else
                                            {
                                                gsetUser.Append(new GH_Point(userSRSToModel * pt3DUser), new GH_Path(i, iLayer, m, gi));
                                            }
                                            ///End loop through geometry points
                                        }
                                    }

                                    sub_geom.Dispose();
                                    sub_geomUser.Dispose();


                                    /// Get Feature Values
                                    if (fset.PathExists(new GH_Path(i, iLayer, m)))
                                    {
                                        fset.get_Branch(new GH_Path(i, iLayer, m)).Clear();
                                    }
                                    for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                                    {
                                        OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                        if (feat.IsFieldSet(iField))
                                        {
                                            fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m));
                                        }
                                        else
                                        {
                                            fset.Append(new GH_String("null"), new GH_Path(i, iLayer, m));
                                        }
                                    }
                                    ///End Get Feature Values
                                }
                                //m++;
                            }
                            m++;
                            geom.Dispose();
                            geomUser.Dispose();
                            feat.Dispose();
                        } ///end while loop through features
                    }
                }         //end loop through boundaries

                layer.Dispose();
            }///end loop through layers

            ds.Dispose();

            DA.SetDataTree(0, layname);
            DA.SetDataTree(1, fcs);
            DA.SetDataTree(2, recs);
            DA.SetDataTree(3, sRefs);
            DA.SetDataTree(4, fnames);
            DA.SetDataTree(5, fset);
            DA.SetDataTree(6, gset);

            DA.SetDataTree(7, gsetUser);
            DA.SetDataTree(8, recsUser);
        }
Example #33
0
        private async void Initialize()
        {
            // Create new Map with basemap.
            Map map = new Map(BasemapStyle.ArcGISTopographic);

            // Provide Map to the MapView.
            _myMapView.Map = map;

            // Get the path to the geodatabase.
            string geodbFilePath = DataManager.GetDataFolder("e0d41b4b409a49a5a7ba11939d8535dc", "militaryoverlay.geodatabase");

            // Load the geodatabase from local storage.
            Geodatabase baseGeodatabase = await Geodatabase.OpenAsync(geodbFilePath);

            // Get the path to the symbol dictionary.
            string symbolFilepath = DataManager.GetDataFolder("c78b149a1d52414682c86a5feeb13d30", "mil2525d.stylx");

            try
            {
                // Load the symbol dictionary from local storage.
                DictionarySymbolStyle symbolStyle = await DictionarySymbolStyle.CreateFromFileAsync(symbolFilepath);

                // Add geodatabase features to the map, using the defined symbology.
                foreach (GeodatabaseFeatureTable table in baseGeodatabase.GeodatabaseFeatureTables)
                {
                    // Load the table.
                    await table.LoadAsync();

                    // Create the feature layer from the table.
                    FeatureLayer layer = new FeatureLayer(table);

                    // Load the layer.
                    await layer.LoadAsync();

                    // Create and use a Dictionary Renderer using the DictionarySymbolStyle.
                    layer.Renderer = new DictionaryRenderer(symbolStyle);

                    // Add the layer to the map.
                    map.OperationalLayers.Add(layer);
                }

                // Create geometry for the center of the map.
                MapPoint centerGeometry = new MapPoint(-13549402.587055, 4397264.96879385, SpatialReference.Create(3857));

                // Set the map's viewpoint to highlight the desired content.
                _myMapView.SetViewpoint(new Viewpoint(centerGeometry, 201555));
            }
            catch (Exception e)
            {
                new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show();
            }
        }
 public static Geometry ReadWellKnownBinary(this Stream inputStream, SpatialReference spatialReference = null)
 {
     return(new WkbConverter().Read(inputStream, spatialReference));
 }
Example #35
0
        ControlZone _zoneB = new ControlZone(); //管控区B

        public bool ConflictAnalysis()
        {
            IFeatureSet resultSet = null;

            try
            {
                #region 相交分析

                OSGeo.OGR.Layer layerA = null;
                if (_zoneA.FeatureSet != null)
                {
                    layerA = GIS.GDAL.VectorConverter.DS2OrgLayer(_zoneA.FeatureSet);
                }
                else
                {
                    layerA = GIS.GDAL.VectorConverter.GetOgrLayer(_zoneA.Address);
                }

                OSGeo.OGR.Layer layerB = null;
                if (_zoneB.FeatureSet != null)
                {
                    layerB = GIS.GDAL.VectorConverter.DS2OrgLayer(_zoneB.FeatureSet);
                }
                else
                {
                    layerB = GIS.GDAL.VectorConverter.GetOgrLayer(_zoneB.Address);
                }

                OSGeo.OGR.Layer resultLayer = null;
                using (OSGeo.OGR.Driver driver = Ogr.GetDriverByName("ESRI Shapefile"))
                {
                    if (driver == null)
                    {
                        System.Environment.Exit(-1);
                    }
                    string[] resultPath = _address.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
                    string   resultName = resultPath[resultPath.Length - 1];
                    using (var dsResult = driver.CreateDataSource(_address, new string[] { }))
                    {
                        if (dsResult == null)
                        {
                            throw new Exception("Can't get to the datasoure.");
                        }

                        for (int i = 0; i < dsResult.GetLayerCount(); i++)
                        {
                            resultLayer = dsResult.GetLayerByIndex(i);
                            if (resultLayer != null && resultLayer.GetLayerDefn().GetName() == resultName)
                            {
                                dsResult.DeleteLayer(i);
                                break;
                            }
                        }
                        SpatialReference reference  = layerA.GetSpatialRef();
                        FeatureDefn      definition = layerA.GetLayerDefn();
                        wkbGeometryType  type       = definition.GetGeomType();
                        resultLayer = dsResult.CreateLayer("ResultLayer", layerA.GetSpatialRef(), layerA.GetLayerDefn().GetGeomType(), new string[] { });

                        bool intersectSuccess = GIS.GDAL.Overlay.Overlay.OverlayOperate(layerA, layerB, ref resultLayer, OverlayType.Intersects, null);

                        if (!intersectSuccess)
                        {
                            return(false);
                        }
                    }
                }

                #endregion

                resultSet = DotSpatial.Data.DataManager.DefaultDataManager.OpenFile(_address) as IFeatureSet;

                #region 添加转换要素的字段

                DataTable resultTable = resultSet.DataTable;

                DataColumn conflictColumn = new DataColumn();
                conflictColumn.DataType   = typeof(string);
                conflictColumn.ColumnName = "冲突类型";
                conflictColumn.MaxLength  = 100;
                resultTable.Columns.Add(conflictColumn);

                DataColumn conflictColumn2 = new DataColumn();
                conflictColumn2.DataType   = typeof(string);
                conflictColumn2.ColumnName = "处理意见";
                conflictColumn2.MaxLength  = 100;
                resultTable.Columns.Add(conflictColumn2);

                DataColumn conflictColumn3 = new DataColumn();
                conflictColumn3.DataType   = typeof(string);
                conflictColumn3.ColumnName = "备注";
                conflictColumn3.MaxLength  = 50;
                resultTable.Columns.Add(conflictColumn3);

                DataColumn conflictColumn4 = new DataColumn();
                conflictColumn4.DataType   = typeof(string);
                conflictColumn4.ColumnName = "用地类型";
                conflictColumn4.MaxLength  = 50;
                resultTable.Columns.Add(conflictColumn4);

                #endregion

                int index = resultTable.Columns.IndexOf("冲突类型");
                for (int i = 0; i < resultTable.Rows.Count; i++)
                {
                    DataRow dataRow = resultTable.Rows[i];
                    dataRow[index] = _conflictType;
                }

                resultSet.Save();
                if (resultSet.Projection == null)
                {
                }
                GIS.FrameWork.Application.App.Map.Layers.Add(resultSet);

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
        public RecordSet ProjectRecordSet(Envelope env, RecordSet rs, int geomFieldIndex, SpatialReference inSR, SpatialReference outSR)
        {
            if (geomFieldIndex < 0)
            {
                return(null);
            }
            if (rs == null)
            {
                return(null);
            }
            if (inSR == null || outSR == null)
            {
                return(rs);
            }
            if (AGSService.SpRefAreEquivalent(inSR, outSR))
            {
                return(rs);
            }
            RecordSet result;

            try
            {
                List <Geometry> list    = new List <Geometry>(rs.Records.Length);
                Record[]        records = rs.Records;
                for (int i = 0; i < records.Length; i++)
                {
                    Record   record   = records[i];
                    Geometry geometry = record.Values[geomFieldIndex] as Geometry;
                    if (geometry != null)
                    {
                        list.Add(geometry);
                    }
                }
                try
                {
                    Geometry[] inGeometryArray = list.ToArray();
                    Geometry[] array           = this._GeomServer.Project(inSR, outSR, true, null, env, inGeometryArray);
                    int        num             = 0;
                    Record[]   records2        = rs.Records;
                    for (int j = 0; j < records2.Length; j++)
                    {
                        Record record2 = records2[j];
                        record2.Values[geomFieldIndex] = array[num++];
                    }
                    result = rs;
                }
                catch
                {
                    if (base.Parent.Challenge())
                    {
                        this._GeomServer.Proxy       = WebRequest.DefaultWebProxy;
                        this._GeomServer.Credentials = base.Parent.Credentials;
                        if (this._GeomServer.Credentials == null)
                        {
                            this._GeomServer.UseDefaultCredentials = true;
                        }
                        try
                        {
                            Geometry[] inGeometryArray2 = list.ToArray();
                            Geometry[] array2           = this._GeomServer.Project(inSR, outSR, true, null, env, inGeometryArray2);
                            int        num2             = 0;
                            Record[]   records3         = rs.Records;
                            for (int k = 0; k < records3.Length; k++)
                            {
                                Record record3 = records3[k];
                                record3.Values[geomFieldIndex] = array2[num2++];
                            }
                            result = rs;
                            return(result);
                        }
                        catch
                        {
                            result = this.ProjectRecordSetCarefully(env, rs, geomFieldIndex, inSR, outSR);
                            return(result);
                        }
                    }
                    result = null;
                }
            }
            catch (Exception ex)
            {
                string arg_190_0 = ex.Message;
                result = this.ProjectRecordSetCarefully(env, rs, geomFieldIndex, inSR, outSR);
            }
            return(result);
        }
Example #37
0
        /// <summary>
        /// Simplify the list of geometries passed in using the GeometryServer.Simplify permanently alters the input geometry so that it becomes topologically consistent.
        /// </summary>
        /// <typeparam name = "T" > The type of the geometries</typeparam>
        /// <param name = "features" > A collection of features which will have their geometries buffered</param>
        /// <param name = "spatialReference" > The spatial reference of the geometries</param>
        /// <param name = "ct" > Optional cancellation token to cancel pending request</param>
        /// <returns>The corresponding features with the newly simplified geometries</returns>
        public virtual async Task <List <Feature <T> > > Simplify <T>(List <Feature <T> > features, SpatialReference spatialReference, CancellationToken ct = default(CancellationToken))
            where T : IGeometry
        {
            var op         = new SimplifyGeometry <T>(GeometryServiceEndpoint, features, spatialReference);
            var simplified = await Post <GeometryOperationResponse <T>, SimplifyGeometry <T> >(op, ct).ConfigureAwait(false);

            if (ct.IsCancellationRequested)
            {
                return(null);
            }

            var result = features.UpdateGeometries <T>(simplified.Geometries);

            if (result.First().Geometry.SpatialReference == null)
            {
                result.First().Geometry.SpatialReference = spatialReference;
            }
            return(result);
        }
Example #38
0
        static IEnumerable<DataTable> ReadData(DataSource OGRDataSource, DataSet OSMDataSet, int SQLBatchSize)
        {
            int featureCount = 0;

            // Create coordinate transformation
            SpatialReference sourceSRS = new SpatialReference("");
            sourceSRS.ImportFromEPSG(4326);
            SpatialReference targetSRS = new SpatialReference("");
            targetSRS.ImportFromEPSG(900913);
            CoordinateTransformation transform = new CoordinateTransformation(sourceSRS, targetSRS);

            // Use interleaved reading - http://www.gdal.org/drv_osm.html
            bool bHasLayersNonEmpty = false;
            do
            {
                bHasLayersNonEmpty = false;
                for (int iLayer = 0; iLayer < OGRDataSource.GetLayerCount(); iLayer++)
                {
                    Layer OGRLayer = OGRDataSource.GetLayerByIndex(iLayer);
                    log(TraceLevel.Verbose, string.Format("Processing {0}...", OGRLayer.GetName()));
                    FeatureDefn OGRFeatDef = OGRLayer.GetLayerDefn();
                    DataTable buffer = OSMDataSet.Tables[OGRLayer.GetName()];

                    Feature feat;
                    while ((feat = OGRLayer.GetNextFeature()) != null)
                    {
                        bHasLayersNonEmpty = true;

                        // Commit buffer larger than batch size
                        if (buffer.Rows.Count >= SQLBatchSize)
                        {
                            yield return buffer.Copy();
                            buffer.Rows.Clear();
                        }

                        // Fill buffer row
                        DataRow row = buffer.NewRow();
                        for (int iField = 0; iField < OGRFeatDef.GetFieldCount(); iField++)
                        {
                            if (feat.IsFieldSet(iField))
                            {
                                // Add one to skip id IDENTITY column
                                row[iField + 1] = feat.GetFieldAsString(iField);
                            }
                        }

                        // Get OGR geometry object
                        Geometry geom = feat.GetGeometryRef();

                        // Project from EPSG:4326 to EPSG:900913
                        geom.Transform(transform);

                        // Serialize to WKB
                        byte[] geomBuffer = new byte[geom.WkbSize()];
                        geom.ExportToWkb(geomBuffer);

                        // Set ogr_geometry buffer column from WKB
                        try
                        {
                            SqlGeometry sqlGeom = SqlGeometry.STGeomFromWKB(new SqlBytes(geomBuffer), 900913).MakeValid();
                            row["ogr_geometry"] = sqlGeom;
                            row["ogr_geometry_area"] = sqlGeom.STArea().Value;

                            // Add row to buffer
                            buffer.Rows.Add(row);
                        }
                        catch (Exception e)
                        {
                            log(TraceLevel.Warning, string.Format("Cannot process osm_id: {0} ({1})", feat.GetFID(), e.Message));
                        }

                        // Update progress
                        featureCount++;
                    }

                    // Commit buffer before moving on to another layer
                    if (buffer.Rows.Count != 0)
                    {
                        yield return buffer.Copy();
                        buffer.Rows.Clear();
                    }
                }
            } while (bHasLayersNonEmpty);
        }
Example #39
0
        private async void Initialize()
        {
            // Create new Map with basemap
            Map myMap = new Map(BasemapStyle.ArcGISTopographic);

            // Provide Map to the MapView
            MyMapView.Map = myMap;

            // Get the path to the geodatabase
            string geodbFilePath = GetGeodatabasePath();

            // Load the geodatabase from local storage
            Geodatabase baseGeodatabase = await Geodatabase.OpenAsync(geodbFilePath);

            // Get the path to the symbol dictionary
            string symbolFilepath = GetStyleDictionaryPath();

            try
            {
                // Load the symbol dictionary from local storage
                DictionarySymbolStyle symbolStyle = await DictionarySymbolStyle.CreateFromFileAsync(symbolFilepath);

                // Add geodatabase features to the map, using the defined symbology
                foreach (FeatureTable table in baseGeodatabase.GeodatabaseFeatureTables)
                {
                    // Load the table
                    await table.LoadAsync();

                    // Create the feature layer from the table
                    FeatureLayer myLayer = new FeatureLayer(table);

                    // Load the layer
                    await myLayer.LoadAsync();

                    // Create a Dictionary Renderer using the DictionarySymbolStyle
                    DictionaryRenderer dictRenderer = new DictionaryRenderer(symbolStyle);

                    // Apply the dictionary renderer to the layer
                    myLayer.Renderer = dictRenderer;

                    // Add the layer to the map
                    myMap.OperationalLayers.Add(myLayer);
                }

                // Create geometry for the center of the map
                MapPoint centerGeometry = new MapPoint(-13549402.587055, 4397264.96879385, SpatialReference.Create(3857));

                // Set the map's viewpoint to highlight the desired content
                MyMapView.SetViewpoint(new Viewpoint(centerGeometry, 201555));
            }
            catch (Exception e)
            {
                await new MessageDialog(e.ToString(), "Error").ShowAsync();
            }
        }
        public async void Search(int wkid)
        {

            // Create the symbol
            SimpleMarkerSymbol markerSymbol = new SimpleMarkerSymbol();
            markerSymbol.Size = 15;
            markerSymbol.Color = Colors.Green;
            markerSymbol.Style = SimpleMarkerStyle.Diamond;

            SimpleFillSymbol sfsState = new SimpleFillSymbol()
            {
                Color = Colors.Red,
                Style = SimpleFillStyle.Solid
            };
            SimpleFillSymbol sfsCounty = new SimpleFillSymbol()
            {
                Color = Colors.Red,
                Style = SimpleFillStyle.Solid
            };

            SpatialReference sr = new SpatialReference(wkid);

            Query queryCity = new Query("areaname = '" + this.SearchText + "'");
            queryCity.OutSpatialReference = sr;
            queryCity.OutFields.Add("*");
            QueryTask queryTaskCity = new QueryTask(new System.Uri(this.USAUri + "/0"));
            QueryResult queryResultCity = await queryTaskCity.ExecuteAsync(queryCity);

            Query queryStates = new Query("state_name = '" + this.SearchText + "'");
            queryStates.OutSpatialReference = sr;
            queryStates.OutFields.Add("*");
            QueryTask queryTaskStates = new QueryTask(new System.Uri(this.USAUri + "/2"));
            QueryResult queryResultStates = await queryTaskStates.ExecuteAsync(queryStates);

            Query queryCounties = new Query("name = '" + this.SearchText + "'");
            queryCounties.OutSpatialReference = sr;
            queryCounties.OutFields.Add("*");
            QueryTask queryTaskCounties = new QueryTask(new System.Uri(this.USAUri + "/3"));
            QueryResult queryResultCounties= await queryTaskCounties.ExecuteAsync(queryCounties);

            // Get the list of features (graphics) from the result
            IReadOnlyList<Feature> featuresCity = queryResultCity.FeatureSet.Features;
            foreach (Feature featureCity in featuresCity)
            {
                Graphic graphicCity = (Graphic)featureCity;
                graphicCity.Symbol = markerSymbol;
                this.graphicsLayerCity.Graphics.Add(graphicCity);
            }

            // Get the list of features (graphics) from the result
            IReadOnlyList<Feature> featuresStates = queryResultStates.FeatureSet.Features;
            foreach (Feature featureState in featuresStates)
            {
                Graphic graphicState = (Graphic)featureState;
                graphicState.Symbol = sfsState;
                this.graphicsLayerState.Graphics.Add(graphicState);
            }
            // Get the list of features (graphics) from the result
            IReadOnlyList<Feature> featuresCounties = queryResultCounties.FeatureSet.Features;
            foreach (Feature featureCounty in featuresCounties)
            {
                Graphic graphicCounty = (Graphic)featureCounty;
                graphicCounty.Symbol = sfsCounty;
                this.graphicsLayerCounty.Graphics.Add(graphicCounty);
            }

                      
        }
Example #41
0
        async static Task <int> Main(string[] args)
        {
            try
            {
                string cmd = "fill", jsonFile = (args.Length == 1 && args[0] != "fill" ? args[0] : String.Empty), indexUrl = String.Empty, indexName = String.Empty, category = String.Empty;

                string proxyUrl = String.Empty, proxyUser = String.Empty, proxyPassword = String.Empty;
                string basicAuthUser = String.Empty, basicAuthPassword = String.Empty;

                int  packageSize = 50000;
                bool replace     = false;

                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i] == "fill" && i < args.Length - 1)
                    {
                        cmd      = "fill";
                        jsonFile = args[i + 1];
                        i++;
                    }
                    if (args[i] == "remove-category")
                    {
                        cmd = "remove-category";
                    }
                    if (args[i] == "-s" && i < args.Length - 1)
                    {
                        indexUrl = args[i + 1];
                    }

                    if (args[i] == "-i" && i < args.Length - 1)
                    {
                        indexName = args[i + 1];
                    }

                    if (args[i] == "-c" && i < args.Length - 1)
                    {
                        category = args[i + 1];
                    }

                    if (args[i] == "-r")
                    {
                        replace = true;
                    }

                    if (args[i] == "-packagesize" && i < args.Length - 1)
                    {
                        packageSize = int.Parse(args[i + 1]);
                    }

                    #region Proxy

                    if (args[i] == "-proxy")
                    {
                        proxyUrl = args[i + 1];
                    }
                    if (args[i] == "-proxy-user")
                    {
                        proxyUser = args[i + 1];
                    }
                    if (args[i] == "-proxy-pwd")
                    {
                        proxyPassword = args[i + 1];
                    }

                    #endregion

                    #region Basic Authentication

                    if (args[i] == "-basic-auth-user")
                    {
                        basicAuthUser = args[i + 1];
                    }

                    if (args[i] == "-basic-auth-pwd")
                    {
                        basicAuthPassword = args[i + 1];
                    }

                    #endregion
                }

                if (args.Length == 0)
                {
                    Console.WriteLine("Usage: gView.Cmd.ElasticSearch fill|remove-catetory [Options]");
                    return(1);
                }


                //gView.Framework.system.SystemVariables.CustomApplicationDirectory =
                //    System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

                Console.WriteLine("Environment");

                Console.WriteLine("Working Directory: " + gView.Framework.system.SystemVariables.StartupDirectory);
                Console.WriteLine("64Bit=" + gView.Framework.system.Wow.Is64BitProcess);

                if (cmd == "fill")
                {
                    #region Fill Index (with Json File)

                    var importConfig = JsonConvert.DeserializeObject <ImportConfig>(File.ReadAllText(jsonFile));

                    if (importConfig?.Connection == null)
                    {
                        throw new Exception("Invalid config. No connection defined");
                    }

                    var httpClientHandler = new HttpClientHandler();
                    if (!String.IsNullOrEmpty(proxyUrl))
                    {
                        httpClientHandler.Proxy = new WebProxy
                        {
                            Address               = new Uri(proxyUrl),
                            BypassProxyOnLocal    = false,
                            UseDefaultCredentials = false,

                            Credentials = new NetworkCredential(proxyUser, proxyPassword)
                        };
                    }

                    var httpClient = new HttpClient(handler: httpClientHandler, disposeHandler: true);
                    if (!String.IsNullOrEmpty(basicAuthUser))
                    {
                        var byteArray = Encoding.ASCII.GetBytes($"{ basicAuthUser }:{ basicAuthPassword }");
                        httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
                    }

                    using (var luceneServerClient = new LuceneServerClient(
                               importConfig.Connection.Url,
                               importConfig.Connection.DefaultIndex,
                               httpClient: httpClient))
                    {
                        if (importConfig.Connection.DeleteIndex)
                        {
                            await luceneServerClient.RemoveIndexAsync();
                        }

                        if (!await luceneServerClient.CreateIndexAsync())
                        {
                            throw new Exception($"Can't create elasticsearch index { importConfig.Connection.DefaultIndex }");
                        }
                        if (!await luceneServerClient.MapAsync(new SearchIndexMapping()))
                        {
                            throw new Exception($"Can't map item in elasticsearch index { importConfig.Connection.DefaultIndex }");
                        }

                        ISpatialReference sRefTarget = SpatialReference.FromID("epsg:4326");

                        Console.WriteLine("Target Spatial Reference: " + sRefTarget.Name + " " + String.Join(" ", sRefTarget.Parameters));

                        foreach (var datasetConfig in importConfig.Datasets)
                        {
                            if (datasetConfig.FeatureClasses == null)
                            {
                                continue;
                            }

                            IDataset dataset = new PlugInManager().CreateInstance(datasetConfig.DatasetGuid) as IDataset;
                            if (dataset == null)
                            {
                                throw new ArgumentException("Can't load dataset with guid " + datasetConfig.DatasetGuid.ToString());
                            }

                            await dataset.SetConnectionString(datasetConfig.ConnectionString);

                            await dataset.Open();

                            foreach (var featureClassConfig in datasetConfig.FeatureClasses)
                            {
                                var itemProto = featureClassConfig.IndexItemProto;
                                if (itemProto == null)
                                {
                                    continue;
                                }

                                string metaId = Guid.NewGuid().ToString("N").ToLower();
                                category = featureClassConfig.Category;
                                if (!String.IsNullOrWhiteSpace(category))
                                {
                                    var meta = new Meta()
                                    {
                                        Id         = metaId,
                                        Category   = category,
                                        Descrption = featureClassConfig.Meta?.Descrption,
                                        Sample     = featureClassConfig?.Meta.Sample,
                                        Service    = featureClassConfig?.Meta.Service,
                                        Query      = featureClassConfig?.Meta.Query
                                    };
                                    if (!await luceneServerClient.AddCustomMetadataAsync(metaId, JsonConvert.SerializeObject(meta)))
                                    {
                                        throw new Exception($"Can't index meta item in elasticsearch index { importConfig.Connection.MetaIndex }");
                                    }
                                }

                                bool useGeometry = featureClassConfig.UserGeometry;

                                IDatasetElement dsElement = await dataset.Element(featureClassConfig.Name);

                                if (dsElement == null)
                                {
                                    throw new ArgumentException("Unknown dataset element " + featureClassConfig.Name);
                                }

                                IFeatureClass fc = dsElement.Class as IFeatureClass;
                                if (fc == null)
                                {
                                    throw new ArgumentException("Dataobject is not a featureclass " + featureClassConfig.Name);
                                }

                                Console.WriteLine("Index " + fc.Name);
                                Console.WriteLine("=====================================================================");

                                QueryFilter filter = new QueryFilter();
                                filter.SubFields = "*";
                                if (!String.IsNullOrWhiteSpace(featureClassConfig.Filter))
                                {
                                    filter.WhereClause = featureClassConfig.Filter;
                                    Console.WriteLine("Filter: " + featureClassConfig.Filter);
                                }

                                List <Dictionary <string, object> > items = new List <Dictionary <string, object> >();
                                int count = 0;

                                ISpatialReference sRef = fc.SpatialReference ?? SpatialReference.FromID("epsg:" + featureClassConfig.SRefId);
                                Console.WriteLine("Source Spatial Reference: " + sRef.Name + " " + String.Join(" ", sRef.Parameters));
                                Console.WriteLine("IDField: " + fc.IDFieldName);

                                using (var transformer = GeometricTransformerFactory.Create())
                                {
                                    if (useGeometry)
                                    {
                                        transformer.SetSpatialReferences(sRef, sRefTarget);
                                    }

                                    IFeatureCursor cursor = await fc.GetFeatures(filter);

                                    IFeature feature;
                                    while ((feature = await cursor.NextFeature()) != null)
                                    {
                                        var indexItem = ParseFeature(metaId, category, feature, itemProto, useGeometry, transformer, featureClassConfig);
                                        items.Add(indexItem);
                                        count++;

                                        if (items.Count >= packageSize)
                                        {
                                            if (!await luceneServerClient.IndexDocumentsAsync(items.ToArray()))
                                            {
                                                throw new Exception($"Error on indexing { items.Count } items on elasticsearch index { importConfig.Connection.DefaultIndex }");
                                            }
                                            items.Clear();

                                            Console.Write(count + "...");
                                        }
                                    }

                                    if (items.Count > 0)
                                    {
                                        if (!await luceneServerClient.IndexDocumentsAsync(items.ToArray()))
                                        {
                                            throw new Exception($"Error on indexing { items.Count } items on elasticsearch index { importConfig.Connection.DefaultIndex }");
                                        }
                                        Console.WriteLine(count + "...finish");
                                    }
                                }
                            }
                        }
                    }

                    #endregion
                }
                else if (cmd == "remove-category")
                {
                    #region Remove Category

                    //RemoveCategory(indexUrl, indexName, replace ? Replace(category) : category,
                    //               proxyUrl, proxyUser, proxyPassword,
                    //               basicAuthUser, basicAuthPassword);

                    #endregion
                }

                return(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);

                return(1);
            }
        }
 public abstract void CreateLayerAsync(Resource layerResource, SpatialReference mapSpatialReference, object userState);
Example #43
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="OpenStreetMapLayer" /> class.
 /// </summary>
 public WebTileLayer()
 {
     SpatialReference = new SpatialReference(WKID);
     Application.Current.Exit += StopProcessingWebRequests;
 }
Example #44
0
        private void createNewMapBasedOnTargetSpatialReferenceForBaseMapLayer(BaseMapInfo baseMapInfo, SpatialReference targetServiceSpatialReference,
                Envelope targetInitialExtent, Envelope targetFullExtent)
        {
            if (Map.SpatialReference.Equals(targetServiceSpatialReference))
            {
                // Spatial references are equal -> extents are valid to compare               
                Envelope targetExtent = Map.Extent;
                if (isFullyContainedWithin(targetExtent, targetFullExtent))
                    targetExtent = targetFullExtent; // if the full extent of the new service is fully within, automatically zoom to it                                
                reCreateBaseMapLayer(baseMapInfo, targetExtent);
            }
            else if (targetServiceSpatialReference != null)
            {
                // Spatial reference mismatch

                // Since cached services cannot re-project on the fly.
                // Check if the application has any cached map services for operational data. 
                // If so, Ask the user if they wish to delete them before changing basemap
                bool hasCachedMapServiceLayer = false;
                for (int i = 1; i < Map.Layers.Count; i++) // we only care about operational data .. not basemap layer (index = 0
                {
                    if (Map.Layers[i] is ArcGISTiledMapServiceLayer)
                    {
                        hasCachedMapServiceLayer = true;
                        break;
                    }
                }
                if (hasCachedMapServiceLayer)
                {
                    MessageBoxDialog.Show(LocalizableStrings.OperationMapServicesLayersWillBeRemoved, LocalizableStrings.OperationMapServicesLayersWillBeRemovedCaption, MessageBoxButton.OKCancel,
                                    new MessageBoxClosedEventHandler(delegate(object obj, MessageBoxClosedArgs args1)
                                    {
                                        if (args1.Result == MessageBoxResult.OK)
                                        {
                                            // Remove all cached map services
                                            for (int i = Map.Layers.Count - 1; i > 0; i--)
                                            {
                                                ArcGISTiledMapServiceLayer tiledMapServiceLayer = Map.Layers[i] as ArcGISTiledMapServiceLayer;
                                                if (tiledMapServiceLayer != null)
                                                    Map.Layers.Remove(tiledMapServiceLayer);
                                            }
                                        }
                                        else
                                        {
                                            OnBaseMapChangeFailed(new ExceptionEventArgs(new Exception(ESRI.ArcGIS.Mapping.Controls.Resources.Strings.ExceptionCacheMapServicesCannotReproject), null));
                                            return;
                                        }
                                        CreateNewBaseMapWithSpatialReference(targetInitialExtent, targetFullExtent, baseMapInfo, targetServiceSpatialReference);
                                    }));
                }
                else
                    CreateNewBaseMapWithSpatialReference(targetInitialExtent, targetFullExtent, baseMapInfo, targetServiceSpatialReference);
            }
            else
            {
                reCreateBaseMapLayer(baseMapInfo, null);
            }
        }
Example #45
0
        private async void Initialize()
        {
            // Create new Map with basemap
            Map myMap = new Map(Basemap.CreateTopographic());

            // Provide Map to the MapView
            _myMapView.Map = myMap;

            // Create geometry for the center of the map
            MapPoint centerGeometry = new MapPoint(-13549402.587055, 4397264.96879385, SpatialReference.Create(3857));

            // Set the map's viewpoint to highlight the desired content
            await _myMapView.SetViewpointCenterAsync(centerGeometry);

            await _myMapView.SetViewpointScaleAsync(201555.279);

            // Get the path to the geodatabase
            string geodbFilePath = GetGeodatabasePath();

            // Load the geodatabase from local storage
            Geodatabase baseGeodatabase = await Geodatabase.OpenAsync(geodbFilePath);

            // Get the path to the symbol dictionary
            string symbolFilepath = GetStyleDictionaryPath();

            // Load the symbol dictionary from local storage
            //     Note that the type of the symbol definition must be explicitly provided along with the file name
            DictionarySymbolStyle symbolStyle = await DictionarySymbolStyle.OpenAsync("mil2525d", symbolFilepath);

            // Add geodatabase features to the map, using the defined symbology
            foreach (FeatureTable table in baseGeodatabase.GeodatabaseFeatureTables)
            {
                // Load the table
                await table.LoadAsync();

                // Create the feature layer from the table
                FeatureLayer myLayer = new FeatureLayer(table);

                // Load the layer
                await myLayer.LoadAsync();

                // Create a Dictionary Renderer using the DictionarySymbolStyle
                DictionaryRenderer dictRenderer = new DictionaryRenderer(symbolStyle);

                // Apply the dictionary renderer to the layer
                myLayer.Renderer = dictRenderer;

                // Add the layer to the map
                myMap.OperationalLayers.Add(myLayer);
            }
        }
Example #46
0
        async private void   Image_MouseEnter(object sender, MouseEventArgs e)
        {
            Polygon polygon;


            var blackSolidLineSymbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlueRGB, 5, SimpleLineStyle.Solid);

            Geometry geometry = null;
            await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
            {
                SpatialReference inSR   = SpatialReferenceBuilder.CreateSpatialReference(32604);
                SpatialReference sr4326 = SpatialReferences.WGS84;
                SpatialReference sr3857 = SpatialReferences.WebMercator;
                ProjectionTransformation projTransFromSRs = ArcGIS.Core.Geometry.ProjectionTransformation.Create(inSR, sr3857);
                List <Coordinate2D> coordinates           = new List <Coordinate2D>()
                {
                    //new Coordinate2D(-159.20168702818188, 21.876487211082708),
                    //new Coordinate2D(-159.42653907783114, 21.838951660451173),
                    //new Coordinate2D(-159.44077880308507, 21.94718691051718),
                    //new Coordinate2D(-159.21630329750306, 21.94718691051718),
                    //new Coordinate2D(-159.21413990271841, 21.9365008022738),
                    //new Coordinate2D(-159.21383956606297, 21.93655454291286),
                    //new Coordinate2D(-159.20168702818188, 21.876487211082708),
                    new Coordinate2D(-17773406.8675, 2478583.7239999995),
                    new Coordinate2D(-17773406.8675, 2578583.7239999995),
                    new Coordinate2D(-16773406.8675, 2578583.7239999995),
                    new Coordinate2D(-17773406.8675, 2478583.7239999995)
                };
                //MapPoint point = new MapPointBuilder.FromGeoCoordinateString()
                //List<MapPoint> mapPoints = new List<MapPoint>();
                //foreach (Coordinate2D item in coordinates)
                //{
                //    MapPoint point = new MapPointBuilder()
                //}
                //mapPoints.Add( coordinates[0].ToMapPoint());
                MapPointBuilder asas = new MapPointBuilder(new Coordinate2D(-159.20168702818188, 21.876487211082708), MapView.Active.Extent.SpatialReference);
                _polygonSymbol       = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.BlackRGB, SimpleFillStyle.Null, SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, 2.0, SimpleLineStyle.Solid));
                MapPoint point       = asas.ToGeometry();
                MapPoint point2      = MapPointBuilder.FromGeoCoordinateString(point.ToGeoCoordinateString(new ToGeoCoordinateParameter(GeoCoordinateType.DD)), MapView.Active.Extent.SpatialReference, GeoCoordinateType.DD);
                using (PolygonBuilder polygonBuilder = new PolygonBuilder(coordinates, inSR))
                {
                    polygonBuilder.SpatialReference = inSR;
                    polygon            = polygonBuilder.ToGeometry();
                    geometry           = polygonBuilder.ToGeometry();
                    Geometry geometry2 = GeometryEngine.Instance.ProjectEx(geometry, projTransFromSRs);
                    _graphic           = MapView.Active.AddOverlayAsync(geometry, _polygonSymbol.MakeSymbolReference());
                    //Application.Current.
                }
            });

            //await  QueuedTask.Run(() =>
            //{
            //    MapView.Active.UpdateOverlay(_graphic, point, SymbolFactory.Instance.ConstructPointSymbol(
            //                            ColorFactory.Instance.BlueRGB, 20.0, SimpleMarkerStyle.Circle).MakeSymbolReference());
            //});
            //_graphic = await this.AddOverlayAsync(geometry, _lineSymbol.MakeSymbolReference());
            Console.WriteLine(sender.ToString());
            //_graphic = MapView.Active.AddOverlay(geometry, _lineSymbol.MakeSymbolReference());


            //Geometry geometry = new PolygonBuilder.CreatePolygon(coordinates, inSR); ;
        }
Example #47
0
        public void ProjectAsync(IEnumerable<Graphic> graphics, SpatialReference outSpatialReference)
        {
            if (outSpatialReference == null ||
                outSpatialReference.WKID != 4326 &&
                !outSpatialReference.Equals(MercatorSref))
            {
                //This projector doesn't support this out sref -> Return geometry untouched
                ProjectCompleted(this, new Tasks.GraphicsEventArgs(graphics.ToList(), null));
            }
            else
            {
                //Perform projection
                var result = graphics.Where(g => g != null).Select(g => new Graphic {Geometry = Project(g.Geometry, outSpatialReference)});

                ProjectCompleted(this, new Tasks.GraphicsEventArgs(result.ToList(), null));
            }
        }
        public static ReturnValue ExportDistrictsToMyAbuDhabiNet()
        {
            var r = new ReturnValue();

            OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", "UTF-8");

            var shpDir = Path.GetFileNameWithoutExtension(DistrictImport.GetShapefileName());
            var ds     = Ogr.OpenShared(DistrictImport.GetShapefileName(), 0);

            if (ds == null)
            {
                r.AddMessage("Data source doesn't exist", true);
                return(r);
            }

            var lyr = ds.GetLayerByIndex(0);

            if (lyr == null)
            {
                r.AddMessage("Layer doesn't destrict", true);
                return(r);
            }

            OSGeo.OGR.Feature nf;

            var srcProj = new SpatialReference(null);
            var tgtProj = new SpatialReference(null);

            srcProj.ImportFromEPSG(32640);
            tgtProj.ImportFromEPSG(4326);

            var trans = new CoordinateTransformation(srcProj, tgtProj);

            string geomWkt;

            Geometry geometry;
            string   districtname_ar;
            string   districtname_en;
            string   districtabbreviation;

            StringBuilder sql = new StringBuilder();

            //sql.AppendLine(sqlStatements.createDistrictTableSQL);
            sql.AppendLine(sqlStatements.emptyDistrictsSQL);

            while (null != (nf = lyr.GetNextFeature()))
            {
                geometry = nf.GetGeometryRef();

                // Transformation goes here
                geometry.Transform(trans);

                geometry.ExportToWkt(out geomWkt);

                districtabbreviation = nf.GetFieldAsString("DISTRICTAB");
                districtname_ar      = nf.GetFieldAsString("NAMEARABIC");
                districtname_en      = nf.GetFieldAsString("NAMELATIN");
                sql.AppendFormat(sqlStatements.insertDistrictsSQL, districtname_ar.MySQLEscape(), districtname_en.MySQLEscape(), geomWkt, districtabbreviation);
            }

            var dlg = new SaveFileDialog();

            dlg.FileName = "districts.sql";
            dlg.Filter   = "SQL files|*.sql";
            dlg.Title    = "Select where to save districts SQL";

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllText(dlg.FileName, sql.ToString());
                r.Success = true;
            }

            return(r);
        }
 public DrawAndEditGraphics()
 {
     this.InitializeComponent();
     mapView1.Map.InitialViewpoint = new Viewpoint(new Envelope(-344448.8744537411, -1182136.4258723476, 3641336.505047027, 1471520.6499406511, SpatialReference.Create(21897)));
     DrawShapes.ItemsSource        = new DrawShape[]
     {
         DrawShape.Freehand, DrawShape.Point, DrawShape.Polygon, DrawShape.Polyline, DrawShape.Arrow, DrawShape.Circle, DrawShape.Ellipse, DrawShape.LineSegment, DrawShape.Rectangle
     };
     DrawShapes.SelectedIndex = 0;
 }
Example #50
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Curve boundary = null;

            DA.GetData <Curve>(0, ref boundary);

            string sourceFileLocation = string.Empty;

            DA.GetData <string>(1, ref sourceFileLocation);

            string clippedLocation = string.Empty;

            DA.GetData <string>(2, ref clippedLocation);

            RESTful.GdalConfiguration.ConfigureGdal();
            OSGeo.GDAL.Gdal.AllRegister();
            ///Specific settings for getting WMS images
            OSGeo.GDAL.Gdal.SetConfigOption("GDAL_HTTP_UNSAFESSL", "YES");
            OSGeo.GDAL.Gdal.SetConfigOption("GDAL_SKIP", "WMS");

            ///Read in the raster data
            Dataset datasource = Gdal.Open(sourceFileLocation, Access.GA_ReadOnly);

            OSGeo.GDAL.Driver drv = datasource.GetDriver();

            string srcInfo = string.Empty;

            if (datasource == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The raster datasource was unreadable by this component. It may not a valid file type for this component or otherwise null/empty.");
                return;
            }


            ///Get the spatial reference of the input raster file and set to WGS84 if not known
            ///Set up transform from source to WGS84
            OSGeo.OSR.SpatialReference sr = new SpatialReference(Osr.SRS_WKT_WGS84);

            if (datasource.GetProjection() == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) is missing.  SRS set automatically set to WGS84.");
            }

            else
            {
                sr = new SpatialReference(datasource.GetProjection());

                if (sr.Validate() != 0)
                {
                    ///Check if SRS needs to be converted from ESRI format to WKT to avoid error:
                    ///"No translation for Lambert_Conformal_Conic to PROJ.4 format is known."
                    ///https://gis.stackexchange.com/questions/128266/qgis-error-6-no-translation-for-lambert-conformal-conic-to-proj-4-format-is-kn
                    SpatialReference srEsri = sr;
                    srEsri.MorphFromESRI();
                    string projEsri = string.Empty;
                    srEsri.ExportToWkt(out projEsri);

                    ///If no SRS exists, check Ground Control Points SRS
                    SpatialReference srGCP   = new SpatialReference(datasource.GetGCPProjection());
                    string           projGCP = string.Empty;
                    srGCP.ExportToWkt(out projGCP);

                    if (!string.IsNullOrEmpty(projEsri))
                    {
                        datasource.SetProjection(projEsri);
                        sr = srEsri;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) morphed form ESRI format.");
                    }
                    else if (!string.IsNullOrEmpty(projGCP))
                    {
                        datasource.SetProjection(projGCP);
                        sr = srGCP;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) set from Ground Control Points (GCPs).");
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) is unknown or unsupported.  SRS assumed to be WGS84." +
                                          "Try setting the SRS with the GdalWarp component using -t_srs EPSG:4326 for the option input.");
                        sr.SetWellKnownGeogCS("WGS84");
                    }
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Data source SRS: EPSG:" + sr.GetAttrValue("AUTHORITY", 1));
                }
            }

            ///Get info about image
            List <string> infoOptions = new List <string> {
                "-stats"
            };

            srcInfo = Gdal.GDALInfo(datasource, new GDALInfoOptions(infoOptions.ToArray()));

            //OSGeo.OSR.SpatialReference sr = new SpatialReference(ds.GetProjection());
            OSGeo.OSR.SpatialReference dst = new OSGeo.OSR.SpatialReference("");
            dst.SetWellKnownGeogCS("WGS84");
            OSGeo.OSR.CoordinateTransformation coordTransform = new OSGeo.OSR.CoordinateTransformation(sr, dst);
            OSGeo.OSR.CoordinateTransformation revTransform   = new OSGeo.OSR.CoordinateTransformation(dst, sr);

            double[] adfGeoTransform = new double[6];
            double[] invTransform    = new double[6];
            datasource.GetGeoTransform(adfGeoTransform);
            Gdal.InvGeoTransform(adfGeoTransform, invTransform);
            Band band = datasource.GetRasterBand(1);

            int width  = datasource.RasterXSize;
            int height = datasource.RasterYSize;

            ///Dataset bounding box
            double oX = adfGeoTransform[0] + adfGeoTransform[1] * 0 + adfGeoTransform[2] * 0;
            double oY = adfGeoTransform[3] + adfGeoTransform[4] * 0 + adfGeoTransform[5] * 0;
            double eX = adfGeoTransform[0] + adfGeoTransform[1] * width + adfGeoTransform[2] * height;
            double eY = adfGeoTransform[3] + adfGeoTransform[4] * width + adfGeoTransform[5] * height;

            ///Transform to WGS84.
            ///TODO: Allow for UserSRS
            double[] extMinPT = new double[3] {
                oX, eY, 0
            };
            double[] extMaxPT = new double[3] {
                eX, oY, 0
            };
            coordTransform.TransformPoint(extMinPT);
            coordTransform.TransformPoint(extMaxPT);
            Point3d dsMin = new Point3d(extMinPT[0], extMinPT[1], extMinPT[2]);
            Point3d dsMax = new Point3d(extMaxPT[0], extMaxPT[1], extMaxPT[2]);

            ///Get bounding box for entire raster data
            Rectangle3d datasourceBBox = new Rectangle3d(Plane.WorldXY, Heron.Convert.WGSToXYZ(dsMin), Heron.Convert.WGSToXYZ(dsMax));


            ///https://gis.stackexchange.com/questions/312440/gdal-translate-bilinear-interpolation
            ///set output to georeferenced tiff as a catch-all

            string clippedRasterFile = clippedLocation + Path.GetFileNameWithoutExtension(sourceFileLocation) + "_clipped.tif";
            string previewPNG        = clippedLocation + Path.GetFileNameWithoutExtension(sourceFileLocation) + "_preview.png";

            if (sourceFileLocation.Contains("http"))
            {
                previewPNG        = clippedLocation + "ImportRaster_preview.png";
                clippedRasterFile = clippedLocation + "ImportRaster_clipped.tif";
            }

            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Original Resolution: " + datasource.RasterXSize.ToString() + "x" + datasource.RasterYSize.ToString());

            if (boundary != null)
            {
                Point3d clipperMin = Heron.Convert.XYZToWGS(boundary.GetBoundingBox(true).Corner(true, false, true));
                Point3d clipperMax = Heron.Convert.XYZToWGS(boundary.GetBoundingBox(true).Corner(false, true, true));

                double lonWest  = clipperMin.X;
                double lonEast  = clipperMax.X;
                double latNorth = clipperMin.Y;
                double latSouth = clipperMax.Y;

                ///GDALTranslate should also be its own component with full control over options
                var translateOptions = new[]
                {
                    "-of", "GTiff",
                    //"-a_nodata", "0",
                    "-projwin_srs", "WGS84",
                    "-projwin", $"{lonWest}", $"{latNorth}", $"{lonEast}", $"{latSouth}"
                };

                using (Dataset clippedDataset = Gdal.wrapper_GDALTranslate(clippedRasterFile, datasource, new GDALTranslateOptions(translateOptions), null, null))
                {
                    Dataset previewDataset = Gdal.wrapper_GDALTranslate(previewPNG, clippedDataset, null, null, null);

                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Clipped Resolution: " + clippedDataset.RasterXSize.ToString() + "x" + datasource.RasterYSize.ToString());

                    ///clean up
                    clippedDataset.FlushCache();
                    clippedDataset.Dispose();
                    previewDataset.FlushCache();
                    previewDataset.Dispose();

                    AddPreviewItem(previewPNG, BBoxToRect(boundary.GetBoundingBox(true)));
                }
            }

            else
            {
                Dataset previewDataset = Gdal.wrapper_GDALTranslate(previewPNG, datasource, null, null, null);

                ///clean up
                previewDataset.FlushCache();
                previewDataset.Dispose();

                AddPreviewItem(previewPNG, datasourceBBox);
            }

            ///clean up
            datasource.FlushCache();
            datasource.Dispose();

            DA.SetData(0, srcInfo);
            DA.SetData(1, datasourceBBox);
            DA.SetData(2, clippedRasterFile);
        }
Example #51
0
        /// <summary>Construct find place sample control</summary>
        public FindPlace()
        {
            InitializeComponent();
            MyMapView.Map.InitialViewpoint = new Viewpoint(new Envelope(-74.2311, 4.47791, -73.964, 4.8648, SpatialReference.Create(4326)));

            _addressOverlay = MyMapView.GraphicsOverlays[0];;

            _locatorTask = new OnlineLocatorTask(new Uri(OnlineLocatorUrl));
            _locatorTask.AutoNormalize = true;

            listResults.ItemsSource = _addressOverlay.Graphics;

            SetSimpleRendererSymbols();
        }
 public LocationDisplay()
 {
     this.InitializeComponent();
     MyMapView.Map.InitialViewpoint  = new Viewpoint(new Envelope(-344448.8744537411, -1182136.4258723476, 3641336.505047027, 1471520.6499406511, SpatialReference.Create(21897)));
     autoPanModeSelector.ItemsSource = Enum.GetValues(typeof(AutoPanMode));
 }
        public override void CreateLayerAsync(Resource layerResource, SpatialReference mapSpatialReference, object userState)
        {
            if (layerResource.ResourceType == ResourceType.DatabaseTable)
            {
                featureService = new FeatureService(layerResource.Url);
                featureService.GetFeatureServiceDetailsFailed += (o, e) =>
                {
                    OnCreateLayerFailed(e);
                };
                featureService.GetFeatureServiceDetailsCompleted += (o, e) =>
                {
                    if (e.FeatureServiceInfo == null)
                    {
                        OnCreateLayerFailed(new ESRI.ArcGIS.Mapping.Core.ExceptionEventArgs(new Exception(Resources.Strings.ExceptionUnableToRetrieveLayerDetails), e.UserState));
                        return;
                    }
                    GeometryType GeometryType = GeometryType.Unknown;
                    switch (e.FeatureServiceInfo.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 = featureService.Uri,
                        ID = Guid.NewGuid().ToString("N"),
                        Mode = FeatureLayer.QueryMode.OnDemand,
                        Renderer = new ESRI.ArcGIS.Mapping.Core.Symbols.HiddenRenderer()
                    };        
                    newFeatureLayer.SetValue(MapApplication.LayerNameProperty, layerResource.DisplayName);
                    newFeatureLayer.SetValue(Core.LayerExtensions.GeometryTypeProperty, GeometryType);
                    newFeatureLayer.SetValue(Core.LayerExtensions.DisplayUrlProperty, layerResource.Url);

                    if (e.FeatureServiceInfo.Fields != null)
                    {
                        Collection<FieldInfo> fields = new Collection<FieldInfo>();
                        foreach (Field field in e.FeatureServiceInfo.Fields)
                        {
                            if (field.DataType == "Microsoft.SqlServer.Types.SqlGeometry" || field.DataType == "esriFieldTypeGeometry")
                                continue;
                            fields.Add(new FieldInfo()
                            {
                                DisplayName = field.Name,
                                FieldType = mapFieldType(field.DataType),
                                Name = field.Name,
                                VisibleInAttributeDisplay = true,
                                VisibleOnMapTip = true,
                            });
                        }
                        newFeatureLayer.SetValue(Core.LayerExtensions.FieldsProperty, fields);
                    }
                    newFeatureLayer.OutFields.Add("*"); // Get all fields at configuration time
                    OnCreateLayerCompleted(new CreateLayerCompletedEventArgs() { Layer = newFeatureLayer, UserState = e.UserState, GeometryType = GeometryType });
                };
                featureService.GetFeatureServiceDetails(userState);
            }
            else
            {
                OnCreateLayerFailed(new ESRI.ArcGIS.Mapping.Core.ExceptionEventArgs(new Exception(string.Format(Resources.Strings.ExceptionCannotCreateLayerForResourceType, layerResource.ResourceType.ToString())), userState));
            }
        }
        /// <summary>
        /// Create a feature class
        /// </summary>
        /// <param name="dataset">Name of the feature class to be created.</param>
        /// <param name="featureclassType">Type of feature class to be created. Options are:
        /// <list type="bullet">
        /// <item>POINT</item>
        /// <item>MULTIPOINT</item>
        /// <item>POLYLINE</item>
        /// <item>POLYGON</item></list></param>
        /// <param name="connection">connection path</param>
        /// <param name="spatialRef">SpatialReference</param>
        /// <param name="graphicsList">List of graphics</param>
        /// <param name="mapview">MapView object</param>
        /// <param name="isKML">Is this a kml output</param>
        /// <returns></returns>
        private static async Task CreateFeatureClass(string dataset, GeomType geomType, string connection, SpatialReference spatialRef, List <Graphic> graphicsList, MapView mapview, bool isKML = false)
        {
            try
            {
                string strGeomType = geomType == GeomType.PolyLine ? "POLYLINE" : "POLYGON";

                List <object> arguments = new List <object>();
                // store the results in the geodatabase
                arguments.Add(connection);
                // name of the feature class
                arguments.Add(dataset);
                // type of geometry
                arguments.Add(strGeomType);
                // no template
                arguments.Add("");
                // no m values
                arguments.Add("DISABLED");
                // no z values
                arguments.Add("DISABLED");
                arguments.Add(spatialRef);

                var       valueArray = Geoprocessing.MakeValueArray(arguments.ToArray());
                IGPResult result     = await Geoprocessing.ExecuteToolAsync("CreateFeatureclass_management", valueArray);

                await CreateFeatures(graphicsList);

                if (isKML)
                {
                    await KMLUtils.ConvertLayerToKML(connection, dataset, MapView.Active);

                    // Delete temporary Shapefile
                    string[] extensionNames     = { ".cpg", ".dbf", ".prj", ".shx", ".shp" };
                    string   datasetNoExtension = Path.GetFileNameWithoutExtension(dataset);
                    foreach (string extension in extensionNames)
                    {
                        string shapeFile = Path.Combine(connection, datasetNoExtension + extension);
                        File.Delete(shapeFile);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Example #55
0
        private void CreateNewBaseMapWithSpatialReference(Envelope targetInitialExtent, Envelope targetFullExtent, BaseMapInfo baseMapInfo, SpatialReference targetServiceSpatialReference)
        {
            // Reproject oldMap's extent before comparison
            GeometryServiceOperationHelper geomHelper = new GeometryServiceOperationHelper(
                            new ConfigurationStoreHelper().GetGeometryServiceUrl(ConfigurationStore),
                            baseMapInfo.UseProxy ? baseMapInfo.ProxyUrl : null);
            geomHelper.GeometryServiceOperationFailed += (o, args) =>
            {
                Logger.Instance.LogError(args.Exception);
                MessageBoxDialog.Show(ESRI.ArcGIS.Mapping.Controls.Resources.Strings.MsgUnableToAccessGeometryService + Environment.NewLine + args.Exception != null ? args.Exception.Message : ESRI.ArcGIS.Mapping.Controls.Resources.Strings.MsgUnknownError);
            };
            geomHelper.ProjectExtentCompleted += (o, args) =>
            {
                Envelope targetExtent = null;
                // If the extents (compared in same projection) interesect, set the extent of the new map to the projected extent
                if (targetInitialExtent != null)
                {
                    if (args.Extent.Intersects(targetInitialExtent))
                    {
                        if (isFullyContainedWithin(args.Extent, targetInitialExtent))
                            targetExtent = targetFullExtent; // if the full extent of the new service is fully within, automatically zoom to it
                        else
                            targetExtent = args.Extent;
                    }
                    else
                        targetExtent = targetInitialExtent;
                }
                else if (targetFullExtent != null)
                {
                    if (args.Extent.Intersects(targetFullExtent))
                    {
                        if (isFullyContainedWithin(args.Extent, targetFullExtent))
                            targetExtent = targetFullExtent; // if the full extent of the new service is fully within, automatically zoom to it
                        else
                            targetExtent = args.Extent;
                    }
                    else
                        targetExtent = targetFullExtent;
                }

                // else don't set an extent
                // the map will default to the full extent of the service

                // Since map will not be in a different projection, we have to re-create the map
                BaseMapInfo targetBaseMapInfo = baseMapInfo;
                IBaseMapDataSource dataSoure = DataSourceProvider.CreateDataSourceForBaseMapType(targetBaseMapInfo.BaseMapType) as IBaseMapDataSource;
                if (dataSoure == null)
                    throw new Exception(string.Format(ESRI.ArcGIS.Mapping.Controls.Resources.Strings.ExceptionDatasourceNotLoadedForBaseMapType, targetBaseMapInfo.BaseMapType.ToString()));
                TiledMapServiceLayer layer = dataSoure.CreateBaseMapLayer(targetBaseMapInfo);
                layer.SetValue(ESRI.ArcGIS.Client.WebMap.Document.IsBaseMapProperty, true);
                layer.SetValue(ESRI.ArcGIS.Client.Extensibility.MapApplication.LayerNameProperty, targetBaseMapInfo.DisplayName);
                checkAndEnsureBingMapsTokenIfRequired(layer);

                // Save current selected layer
                Layer currentSelectedLayer = SelectedLayer;

                saveGraphicsInViewForSelectedLayerInAttributeDisplay();

                // Disable listening for layer changed events because we are re-adding layers to the collection. The initialization events are not fired nor is symbology changed
                Map.Layers.CollectionChanged -= Layers_CollectionChanged;

                List<Layer> oldBaseMapLayers = new List<Layer>();
                foreach (Layer l in Map.Layers)
                {
                    if ((bool)l.GetValue(ESRI.ArcGIS.Client.WebMap.Document.IsBaseMapProperty))
                        oldBaseMapLayers.Add(l);
                }

                switchBaseMapLayer(layer, targetExtent, oldBaseMapLayers);

                // Re-Enable listening for layer changed events
                Map.Layers.CollectionChanged += Layers_CollectionChanged;

                // Restore current selected layer
                SelectedLayer = currentSelectedLayer;

                restoreGraphicsInViewForSelectedLayerInAttributeDisplay();

                OnNewMapCreated(new MapRecreatedEventArgs() { NewMap = Map });
                OnBaseMapChangeComplete(EventArgs.Empty);
            };
            geomHelper.ProjectExtent(Map.Extent, targetServiceSpatialReference);
        }
        /// <summary>
        /// Creates the output featureclass, either fgdb featureclass or shapefile
        /// </summary>
        /// <param name="outputPath">location of featureclass</param>
        /// <param name="saveAsType">Type of output selected, either fgdb featureclass or shapefile</param>
        /// <param name="graphicsList">List of graphics for selected tab</param>
        /// <param name="ipSpatialRef">Spatial Reference being used</param>
        /// <returns>Output featureclass</returns>
        public async Task CreateFCOutput(string outputPath, SaveAsType saveAsType, List <Graphic> graphicsList, SpatialReference spatialRef, MapView mapview, GeomType geomType, bool isKML = false)
        {
            string dataset    = System.IO.Path.GetFileName(outputPath);
            string connection = System.IO.Path.GetDirectoryName(outputPath);

            try
            {
                await QueuedTask.Run(async() =>
                {
                    await CreateFeatureClass(dataset, geomType, connection, spatialRef, graphicsList, mapview, isKML);
                });
            }
            catch (Exception ex)
            {
            }
        }
        private RecordSet ProjectRecordSetCarefully(Envelope env, RecordSet rs, int geomFieldIndex, SpatialReference inSR, SpatialReference outSR)
        {
            if (geomFieldIndex < 0)
            {
                return(null);
            }
            if (rs == null)
            {
                return(null);
            }
            if (inSR == null || outSR == null)
            {
                return(null);
            }
            int       num  = 0;
            int       num2 = 0;
            int       num3 = 150;
            RecordSet result;

            try
            {
                List <Geometry> list    = new List <Geometry>(num3);
                Record[]        records = rs.Records;
                for (int i = 0; i < records.Length; i++)
                {
                    Record   record   = records[i];
                    Geometry geometry = record.Values[geomFieldIndex] as Geometry;
                    if (geometry != null)
                    {
                        list.Add(geometry);
                        num2++;
                        if (num2 == num + num3)
                        {
                            Geometry[] array  = this._GeomServer.Project(inSR, outSR, true, null, env, list.ToArray());
                            Geometry[] array2 = array;
                            for (int j = 0; j < array2.Length; j++)
                            {
                                Geometry geometry2 = array2[j];
                                rs.Records[num++].Values[geomFieldIndex] = geometry2;
                            }
                            list.Clear();
                        }
                    }
                }
                if (list.Count > 0)
                {
                    Geometry[] array3 = this._GeomServer.Project(inSR, outSR, true, null, env, list.ToArray());
                    Geometry[] array4 = array3;
                    for (int k = 0; k < array4.Length; k++)
                    {
                        Geometry geometry3 = array4[k];
                        rs.Records[num++].Values[geomFieldIndex] = geometry3;
                    }
                    list.Clear();
                }
                result = rs;
            }
            catch (Exception)
            {
                result = null;
            }
            return(result);
        }
        private void addToMap(GPFeatureRecordSetLayer result, ParameterConfig config)
        {
            if (result == null)
            {
                return;
            }

            SpatialReference sr = Map.SpatialReference.Clone();

            ESRI.ArcGIS.Mapping.Core.GeometryType geomType = Core.GeometryType.Unknown;
            FeatureLayerParameterConfig           flConfig = config as FeatureLayerParameterConfig;

            foreach (Graphic item in result.FeatureSet.Features)
            {
                if (item.Geometry != null)
                {
                    item.Geometry.SpatialReference = sr;
                    if (geomType == Core.GeometryType.Unknown)
                    {
                        if (item.Geometry is MapPoint)
                        {
                            geomType = Core.GeometryType.Point;
                        }
                        else if (item.Geometry is MultiPoint)
                        {
                            geomType = Core.GeometryType.MultiPoint;
                        }
                        else if (item.Geometry is ESRI.ArcGIS.Client.Geometry.Polygon)
                        {
                            geomType = Core.GeometryType.Polygon;
                        }
                        else if (item.Geometry is ESRI.ArcGIS.Client.Geometry.Polyline)
                        {
                            geomType = Core.GeometryType.Polyline;
                        }
                    }
                    if (flConfig != null && flConfig.DoubleFields != null && flConfig.DoubleFields.Length > 0)
                    {
                        foreach (string name in flConfig.DoubleFields)
                        {
                            if (item.Attributes.ContainsKey(name) && item.Attributes[name] != null &&
                                (!(item.Attributes[name] is double)))
                            {
                                double d;
                                if (double.TryParse(item.Attributes[name].ToString(), System.Globalization.NumberStyles.Any, CultureHelper.GetCurrentCulture(), out d))
                                {
                                    item.Attributes[name] = d;
                                }
                            }
                        }
                    }
                    if (flConfig != null && flConfig.SingleFields != null && flConfig.SingleFields.Length > 0)
                    {
                        foreach (string name in flConfig.SingleFields)
                        {
                            if (item.Attributes.ContainsKey(name) && item.Attributes[name] != null &&
                                (!(item.Attributes[name] is Single)))
                            {
                                Single s;
                                if (Single.TryParse(item.Attributes[name].ToString(), out s))
                                {
                                    item.Attributes[name] = s;
                                }
                            }
                        }
                    }
                }
            }
            GraphicsLayer layer = GraphicsLayer.FromGraphics(result.FeatureSet.Features, new SimpleRenderer());

            if (flConfig != null)
            {
                if (flConfig.GeometryType == geomType)
                {
                    layer.Renderer = flConfig.Layer.Renderer;
                }
                else
                {
                    layer.Renderer = FeatureLayerParameterConfig.GetSimpleRenderer(geomType);
                }

                setLayerProps(config, layer);
                if (flConfig.Layer != null)
                {
                    Core.LayerExtensions.SetFields(layer, Core.LayerExtensions.GetFields(flConfig.Layer));
                    Core.LayerExtensions.SetDisplayField(layer, Core.LayerExtensions.GetDisplayField(flConfig.Layer));
                    Core.LayerExtensions.SetGeometryType(layer, Core.LayerExtensions.GetGeometryType(flConfig.Layer));

                    // Set whether pop-ups are enabled and whether to show them on click or on hover
                    LayerProperties.SetIsPopupEnabled(layer, LayerProperties.GetIsPopupEnabled(flConfig.Layer));
                    Core.LayerExtensions.SetPopUpsOnClick(layer, Core.LayerExtensions.GetPopUpsOnClick(flConfig.Layer));
                }
            }

            GraphicsLayerTypeFixer.CorrectDataTypes(layer.Graphics, layer);

            Map.Layers.Add(layer);
            layerParamNameIDLookup.Add(config.Name, layer.ID);
        }
        void findNearbyToolWindow_FindNearby(object sender, FindNearbyEventArgs e)
        {
            if (Layer == null)
                return;

            GraphicsLayer graphicsLayer = Layer as GraphicsLayer;
            if (graphicsLayer == null)
                return;

            if (graphicsLayer.SelectionCount < 1)
            {
                findNearbyToolWindow.StopBusyIndicator();
                MessageBoxDialog.Show(Resources.Strings.MsgNoFeaturesSelected, Resources.Strings.ErrorCaption, MessageBoxButton.OK);
                return;
            }

            BufferParameters bufferParams = new BufferParameters();
            switch (e.LinearUnit)
            {
                case LinearUnit.Miles:
                    bufferParams.Unit = ESRI.ArcGIS.Client.Tasks.LinearUnit.StatuteMile;
                    break;
                case LinearUnit.Meters:
                    bufferParams.Unit = ESRI.ArcGIS.Client.Tasks.LinearUnit.Meter;
                    break;
                case LinearUnit.Kilometers:
                    bufferParams.Unit = ESRI.ArcGIS.Client.Tasks.LinearUnit.Kilometer;
                    break;
            }
            bufferParams.UnionResults = true;
            bufferParams.OutSpatialReference = Map.SpatialReference;
            SpatialReference gcs = new SpatialReference(4326);
            bufferParams.BufferSpatialReference = gcs;
            bufferParams.Geodesic = true;
            bufferParams.Distances.Add(e.Distance);

            // Check the spatial reference of the first graphic
            Graphic firstGraphic = graphicsLayer.SelectedGraphics.ElementAt(0);
            bool isInGcs = firstGraphic.Geometry != null
                             && firstGraphic.Geometry.SpatialReference != null
                             && firstGraphic.Geometry.SpatialReference.Equals(gcs);

            // In order to perform geodesic buffering we need to pass geometries in GCS to the geom service
            if (isInGcs)
            {
                foreach (Graphic selectedGraphic in graphicsLayer.SelectedGraphics)
                    bufferParams.Features.Add(selectedGraphic);

                buffer(GeometryServiceUrl, bufferParams, e);
            }
            else
            {
                GeometryServiceOperationHelper helper = new GeometryServiceOperationHelper(GeometryServiceUrl);
                helper.ProjectGraphicsCompleted += (o, args) => {
                    foreach (Graphic selectedGraphic in args.Graphics)
                        bufferParams.Features.Add(selectedGraphic);
                    buffer(GeometryServiceUrl, bufferParams, e);
                };
                helper.ProjectGraphics(graphicsLayer.SelectedGraphics.ToList(), new SpatialReference(4326));
            }
        }        
        }   // end MainWindow

        /// <summary>
        /// Open WMS service and store the list of imagery
        /// perserving heirarchy, if any
        /// Source: Runtime wms Service catalog
        /// MOD - pass in serviceurl
        /// </summary>
        private async void InitializeWMSLayer_VM()
        {
            // Initialize the display with a basemap
            // BasemapView is UI esri mapview name in XAML
            // Reset Map projection if applicable
            Map myMap = new Map(SpatialReference.Create(4326));

            baseImageLayer = new ArcGISMapImageLayer(new Uri(
                                                         "https://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer"));

            // Add baseImageLayer to the Map
            myMap.OperationalLayers.Add(baseImageLayer);

            // Assign the map to the MapView
            BasemapView.Map = myMap;

            // Create the WMS Service Load data from the URI
            // Create WMS Service service with default uri
            serviceURI = new Uri(wmsUriStartup.capableUri);
            serviceWMS = new WmsService(serviceURI);

            // If service can load, initialize the app
            try
            {
                // Load the WMS Service.
                await serviceWMS.LoadAsync();

                // Get the service info (metadata) from the service.
                WmsServiceInfo info = serviceWMS.ServiceInfo;

                // Process info to get information for all the layers
                // for the given serviceUri
                // LayerInfos gets a list of sublayers for a given layer
                foreach (var layerInfo in info.LayerInfos)
                {
                    LayerInfoVM.BuildLayerInfoList(new LayerInfoVM(layerInfo, null, false), _layerInfoOC);
                }


                // Sort Layers
                // This sorts list but list does not get passed to Itemsource

                /*
                 * List<WmsLayerInfo> sortedWmsInfo = new List<WmsLayerInfo>();
                 * ObservableCollection<LayerInfoVM> SortedList = new ObservableCollection<LayerInfoVM>( _layerInfoOC.OrderBy(o => o.Info.Title).ToList())
                 * _layerInfoOC = new ObservableCollection<LayerInfoVM>(SortedList);
                 * foreach (LayerInfoVM layerInfo in _layerInfoOC)
                 *  Debug.WriteLine(layerInfo.Info.Title + "  " + layerInfo.Info.Name);
                 * Debug.WriteLine("Counts: " + _layerInfoOC.Count + "  " + SortedList.Count);
                 */

                // Update the map display based on the viewModel.
                UpdateViewModel(_layerInfoOC);

                // Update UI element
                ProductLabel.Content = "NASA GIBS - " + wmsUriStartup.EPSG + " - "
                                       + wmsUriStartup.latency;
                ProductTreeView.ItemsSource = _layerInfoOC.Take(1);
            }   // end try
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "WMS SERVER LOAD ERROR");
            }
        }   // end InitializeWMSLayer_VM