/// <summary> /// Zooms the map to fit a bounding box /// </summary> /// <remarks> /// NOTE: If the aspect ratio of the box and the aspect ratio of the mapsize /// isn't the same, the resulting map-envelope will be adjusted so that it contains /// the bounding box, thus making the resulting envelope larger! /// </remarks> /// <param name="bbox"></param> public void ZoomToBox(Envelope bbox) { if (bbox != null && !bbox.IsNull) { //Ensure aspect ratio var resX = Size.Width == 0 ? double.MaxValue : bbox.Width / Size.Width; var resY = Size.Height == 0 ? double.MaxValue : bbox.Height / Size.Height; var zoom = bbox.Width; if (resY > resX && resX > 0) { zoom *= resY / resX; } var center = new Coordinate(bbox.Centre); zoom = _mapViewportGuard.VerifyZoom(zoom, center); var changed = false; if (zoom != _zoom) { _zoom = zoom; changed = true; } if (!center.Equals2D(_center)) { _center = center; changed = true; } if (changed && MapViewOnChange != null) { MapViewOnChange(); } } }
/// <summary> /// Converts screen x/y coordinates to latitude/longitude on the map. /// Note that x/y must be relative to the GtkImage (image)'s GdkWindow. /// </summary> /// <param name="x">X coordinate.</param> /// <param name="y">Y coordinate.</param> /// <param name="lat">Latitude.</param> /// <param name="lon">Longitude.</param> private void CartesianToGeoCoords(double x, double y, out double lat, out double lon) { Coordinate coord = map.ImageToWorld(new PointF((float)x, (float)y), true); lat = coord.Y; lon = coord.X; }
/// <summary> /// Changes the view center and zoom level. /// </summary> /// <param name="center">The center.</param> /// <param name="zoom">The zoom level.</param> public void ChangeView(Point center, double zoom) { var newZoom = zoom; var newCenter = center; newZoom = _mapViewportGuard.VerifyZoom(newZoom, newCenter); var changed = false; if (Math.Abs(newZoom - _zoom) > PRECISION_TOLERANCE) { _zoom = newZoom; changed = true; } if (!newCenter.Equals2D(_center, PRECISION_TOLERANCE)) { _center = newCenter; changed = true; } if (changed) { ViewChanged(); OnMapViewChanged(); } }
private void mp_MouseDown(GeoAPI.Geometries.Coordinate WorldPos, MouseEventArgs ImagePos) { FeatureDataSet selected = new FeatureDataSet(); Envelope boundingBox = new Envelope(WorldPos); boundingBox.ExpandBy(0.01); FeatureDataSet sel = new FeatureDataSet(); Envelope b = new Envelope(WorldPos); b.ExpandBy(1); Cquartier.DataSource.ExecuteIntersectionQuery(boundingBox, selected); Cantenne.DataSource.ExecuteIntersectionQuery(b, sel); if (sel.Tables[0].Count == 0) { return; } Text = sel.Tables[0].Rows[0]["num"].ToString(); this.CoucheSelected.DataSource = new GeometryProvider(sel.Tables[0]); mapImage1.Map.Layers.Add(this.CoucheSelected); buffer_select(Int32.Parse(Text)); mapImage1.Refresh(); }
/// <summary> /// Initializes a new map /// </summary> /// <param name="size">Size of map in pixels</param> public Map(Size size) { _mapViewportGuard = new MapViewPortGuard(size, 0d, double.MaxValue); if (LicenseManager.UsageMode != LicenseUsageMode.Designtime) { Factory = GeoAPI.GeometryServiceProvider.Instance.CreateGeometryFactory(_srid); } _layers = new LayerCollection(); _layersPerGroup.Add(_layers, new List <ILayer>()); _backgroundLayers = new LayerCollection(); _layersPerGroup.Add(_backgroundLayers, new List <ILayer>()); BackColor = Color.Transparent; _mapTransform = new Matrix(); _mapTransformInverted = new Matrix(); _center = new Point(0, 0); _zoom = 1; WireEvents(); if (_logger.IsDebugEnabled) { _logger.DebugFormat("Map initialized with size {0},{1}", size.Width, size.Height); } }
/// <summary> /// 鼠标拖动时触发 /// </summary> /// <param name="worldPos"></param> /// <param name="imagePos"></param> private void mapBox_MouseDrag(GeoAPI.Geometries.Coordinate worldPos, MouseEventArgs imagePos) { if (MapMouseDrag != null) { MapMouseDrag(); } }
private void 测试9交模型ToolStripMenuItem_Click(object sender, EventArgs e) { NetTopologySuite.Geometries.GeometryFactory geoFactory = new GeometryFactory(); Coordinate[] cood01 = new Coordinate[4]; cood01[0] = new Coordinate(0, 0); cood01[1] = new Coordinate(10, 10); cood01[2] = new Coordinate(10, 0); cood01[3] = cood01[0]; Coordinate[] cood02 = new Coordinate[4]; cood02[0] = new Coordinate(0, 0); cood02[1] = new Coordinate(10, 10); cood02[2] = new Coordinate(10, 0); cood02[3] = cood02[0]; IPolygon p1 = geoFactory.CreatePolygon(cood01); IPolygon p2 = geoFactory.CreatePolygon(cood02); IGeometry diff = p1.Difference(p2); for (int i = 0; i < diff.Coordinates.Length; i++) { Debug.WriteLine("X:{0} Y:{1}", diff.Coordinates[i].X, diff.Coordinates[i].Y); } IGeometry intersection = p1.Intersection(p2); for (int i = 0; i < intersection.Coordinates.Length; i++) { Debug.WriteLine("X:{0} Y:{1}", intersection.Coordinates[i].X, intersection.Coordinates[i].Y); } }
public void WriteToNTS() { if (vectLocations.Contains(new Vector3(0, 0, 0))) { return; } if (vertexSelector.lineFeatures.Contains(feature)) { attribute["Title"] = title.GetComponent <TMP_InputField>().text; attribute["Description"] = description.GetComponent <TMP_InputField>().text; feature.Attributes = attribute; } else { attribute.Add("Title", title.GetComponent <TMP_InputField>().text); attribute.Add("Description", description.GetComponent <TMP_InputField>().text); feature.Attributes = attribute; GeoAPI.Geometries.Coordinate[] coord = new GeoAPI.Geometries.Coordinate[vectLocations.Count]; int i = 0; foreach (Vector3 v in vectLocations) { var cartesianCoordinates = new Cognitics.CoordinateSystems.CartesianCoordinates(v.x, v.z); var geographicCoordinates = cartesianCoordinates.TransformedWith(cdbDatabase.Projection); coord[i] = new GeoAPI.Geometries.Coordinate(geographicCoordinates.Longitude, geographicCoordinates.Latitude, v.y); ++i; } LineString ls = new LineString(coord); feature.Geometry = ls; vertexSelector.lineFeatures.Add(feature); } ClearFields(); }
private void 绘制ToolStripMenuItem_Click(object sender, EventArgs e) { FeatureDataTable fdt = new FeatureDataTable(); fdt.Columns.Add("FID", typeof(int)); fdt.Columns.Add("Rotation", typeof(double)); GeometryFactory geoFactory = new GeometryFactory(); Coordinate[] lineCoord01 = new Coordinate[] { new Coordinate(0, 0), new Coordinate(10, 10), new Coordinate(20, 20), new Coordinate(0, 0) }; Coordinate[] lineCoord02 = new Coordinate[] { new Coordinate(10, 20), new Coordinate(10, 30), new Coordinate(10, 48), new Coordinate(0, 0) }; ILineString line01 = geoFactory.CreateLineString(lineCoord01); ILineString line02 = geoFactory.CreateLineString(lineCoord02); Coordinate[] pCoordinate01 = new Coordinate[] { new Coordinate(0, 0), new Coordinate(10, 10), new Coordinate(20, 20), new Coordinate(0, 0) }; Coordinate[] pCoordinate02 = new Coordinate[] { new Coordinate(10, 20), new Coordinate(10, 30), new Coordinate(10, 48), new Coordinate(10, 20) }; IPolygon polygon01 = geoFactory.CreatePolygon(pCoordinate01); IPolygon polygon02 = geoFactory.CreatePolygon(pCoordinate02); FeatureDataRow fdr = fdt.NewRow(); fdr["FID"] = 3; fdr["Rotation"] = 180; //fdr.Geometry = line01; fdr.Geometry = polygon01; fdt.Rows.Add(fdr); FeatureDataRow fdr02 = fdt.NewRow(); fdr02["FID"] = 7; fdr02["Rotation"] = 270; //fdr02.Geometry = line02; fdr02.Geometry = polygon02; fdt.Rows.Add(fdr02); VectorLayer vlayer = new VectorLayer("1"); vlayer.Style.Fill = new SolidBrush(Color.FromArgb(0, 255, 255, 255)); vlayer.Style.EnableOutline = true; vlayer.DataSource = new SharpMap.Data.Providers.GeometryFeatureProvider(fdt); mbox.Map.Layers.Add(vlayer); LabelLayer llayer = new LabelLayer("lab"); llayer.DataSource = new SharpMap.Data.Providers.GeometryFeatureProvider(fdt); llayer.LabelColumn = "FID"; llayer.Style.Rotation = 0; llayer.RotationColumn = "Rotation"; llayer.Style.IsTextOnPath = false; llayer.Style.Font = new Font("宋体", 25); mbox.Map.Layers.Add(llayer); mbox.Map.ZoomToExtents(); mbox.Refresh(); }
public Point GroundToImage(Point groundPoint) { return(new Point { X = _inverseTransform[0] + _inverseTransform[1] * groundPoint.X + _inverseTransform[2] * groundPoint.Y, Y = _inverseTransform[3] + _inverseTransform[4] * groundPoint.X + _inverseTransform[5] * groundPoint.Y }); }
public void ImageToWorld_DefaultMap_ReturnValue() { Map map = new Map(new Size(500, 200)); map.Center = new Point(23, 34); map.Zoom = 1000; Point p = map.ImageToWorld(new PointF(242.5f, 92)); Assert.AreEqual(new Point(8, 50), p); }
private static void GeneratePoints(IGeometryFactory factory, ICollection <IGeometry> geometry, Random rndGen) { var numPoints = rndGen.Next(10, 100); for (var pointIndex = 0; pointIndex < numPoints; pointIndex++) { var point = new GeoPoint(rndGen.NextDouble() * 1000, rndGen.NextDouble() * 1000); geometry.Add(factory.CreatePoint(point)); } }
public static void EnsureVisible(SharpMap.Map map, GeoAPI.Geometries.Coordinate pt) { const double ensureVisibleRatio = 0.1d; //Get current map envelope var bb = map.Envelope; System.Console.WriteLine(string.Format("Map envelope: {0}", bb)); //Set valid envelope var evbb = bb.Grow(-ensureVisibleRatio * bb.Width, -ensureVisibleRatio * bb.Height); System.Console.WriteLine(string.Format("Valid envelope: {0}", evbb)); //Test if Point is in valid envelope if (evbb.Contains(pt)) { return; } //It is not System.Console.WriteLine(string.Format("Valid envelope does not contain {0}", pt)); //LineString from Map.Center -> to Point var ls = map.Factory.CreateLineString(new[] { evbb.Centre, pt }); System.Console.WriteLine(string.Format("LineString Map.Center -> Point: {0}", ls)); //Setup Linestring from BoundingBox var evbbpts = new [] { evbb.TopLeft(), evbb.TopRight(), evbb.BottomRight(), evbb.BottomLeft(), evbb.TopLeft() }; var evbblinearring = map.Factory.CreateLineString(evbbpts); System.Console.WriteLine(string.Format("Linestring of valid envelope: {0}", evbblinearring)); //// convert geometries to NTS //var ntsevbb = (NetTopologySuite.Geometries.LineString) // SharpMap.Converters.NTS.GeometryConverter.ToNTSGeometry(evbblinearring, gf); //var ntsls = (NetTopologySuite.Geometries.LineString) // SharpMap.Converters.NTS.GeometryConverter.ToNTSGeometry(ls, gf); // Get intersection point var intGeo = evbblinearring.Intersection(ls); var intPt = (NetTopologySuite.Geometries.Point)intGeo; System.Console.WriteLine(string.Format("Intersection point is: {0}", intPt)); //Compute offset var dx = pt.X - intPt.X; var dy = pt.Y - intPt.Y; System.Console.WriteLine(string.Format("Map.Center needs to be shifted by: [{0}, {1}]", dx, dy)); //Set new center Center map.Center = new GeoAPI.Geometries.Coordinate(map.Center.X + dx, map.Center.Y + dy); }
/// <summary> /// Reprojects a GeoPoint to a NetTopologySuite Point in a target Coordinate System /// </summary> public NetTopologySuite.Geometries.Point Reproject(ProjNet.CoordinateSystems.CoordinateSystem targetProjection) { CoordinateSystemFactory coordSystem = new CoordinateSystemFactory(); var transform = new ProjNet.CoordinateSystems.Transformations.CoordinateTransformationFactory(); var reproject = transform.CreateFromCoordinateSystems(this.CoordinateReferenceSystem, targetProjection); var reprojectedPoint = reproject.MathTransform.Transform(new double[2] { this.GeoCoordinate.X, this.GeoCoordinate.Y }); var reprojectedCoord = new GeoAPI.Geometries.Coordinate(reprojectedPoint[0], reprojectedPoint[1]); return(new NetTopologySuite.Geometries.Point(reprojectedCoord)); }
private static GeoAPI.Geometries.ILineString CreateSineLine(GeoAPI.Geometries.Coordinate offset, double scaleY = 100) { var factory = new NetTopologySuite.Geometries.GeometryFactory(); var cs = factory.CoordinateSequenceFactory.Create(181, 2); for (int i = 0; i <= 180; i++) { cs.SetOrdinate(i, GeoAPI.Geometries.Ordinate.X, offset.X + 2 * i); cs.SetOrdinate(i, GeoAPI.Geometries.Ordinate.Y, offset.Y + scaleY * System.Math.Sin(2d * i * System.Math.PI / 180d)); } return(factory.CreateLineString(cs)); }
private void FormMovingObjectOverTileLayer_Load(object sender, EventArgs e) { //Lisbon... #if DotSpatialProjections var mathTransform = LayerTools.Wgs84toGoogleMercator; var geom = GeometryTransform.TransformBox( new Envelope(-9.205626, -9.123736, 38.690993, 38.740837), mathTransform.Source, mathTransform.Target); #else var mathTransform = LayerTools.Wgs84toGoogleMercator.MathTransform; GeoAPI.Geometries.Envelope geom = GeometryTransform.TransformBox( new Envelope(-9.205626, -9.123736, 38.690993, 38.740837), mathTransform); #endif //Google Background TileAsyncLayer layer2 = new TileAsyncLayer(new OsmTileSource(), "TileLayer - OSM"); this.mapBox1.Map.BackgroundLayer.Add(layer2); var gf = new GeometryFactory(new PrecisionModel(), 3857); //Adds a static layer var staticLayer = new VectorLayer("Fixed Marker"); //position = geom.GetCentroid(); var aux = new List<IGeometry>(); aux.Add(gf.CreatePoint(geom.Centre)); staticLayer.Style.Symbol = Resources.PumpSmall; var geoProviderFixed = new SharpMap.Data.Providers.FeatureProvider(aux); staticLayer.DataSource = geoProviderFixed; this.mapBox1.Map.Layers.Add(staticLayer); //Adds a moving variable layer VectorLayer pushPinLayer = new VectorLayer("PushPins"); position = geom.Centre; geos.Add(gf.CreatePoint(position)); pushPinLayer.Style.Symbol = Resources.OutfallSmall; var geoProvider = new SharpMap.Data.Providers.FeatureProvider(geos); pushPinLayer.DataSource = geoProvider; this.mapBox1.Map.VariableLayers.Add(pushPinLayer); this.mapBox1.Map.ZoomToBox(geom); this.mapBox1.Refresh(); }
private void FormMovingObjectOverTileLayer_Load(object sender, EventArgs e) { //Lisbon... var mathTransform = LayerTools.Wgs84toGoogleMercator.MathTransform; GeoAPI.Geometries.Envelope geom = GeometryTransform.TransformBox( new Envelope(-9.205626, -9.123736, 38.690993, 38.740837), mathTransform); var map = new SharpMap.Map(); //Google Background TileAsyncLayer layer2 = new TileAsyncLayer(KnownTileSources.Create(KnownTileSource.BingRoads), "TileLayer - Bing"); map.BackgroundLayer.Add(layer2); var gf = new GeometryFactory(new PrecisionModel(), 3857); //Adds a static layer var staticLayer = new VectorLayer("Fixed Marker"); //position = geom.GetCentroid(); var aux = new List <IGeometry>(); aux.Add(gf.CreatePoint(geom.Centre)); staticLayer.Style.Symbol = Resources.PumpSmall; var geoProviderFixed = new SharpMap.Data.Providers.GeometryProvider(aux); staticLayer.DataSource = geoProviderFixed; map.Layers.Add(staticLayer); //Adds a moving variable layer VectorLayer pushPinLayer = new VectorLayer("PushPins"); position = geom.Centre; geos.Add(gf.CreatePoint(position)); pushPinLayer.Style.Symbol = Resources.OutfallSmall; var geoProvider = new SharpMap.Data.Providers.GeometryProvider(geos); pushPinLayer.DataSource = geoProvider; map.VariableLayers.Add(pushPinLayer); map.ZoomToBox(geom); this.mapBox1.Map = map; this.mapBox1.Refresh(); }
protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack) { //Page is post back. Restore center and zoom-values from viewstate Center = (Point)ViewState["mapCenter"]; Zoom = (double)ViewState["mapZoom"]; } else { //This is the initial view of the map. Center = new Point(12, 48); Zoom = 45; //Create the map GenerateMap(); } }
protected void ddlProjection_SelectedIndexChanged(object sender, EventArgs e) { //Transform current view to new coordinate system and zoom to the transformed box string PreviousProj = ViewState["currentProj"].ToString(); string SelectedProj = ddlProjection.SelectedValue; //Points defining the current view Point left = new Point(myMap.Envelope.MinX, myMap.Center.Y); Point right = new Point(myMap.Envelope.MaxX, myMap.Center.Y); Point center = myMap.Center; if (PreviousProj != "Pseudo") { //Transform current view back to geographic coordinates ICoordinateTransformation trans = GetTransform(PreviousProj); left = GeometryTransform.TransformCoordinate(new Point(myMap.Envelope.MinX, myMap.Center.Y), trans.MathTransform.Inverse()); right = GeometryTransform.TransformCoordinate(new Point(myMap.Envelope.MaxX, myMap.Center.Y), trans.MathTransform.Inverse()); center = GeometryTransform.TransformCoordinate(myMap.Center, trans.MathTransform.Inverse()); } //If both PreviousSRID and SelectedSRID are projected coordsys, first transform to geographic if (SelectedProj == "Pseudo") { myMap.Center = center; myMap.Zoom = Math.Abs(right.X - left.X); } else //Project coordinates to new projection { //Transform back to geographic and over to new projection ICoordinateTransformation trans = GetTransform(SelectedProj); left = GeometryTransform.TransformCoordinate(left, trans.MathTransform); right = GeometryTransform.TransformCoordinate(right, trans.MathTransform); center = GeometryTransform.TransformCoordinate(center, trans.MathTransform); myMap.Center = center; myMap.Zoom = Math.Abs(right.X - left.X); var envelopeGcs = GeometryTransform.TransformBox(myMap.Envelope, trans.MathTransform.Inverse()); litEnvelopeLatLong.Text = envelopeGcs.ToString(); } GenerateMap(); }
protected void ddlProjection_SelectedIndexChanged(object sender, EventArgs e) { //Transform current view to new coordinate system and zoom to the transformed box string PreviousProj = ViewState["currentProj"].ToString(); string SelectedProj = ddlProjection.SelectedValue; //Points defining the current view Point left = new Point(myMap.Envelope.MinX, myMap.Center.Y); Point right = new Point(myMap.Envelope.MaxX, myMap.Center.Y); Point center = myMap.Center; if (PreviousProj != "Pseudo") { //Transform current view back to geographic coordinates ICoordinateTransformation trans = GetTransform(PreviousProj); left = GeometryTransform.TransformCoordinate(new Point(myMap.Envelope.MinX, myMap.Center.Y), trans.MathTransform.Inverse()); right = GeometryTransform.TransformCoordinate(new Point(myMap.Envelope.MaxX, myMap.Center.Y), trans.MathTransform.Inverse()); center = GeometryTransform.TransformCoordinate(myMap.Center, trans.MathTransform.Inverse()); } //If both PreviousSRID and SelectedSRID are projected coordsys, first transform to geographic if (SelectedProj == "Pseudo") { myMap.Center = center; myMap.Zoom = Math.Abs(right.X - left.X); } else //Project coordinates to new projection { //Transform back to geographic and over to new projection ICoordinateTransformation trans = GetTransform(SelectedProj); left = GeometryTransform.TransformCoordinate(left, trans.MathTransform); right = GeometryTransform.TransformCoordinate(right, trans.MathTransform); center = GeometryTransform.TransformCoordinate(center, trans.MathTransform); myMap.Center = center; myMap.Zoom = Math.Abs(right.X - left.X); var envelopeGcs = GeometryTransform.TransformBox(myMap.Envelope, trans.MathTransform.Inverse()); litEnvelopeLatLong.Text = envelopeGcs.ToString(); } GenerateMap(); }
//void mapBox1_MouseClick(object sender, MouseEventArgs e) //{ // if (mouseState == "query") // { // GeoAPI.Geometries.Coordinate coord = this.mapBox1.Map.ImageToWorld(new PointF(e.X, e.Y)); // FeatureDataSet ds; // ds = QueryMapByClick(coord); // foreach (DataRow dr in ds.Tables[0].Rows) // { // string s = ""; // for (int i = 0; i < ds.Tables[0].Columns.Count; i++) // { // s = s + dr[i].ToString() + ","; // } // MessageBox.Show(s); // //Console.WriteLine(s); // } // } //} private FeatureDataSet QueryMapByClick(GeoAPI.Geometries.Coordinate coord) { FeatureDataSet ds = new FeatureDataSet(); SharpMap.Layers.VectorLayer vlayer = this.mapBox1.Map.Layers[0] as VectorLayer; if (!vlayer.DataSource.IsOpen) { vlayer.DataSource.Open(); } GeoAPI.Geometries.Envelope env = new GeoAPI.Geometries.Envelope(); env.Init(coord.X - 0.01, coord.X + 0.01, coord.Y - 0.01, coord.Y + 0.01); vlayer.DataSource.ExecuteIntersectionQuery(env, ds); if (ds.Tables.Count > 0) { ShowSelectLayer(ds.Tables[0]); } return(ds); }
private static void GeneratePolygons(IGeometryFactory factory, ICollection <IGeometry> geometry, Random rndGen) { int numPolygons = rndGen.Next(10, 100); for (var polyIndex = 0; polyIndex < numPolygons; polyIndex++) { var vertices = new GeoPoint[5]; var upperLeft = new GeoPoint(rndGen.NextDouble() * 1000, rndGen.NextDouble() * 1000); var sideLength = rndGen.NextDouble() * 50; // Make a square vertices[0] = new GeoPoint(upperLeft.X, upperLeft.Y); vertices[1] = new GeoPoint(upperLeft.X + sideLength, upperLeft.Y); vertices[2] = new GeoPoint(upperLeft.X + sideLength, upperLeft.Y - sideLength); vertices[3] = new GeoPoint(upperLeft.X, upperLeft.Y - sideLength); vertices[4] = upperLeft; geometry.Add(factory.CreatePolygon(factory.CreateLinearRing(vertices), null)); } }
public override void OnMouseDown(GeoAPI.Geometries.Coordinate worldPosition, System.Windows.Forms.MouseEventArgs e) { // Starting a new measurement? if (pointGeometries.Count() >= 2 && Control.ModifierKeys != Keys.Alt) { Clear(); } // Add the newly selected point var point = new GeoPoint(worldPosition); pointLayer.DataSource.Add(point); CalculateDistance(); // Refresh the screen pointLayer.RenderRequired = true; MapControl.Refresh(); // HACK: Why is this needed? (Only RenderRequired = true isn't enough...) base.OnMouseDown(worldPosition, e); }
/// <summary> /// Initializes a new map /// </summary> /// <param name="size">Size of map in pixels</param> public Map(Size size) { _mapViewportGuard = new MapViewPortGuard(size, 0d, Double.MaxValue); Factory = GeoAPI.GeometryServiceProvider.Instance.CreateGeometryFactory(_srid); _layers = new LayerCollection(); _backgroundLayers = new LayerCollection(); _variableLayers = new VariableLayerCollection(_layers); BackColor = Color.Transparent; _mapTransform = new Matrix(); MapTransformInverted = new Matrix(); _center = new Point(0, 0); _zoom = 1; WireEvents(); if (_logger.IsDebugEnabled) { _logger.DebugFormat("Map initialized with size {0},{1}", size.Width, size.Height); } }
private static void GenerateLines(IGeometryFactory factory, ICollection<IGeometry> geometry, Random rndGen) { var numLines = rndGen.Next(10, 100); for (var lineIndex = 0; lineIndex < numLines; lineIndex++) { var numVerticies = rndGen.Next(4, 15); var vertices = new GeoPoint[numVerticies]; var lastPoint = new GeoPoint(rndGen.NextDouble()*1000, rndGen.NextDouble()*1000); vertices[0] = lastPoint; for (var vertexIndex = 1; vertexIndex < numVerticies; vertexIndex++) { var nextPoint = new GeoPoint(lastPoint.X + rndGen.Next(-50, 50), lastPoint.Y + rndGen.Next(-50, 50)); vertices[vertexIndex] = nextPoint; lastPoint = nextPoint; } geometry.Add(factory.CreateLineString(vertices)); } }
protected void imgMap_Click(object sender, ImageClickEventArgs e) { //Set center of the map to where the client clicked //We set up a simple empty map so we can use the ImageToWorld() method for easy conversion from Image to World coordinates Map myMap = new Map(new Size(Convert.ToInt32(imgMap.Width.Value), Convert.ToInt32(imgMap.Height.Value))); myMap.Center = Center; myMap.Zoom = Zoom; Center = myMap.ImageToWorld(new System.Drawing.Point(e.X, e.Y)); //Set zoom value if any of the zoom tools were selected if (rblMapTools.SelectedValue == "0") //Zoom in { Zoom = Zoom * 0.5; } else if (rblMapTools.SelectedValue == "1") //Zoom out { Zoom = Zoom * 2; } //Create the map GenerateMap(); }
private static void GenerateLines(IGeometryFactory factory, ICollection <IGeometry> geometry, Random rndGen) { var numLines = rndGen.Next(10, 100); for (var lineIndex = 0; lineIndex < numLines; lineIndex++) { var numVerticies = rndGen.Next(4, 15); var vertices = new GeoPoint[numVerticies]; var lastPoint = new GeoPoint(rndGen.NextDouble() * 1000, rndGen.NextDouble() * 1000); vertices[0] = lastPoint; for (var vertexIndex = 1; vertexIndex < numVerticies; vertexIndex++) { var nextPoint = new GeoPoint(lastPoint.X + rndGen.Next(-50, 50), lastPoint.Y + rndGen.Next(-50, 50)); vertices[vertexIndex] = nextPoint; lastPoint = nextPoint; } geometry.Add(factory.CreateLineString(vertices)); } }
private void mp_MouseDown(GeoAPI.Geometries.Coordinate worldPos, MouseEventArgs imagePos) { FeatureDataSet selected = new FeatureDataSet(); Envelope boundingBox = new Envelope(worldPos); boundingBox.ExpandBy(0.01); l.DataSource.ExecuteIntersectionQuery(boundingBox, selected); if (selected.Tables[0].Count == 0) { return; } Text = selected.Tables[0].Rows[0]["nom"].ToString(); s.DataSource = new GeometryProvider(selected.Tables[0]); if (mp.Map.FindLayer("s") != null) { mp.Map.Layers.Add(s); } mp.Refresh(); }
private static void GeneratePolygons(IGeometryFactory factory, ICollection<IGeometry> geometry, Random rndGen) { int numPolygons = rndGen.Next(10, 100); for (var polyIndex = 0; polyIndex < numPolygons; polyIndex++) { var vertices = new GeoPoint[5]; var upperLeft = new GeoPoint(rndGen.NextDouble()*1000, rndGen.NextDouble()*1000); var sideLength = rndGen.NextDouble()*50; // Make a square vertices[0] = new GeoPoint(upperLeft.X, upperLeft.Y); vertices[1] = new GeoPoint(upperLeft.X + sideLength, upperLeft.Y); vertices[2] = new GeoPoint(upperLeft.X + sideLength, upperLeft.Y - sideLength); vertices[3] = new GeoPoint(upperLeft.X, upperLeft.Y - sideLength); vertices[4] = upperLeft; geometry.Add(factory.CreatePolygon(factory.CreateLinearRing(vertices), null)); } }
public Point GroundToImage(Point groundPoint) { return new Point { X = _inverseTransform[0] + _inverseTransform[1]*groundPoint.X + _inverseTransform[2]*groundPoint.Y, Y = _inverseTransform[3] + _inverseTransform[4]*groundPoint.X + _inverseTransform[5]*groundPoint.Y }; }
internal static DotSpatial.Topology.Coordinate ToDotSpatialCoordinate(GeoAPI.Geometries.Coordinate coordinate) { return(new DotSpatial.Topology.Coordinate(coordinate.X, coordinate.Y)); }
internal static DotSpatial.Topology.Point ToDotSpatialPoint(GeoAPI.Geometries.Coordinate point) { return(new DotSpatial.Topology.Point(point.X, point.Y)); }
/// <summary> /// Zooms the map to fit a bounding box /// </summary> /// <remarks> /// NOTE: If the aspect ratio of the box and the aspect ratio of the mapsize /// isn't the same, the resulting map-envelope will be adjusted so that it contains /// the bounding box, thus making the resulting envelope larger! /// </remarks> /// <param name="bbox"></param> public void ZoomToBox(Envelope bbox) { if (bbox != null && !bbox.IsNull) { //Ensure aspect ratio var resX = Size.Width == 0 ? double.MaxValue : bbox.Width / Size.Width; var resY = Size.Height == 0 ? double.MaxValue : bbox.Height / Size.Height; var zoom = bbox.Width; if (resY > resX && resX > 0) { zoom *= resY / resX; } var center = new Coordinate(bbox.Centre); zoom = _mapViewportGuard.VerifyZoom(zoom, center); var changed = false; if (zoom != _zoom) { _zoom = zoom; changed = true; } if (!center.Equals2D(_center)) { _center = center; changed = true; } if (changed && MapViewOnChange != null) MapViewOnChange(); } }
/// <summary> /// Converts a point from world coordinates to image coordinates based on the current /// zoom, center and mapsize. /// </summary> /// <param name="p">Point in world coordinates</param> /// <returns>Point in image coordinates</returns> public PointF WorldToImage(Point p) { return WorldToImage(p, false); }
/// <summary> /// Converts a point from world coordinates to image coordinates based on the current /// zoom, center and mapsize. /// </summary> /// <param name="p">Point in world coordinates</param> /// <returns>Point in image coordinates</returns> public PointF WorldToImage(Point p) { return(WorldToImage(p, false)); }
protected virtual void GetPreview(Dataset dataset, Size size, Graphics g, BoundingBox displayBbox, ProjectionInfo mapProjection, Map map) #endif { double[] geoTrans = new double[6]; _gdalDataset.GetGeoTransform(geoTrans); // not rotated, use faster display method if ((!_useRotation || (geoTrans[1] == 1 && geoTrans[2] == 0 && geoTrans[4] == 0 && Math.Abs(geoTrans[5]) == 1)) && !_haveSpot && _transform == null) { GetNonRotatedPreview(dataset, size, g, displayBbox, mapProjection); return; } // not rotated, but has spot...need default rotation else if ((geoTrans[0] == 0 && geoTrans[3] == 0) && _haveSpot) geoTrans = new[] { 999.5, 1, 0, 1000.5, 0, -1 }; _geoTransform = new GeoTransform(geoTrans); double DsWidth = _imagesize.Width; double DsHeight = _imagesize.Height; double left, top, right, bottom; double GndX = 0, GndY = 0, ImgX = 0, ImgY = 0, PixX, PixY; double[] intVal = new double[Bands]; double imageVal = 0, SpotVal = 0; double bitScalar = 1.0; Bitmap bitmap = null; Point bitmapTL = new Point(), bitmapBR = new Point(); GeoPoint imageTL = new GeoPoint(), imageBR = new GeoPoint(); BoundingBox shownImageBbox, trueImageBbox; int bitmapLength, bitmapHeight; int displayImageLength, displayImageHeight; int iPixelSize = 3; //Format24bppRgb = byte[b,g,r] if (dataset != null) { //check if image is in bounding box if ((displayBbox.MinX > _envelope.MaxX) || (displayBbox.MaxX < _envelope.MinX) || (displayBbox.MaxY < _envelope.MinY) || (displayBbox.MinY > _envelope.MaxY)) return; // init histo _histogram = new List<int[]>(); for (int i = 0; i < _lbands + 1; i++) _histogram.Add(new int[256]); // bounds of section of image to be displayed left = Math.Max(displayBbox.MinX, _envelope.MinX); top = Math.Min(displayBbox.MaxY, _envelope.MaxY); right = Math.Min(displayBbox.MaxX, _envelope.MaxX); bottom = Math.Max(displayBbox.MinY, _envelope.MinY); trueImageBbox = new BoundingBox(left, right, bottom, top); // put display bounds into current projection if (_transform != null) { #if !DotSpatialProjections _transform.MathTransform.Invert(); shownImageBbox = GeometryTransform.TransformBox(trueImageBbox, _transform.MathTransform); _transform.MathTransform.Invert(); #else shownImageBbox = GeometryTransform.TransformBox(trueImageBbox, _transform.Source, _transform.Target); #endif } else shownImageBbox = trueImageBbox; // find min/max x and y pixels needed from image imageBR.X = (int) (Math.Max(_geoTransform.GroundToImage(shownImageBbox.TopLeft()).X, Math.Max(_geoTransform.GroundToImage(shownImageBbox.TopRight()).X, Math.Max(_geoTransform.GroundToImage(shownImageBbox.BottomLeft()).X, _geoTransform.GroundToImage(shownImageBbox.BottomRight()).X))) + 1); imageBR.Y = (int) (Math.Max(_geoTransform.GroundToImage(shownImageBbox.TopLeft()).Y, Math.Max(_geoTransform.GroundToImage(shownImageBbox.TopRight()).Y, Math.Max(_geoTransform.GroundToImage(shownImageBbox.BottomLeft()).Y, _geoTransform.GroundToImage(shownImageBbox.BottomRight()).Y))) + 1); imageTL.X = (int) Math.Min(_geoTransform.GroundToImage(shownImageBbox.TopLeft()).X, Math.Min(_geoTransform.GroundToImage(shownImageBbox.TopRight()).X, Math.Min(_geoTransform.GroundToImage(shownImageBbox.BottomLeft()).X, _geoTransform.GroundToImage(shownImageBbox.BottomRight()).X))); imageTL.Y = (int) Math.Min(_geoTransform.GroundToImage(shownImageBbox.TopLeft()).Y, Math.Min(_geoTransform.GroundToImage(shownImageBbox.TopRight()).Y, Math.Min(_geoTransform.GroundToImage(shownImageBbox.BottomLeft()).Y, _geoTransform.GroundToImage(shownImageBbox.BottomRight()).Y))); // stay within image if (imageBR.X > _imagesize.Width) imageBR.X = _imagesize.Width; if (imageBR.Y > _imagesize.Height) imageBR.Y = _imagesize.Height; if (imageTL.Y < 0) imageTL.Y = 0; if (imageTL.X < 0) imageTL.X = 0; displayImageLength = (int)(imageBR.X - imageTL.X); displayImageHeight = (int)(imageBR.Y - imageTL.Y); // find ground coordinates of image pixels var groundBR = _geoTransform.ImageToGround(imageBR); var groundTL = _geoTransform.ImageToGround(imageTL); // convert ground coordinates to map coordinates to figure out where to place the bitmap bitmapBR = new Point((int)map.WorldToImage(trueImageBbox.BottomRight()).X + 1, (int)map.WorldToImage(trueImageBbox.BottomRight()).Y + 1); bitmapTL = new Point((int)map.WorldToImage(trueImageBbox.TopLeft()).X, (int)map.WorldToImage(trueImageBbox.TopLeft()).Y); bitmapLength = bitmapBR.X - bitmapTL.X; bitmapHeight = bitmapBR.Y - bitmapTL.Y; // check to see if image is on its side if (bitmapLength > bitmapHeight && displayImageLength < displayImageHeight) { displayImageLength = bitmapHeight; displayImageHeight = bitmapLength; } else { displayImageLength = bitmapLength; displayImageHeight = bitmapHeight; } // scale if (_bitDepth == 12) bitScalar = 16.0; else if (_bitDepth == 16) bitScalar = 256.0; else if (_bitDepth == 32) bitScalar = 16777216.0; // 0 pixels in length or height, nothing to display if (bitmapLength < 1 || bitmapHeight < 1) return; //initialize bitmap bitmap = new Bitmap(bitmapLength, bitmapHeight, PixelFormat.Format24bppRgb); BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmapLength, bitmapHeight), ImageLockMode.ReadWrite, bitmap.PixelFormat); try { unsafe { // turn everything to _noDataInitColor, so we can make fill transparent byte cr = _noDataInitColor.R; byte cg = _noDataInitColor.G; byte cb = _noDataInitColor.B; for (int y = 0; y < bitmapHeight; y++) { byte* brow = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride); for (int x = 0; x < bitmapLength; x++) { Int32 offsetX = x * 3; brow[offsetX++] = cb; brow[offsetX++] = cg; brow[offsetX] = cr; } } // create 3 dimensional buffer [band][x pixel][y pixel] double[][] tempBuffer = new double[Bands][]; double[][][] buffer = new double[Bands][][]; for (int i = 0; i < Bands; i++) { buffer[i] = new double[displayImageLength][]; for (int j = 0; j < displayImageLength; j++) buffer[i][j] = new double[displayImageHeight]; } Band[] band = new Band[Bands]; int[] ch = new int[Bands]; // Double[] noDataValues = new Double[Bands]; Double[] scales = new Double[Bands]; ColorTable colorTable = null; // get data from image for (int i = 0; i < Bands; i++) { tempBuffer[i] = new double[displayImageLength * displayImageHeight]; band[i] = dataset.GetRasterBand(i + 1); //get nodata value if present Int32 hasVal = 0; band[i].GetNoDataValue(out noDataValues[i], out hasVal); if (hasVal == 0) noDataValues[i] = Double.NaN; band[i].GetScale(out scales[i], out hasVal); if (hasVal == 0) scales[i] = 1.0; band[i].ReadRaster( (int)imageTL.X, (int)imageTL.Y, (int)(imageBR.X - imageTL.X), (int)(imageBR.Y - imageTL.Y), tempBuffer[i], displayImageLength, displayImageHeight, 0, 0); // parse temp buffer into the image x y value buffer long pos = 0; for (int y = 0; y < displayImageHeight; y++) { for (int x = 0; x < displayImageLength; x++, pos++) buffer[i][x][y] = tempBuffer[i][pos]; } if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_BlueBand) ch[i] = 0; else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_GreenBand) ch[i] = 1; else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_RedBand) ch[i] = 2; else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_Undefined) { if (Bands > 1) ch[i] = 3; // infrared else { ch[i] = 4; if (_colorBlend == null) { Double dblMin, dblMax; band[i].GetMinimum(out dblMin, out hasVal); if (hasVal == 0) dblMin = Double.NaN; band[i].GetMaximum(out dblMax, out hasVal); if (hasVal == 0) dblMax = double.NaN; if (Double.IsNaN(dblMin) || Double.IsNaN(dblMax)) { double dblMean, dblStdDev; band[i].GetStatistics(0, 1, out dblMin, out dblMax, out dblMean, out dblStdDev); //double dblRange = dblMax - dblMin; //dblMin -= 0.1*dblRange; //dblMax += 0.1*dblRange; } Single[] minmax = new float[] { Convert.ToSingle(dblMin), 0.5f * Convert.ToSingle(dblMin + dblMax), Convert.ToSingle(dblMax) }; Color[] colors = new Color[] { Color.Blue, Color.Yellow, Color.Red }; _colorBlend = new ColorBlend(colors, minmax); } intVal = new Double[3]; } } else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_GrayIndex) ch[i] = 0; else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_PaletteIndex) { colorTable = band[i].GetRasterColorTable(); ch[i] = 5; intVal = new Double[3]; } else ch[i] = -1; } // store these values to keep from having to make slow method calls int bitmapTLX = bitmapTL.X; int bitmapTLY = bitmapTL.Y; double imageTop = imageTL.Y; double imageLeft = imageTL.X; double dblMapPixelWidth = map.PixelWidth; double dblMapPixelHeight = map.PixelHeight; double dblMapMinX = map.Envelope.MinX; double dblMapMaxY = map.Envelope.MaxY; double geoTop, geoLeft, geoHorzPixRes, geoVertPixRes, geoXRot, geoYRot; // get inverse values geoTop = _geoTransform.Inverse[3]; geoLeft = _geoTransform.Inverse[0]; geoHorzPixRes = _geoTransform.Inverse[1]; geoVertPixRes = _geoTransform.Inverse[5]; geoXRot = _geoTransform.Inverse[2]; geoYRot = _geoTransform.Inverse[4]; double dblXScale = (imageBR.X - imageTL.X) / (displayImageLength - 1); double dblYScale = (imageBR.Y - imageTL.Y) / (displayImageHeight - 1); double[] dblPoint; // get inverse transform // NOTE: calling transform.MathTransform.Inverse() once and storing it // is much faster than having to call every time it is needed #if !DotSpatialProjections IMathTransform inverseTransform = null; if (_transform != null) inverseTransform = _transform.MathTransform.Inverse(); #endif for (PixY = 0; PixY < bitmapBR.Y - bitmapTL.Y; PixY++) { byte* row = (byte*)bitmapData.Scan0 + ((int)Math.Round(PixY) * bitmapData.Stride); for (PixX = 0; PixX < bitmapBR.X - bitmapTL.X; PixX++) { // same as Map.ImageToGround(), but much faster using stored values...rather than called each time GndX = dblMapMinX + (PixX + bitmapTLX) * dblMapPixelWidth; GndY = dblMapMaxY - (PixY + bitmapTLY) * dblMapPixelHeight; // transform ground point if needed if (_transform != null) { #if !DotSpatialProjections dblPoint = inverseTransform.Transform(new[] { GndX, GndY }); #else dblPoint = new double[] { GndX, GndY }; Reproject.ReprojectPoints(dblPoint, null, _transform.Source, _transform.Target, 0, 1); #endif GndX = dblPoint[0]; GndY = dblPoint[1]; } // same as GeoTransform.GroundToImage(), but much faster using stored values... ImgX = (geoLeft + geoHorzPixRes * GndX + geoXRot * GndY); ImgY = (geoTop + geoYRot * GndX + geoVertPixRes * GndY); if (ImgX < imageTL.X || ImgX > imageBR.X || ImgY < imageTL.Y || ImgY > imageBR.Y) continue; // color correction for (int i = 0; i < Bands; i++) { intVal[i] = buffer[i][(int)((ImgX - imageLeft) / dblXScale)][ (int)((ImgY - imageTop) / dblYScale)]; imageVal = SpotVal = intVal[i] = intVal[i] / bitScalar; if (ch[i] == 4) { if (imageVal != noDataValues[i]) { Color color = _colorBlend.GetColor(Convert.ToSingle(imageVal)); intVal[0] = color.B; intVal[1] = color.G; intVal[2] = color.R; //intVal[3] = ce.c4; } else { intVal[0] = cb; intVal[1] = cg; intVal[2] = cr; } } else if (ch[i] == 5 && colorTable != null) { if (imageVal != noDataValues[i]) { ColorEntry ce = colorTable.GetColorEntry(Convert.ToInt32(imageVal)); intVal[0] = ce.c3; intVal[1] = ce.c2; intVal[2] = ce.c1; //intVal[3] = ce.c4; } else { intVal[0] = cb; intVal[1] = cg; intVal[2] = cr; } } else { if (_colorCorrect) { intVal[i] = ApplyColorCorrection(imageVal, SpotVal, ch[i], GndX, GndY); // if pixel is within ground boundary, add its value to the histogram if (ch[i] != -1 && intVal[i] > 0 && (_histoBounds.Bottom >= (int)GndY) && _histoBounds.Top <= (int)GndY && _histoBounds.Left <= (int)GndX && _histoBounds.Right >= (int)GndX) { _histogram[ch[i]][(int)intVal[i]]++; } } if (intVal[i] > 255) intVal[i] = 255; } } // luminosity if (_lbands >= 3) _histogram[_lbands][(int)(intVal[2] * 0.2126 + intVal[1] * 0.7152 + intVal[0] * 0.0722)] ++; WritePixel(PixX, intVal, iPixelSize, ch, row); } } } } finally { bitmap.UnlockBits(bitmapData); } } bitmap.MakeTransparent(_noDataInitColor); if (_transparentColor != Color.Empty) bitmap.MakeTransparent(_transparentColor); g.DrawImage(bitmap, new Point(bitmapTL.X, bitmapTL.Y)); }
private static void GeneratePoints(IGeometryFactory factory, ICollection<IGeometry> geometry, Random rndGen) { var numPoints = rndGen.Next(10, 100); for (var pointIndex = 0; pointIndex < numPoints; pointIndex++) { var point = new GeoPoint(rndGen.NextDouble()*1000, rndGen.NextDouble()*1000); geometry.Add(factory.CreatePoint(point)); } }
private void ExecuteIntersectionQuery(GeoPoint pt, FeatureDataSet ds) { if (CoordinateTransformation != null) { #if !DotSpatialProjections if (ReverseCoordinateTransformation != null) { pt = GeometryTransform.TransformCoordinate(pt, ReverseCoordinateTransformation.MathTransform); } else { CoordinateTransformation.MathTransform.Invert(); pt = GeometryTransform.TransformCoordinate(pt, CoordinateTransformation.MathTransform); CoordinateTransformation.MathTransform.Invert(); } #else pt = GeometryTransform.TransformCoordinate(pt, CoordinateTransformation.Target, CoordinateTransformation.Source); #endif } //Setup resulting Table var dt = new FeatureDataTable(); dt.Columns.Add("Ordinate X", typeof(Double)); dt.Columns.Add("Ordinate Y", typeof(Double)); for (int i = 1; i <= Bands; i++) dt.Columns.Add(string.Format("Value Band {0}", i), typeof(Double)); //Get location on raster Double[] buffer = new double[1]; Int32[] bandMap = new int[Bands]; for (int i = 1; i <= Bands; i++) bandMap[i - 1] = i; var imgPt = _geoTransform.GroundToImage(pt); Int32 x = Convert.ToInt32(imgPt.X); Int32 y = Convert.ToInt32(imgPt.Y); //Test if raster ordinates are within bounds if (x < 0) return; if (y < 0) return; if (x >= _imagesize.Width) return; if (y >= _imagesize.Height) return; //Create new row, add ordinates and location geometry FeatureDataRow dr = dt.NewRow(); dr.Geometry = Factory.CreatePoint(pt); dr[0] = pt.X; dr[1] = pt.Y; //Add data from raster for (int i = 1; i <= Bands; i++) { Band band = _gdalDataset.GetRasterBand(i); //DataType dtype = band.DataType; CPLErr res = band.ReadRaster(x, y, 1, 1, buffer, 1, 1, 0, 0); if (res == CPLErr.CE_None) { dr[1 + i] = buffer[0]; } else { dr[1 + i] = Double.NaN; } } //Add new row to table dt.Rows.Add(dr); //Add table to dataset ds.Tables.Add(dt); }
private void 处理KMLToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); if (ofd.ShowDialog() == DialogResult.OK) { NetTopologySuite.Geometries.GeometryFactory gFactory = new GeometryFactory(); Dictionary <int, FeatureDataTable> fdtDic = new Dictionary <int, FeatureDataTable>(); XmlDocument doc = new XmlDocument(); doc.Load(ofd.FileName); XmlNode root = doc.DocumentElement; string nameUri = root.NamespaceURI; XmlNamespaceManager xnm = new XmlNamespaceManager(doc.NameTable); xnm.AddNamespace("pre", nameUri); XmlNodeList folderName = root.SelectNodes("pre:Document/pre:Folder/pre:Folder/pre:name", xnm); XmlNode oddNode = null; XmlNode evenNode = null; for (int i = 0; i < folderName.Count; i++) { if (folderName[i].InnerText == "odd num") { oddNode = folderName[i].ParentNode; } if (folderName[i].InnerText == "even num") { evenNode = folderName[i].ParentNode; } } XmlNodeList folders_Odd = null; XmlNodeList folders_Even = null; if (oddNode != null) { folders_Odd = oddNode.SelectNodes("pre:Folder", xnm); } if (evenNode != null) { folders_Even = evenNode.SelectNodes("pre:Folder", xnm); } if (folders_Odd != null) { for (int i = 0; i < folders_Odd.Count; i++) { FeatureDataTable srcfdt = null; string flihgtNameStr = folders_Odd[i].SelectSingleNode("pre:name", xnm).InnerText.Trim(); //寻找偶数 XmlNode sameFlightEven = null; if (folders_Even != null) { for (int j = 0; j < folders_Even.Count; j++) { XmlNode flightN = folders_Odd[i].SelectSingleNode("pre:name", xnm); string tempFlightName = flightN.InnerText.Trim(); if (tempFlightName == flihgtNameStr) { sameFlightEven = flightN.ParentNode; } } } XmlNodeList placemarks_Odd = folders_Odd[i].SelectNodes("pre:Placemark", xnm); XmlNodeList placemarks_even = null; if (sameFlightEven != null) { placemarks_even = folders_Even[i].SelectNodes("pre:Placemark", xnm); } string[] flightName = flihgtNameStr.Split(' '); int flihgtId = Convert.ToInt32(flightName[1]); //if (fdtDic.Keys.Contains(flihgtId)) //{ // srcfdt = fdtDic[flihgtId]; //} //else //{ // srcfdt = new FeatureDataTable(); // srcfdt.Columns.Add("FlightId", typeof(int)); // srcfdt.Columns.Add("Name", typeof(string)); // srcfdt.Columns.Add("OverlapCount", typeof(int)); // fdtDic.Add(flihgtId, srcfdt); //} srcfdt = new FeatureDataTable(); srcfdt.Columns.Add("FlightId", typeof(int)); srcfdt.Columns.Add("Name", typeof(string)); srcfdt.Columns.Add("OverlapCount", typeof(int)); fdtDic.Add(flihgtId, srcfdt); for (int k = 0; k < placemarks_Odd.Count; k++) { XmlNode coordinatesN_odd = placemarks_Odd[k].SelectSingleNode("pre:Polygon/pre:outerBoundaryIs/pre:LinearRing/pre:coordinates", xnm); string placemarkName_odd = placemarks_Odd[k].SelectSingleNode("pre:name", xnm).InnerText; string coordinateStr = coordinatesN_odd.InnerText.Trim(); string[] coordinateArry = coordinateStr.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); Coordinate[] coordinates = new Coordinate[coordinateArry.Length]; for (int j = 0; j < coordinateArry.Length; j++) { string[] xyh = coordinateArry[j].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); coordinates[j] = new Coordinate(Convert.ToDouble(xyh[0]), Convert.ToDouble(xyh[1]), Convert.ToDouble(xyh[2])); } if (coordinateArry.Length > 3) { GeoAPI.Geometries.IPolygon polygon = gFactory.CreatePolygon(coordinates); FeatureDataRow fdr = srcfdt.NewRow(); fdr["FlightId"] = flihgtId; Debug.WriteLine(flihgtId); fdr["Name"] = placemarkName_odd; fdr["OverlapCount"] = 0; fdr.Geometry = polygon; srcfdt.AddRow(fdr); } if (placemarks_even != null) { if (k >= placemarks_even.Count) { continue; } XmlNode coordinatesN_even = placemarks_even[k].SelectSingleNode("pre:Polygon/pre:outerBoundaryIs/pre:LinearRing/pre:coordinates", xnm); string placemarkName_even = placemarks_even[k].SelectSingleNode("pre:name", xnm).InnerText; string coordStr = coordinatesN_even.InnerText.Trim(); string[] coordinateA_even = coordStr.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); Coordinate[] coor = new Coordinate[coordinateA_even.Length]; for (int j = 0; j < coordinateA_even.Length; j++) { string[] xyh = coordinateA_even[j].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); coor[j] = new Coordinate(Convert.ToDouble(xyh[0]), Convert.ToDouble(xyh[1]), Convert.ToDouble(xyh[2])); } if (coor.Length > 3) { GeoAPI.Geometries.IPolygon polygon = gFactory.CreatePolygon(coor); FeatureDataRow fdr = srcfdt.NewRow(); fdr["FlightId"] = flihgtId; Debug.WriteLine(flihgtId); fdr["Name"] = placemarkName_even; fdr["OverlapCount"] = 0; fdr.Geometry = polygon; srcfdt.AddRow(fdr); } } } } } //对fdtDic中的所有航线进行旁向重叠计算 int index = 0; foreach (var item in fdtDic.Values) { overlapLR(item); if (++index >= 1) { break; } } FeatureDataTable allfdt = null;//所有的航线都放进来了 if (fdtDic.Count > 0) { foreach (FeatureDataTable item in fdtDic.Values) { if (allfdt == null) { allfdt = new FeatureDataTable(); allfdt.Columns.Add("FlightId", typeof(int)); allfdt.Columns.Add("Name", typeof(string)); allfdt.Columns.Add("OverlapCount", typeof(int)); } foreach (var r in item.Rows) { FeatureDataRow srcFdr = r as FeatureDataRow; FeatureDataRow tempfdr = allfdt.NewRow(); tempfdr["FlightId"] = srcFdr["FlightId"]; tempfdr["Name"] = srcFdr["Name"]; tempfdr["OverlapCount"] = srcFdr["OverlapCount"]; if (Convert.ToInt32(srcFdr["OverlapCount"]) > 0) { Debug.WriteLine(Convert.ToInt32(srcFdr["OverlapCount"])); } tempfdr.Geometry = srcFdr.Geometry; allfdt.Rows.Add(tempfdr); Debug.WriteLine(srcFdr["FlightId"]); Debug.WriteLine(srcFdr["Name"]); Debug.WriteLine(srcFdr["OverlapCount"]); Debug.WriteLine(tempfdr.Geometry.Area); Debug.WriteLine(tempfdr.Geometry); //if (++geolength>20) //{ // break; //} } } VectorStyle overlap0 = new VectorStyle(); overlap0.Fill = new SolidBrush(Color.FromArgb(25, Color.Green)); overlap0.Outline = new Pen(Color.Red, 1.0f); overlap0.EnableOutline = true; VectorStyle overlap2 = new VectorStyle(); overlap2.Fill = new SolidBrush(Color.FromArgb(20, Color.Yellow)); overlap2.Outline = new Pen(Color.Yellow, 1.0f); overlap2.EnableOutline = true; VectorStyle overlap3 = new VectorStyle(); overlap3.Fill = new SolidBrush(Color.FromArgb(20, Color.Pink)); overlap3.Outline = new Pen(Color.Yellow, 2.0f); overlap3.EnableOutline = true; VectorStyle overlap4 = new VectorStyle(); overlap4.Fill = new SolidBrush(Color.FromArgb(20, Color.Blue)); overlap4.Outline = new Pen(Color.Pink, 2.0f); overlap4.EnableOutline = true; VectorStyle overlap5 = new VectorStyle(); overlap5.Fill = new SolidBrush(Color.FromArgb(20, Color.Black)); overlap5.Outline = new Pen(Color.PowderBlue, 2.0f); overlap5.EnableOutline = true; VectorStyle defualtStyle = new VectorStyle(); defualtStyle.Fill = new SolidBrush(Color.FromArgb(25, Color.Green)); //overlap0.Outline = new Pen(Color.Yellow, 1.0f); overlap0.EnableOutline = true; Dictionary <int, IStyle> styles = new Dictionary <int, IStyle>(); styles.Add(0, overlap0); styles.Add(1, overlap2); styles.Add(2, overlap3); styles.Add(3, overlap4); styles.Add(4, overlap5); VectorLayer vlayer = new VectorLayer("l"); vlayer.DataSource = new SharpMap.Data.Providers.GeometryFeatureProvider(allfdt); vlayer.Theme = new UniqueValuesTheme <int>("OverlapCount", styles, defualtStyle); vlayer.Style.Fill = new SolidBrush(Color.FromArgb(30, Color.Green)); vlayer.Enabled = true; mbox.Map.Layers.Add(vlayer); mbox.Map.ZoomToExtents(); mbox.ActiveTool = MapBox.Tools.Pan; mbox.Refresh(); } } }
// get 4 corners of image public GeoPoint[] GetFourCorners() { var points = new GeoPoint[4]; double[] dblPoint; if (_gdalDataset != null) { var geoTrans = new double[6]; _gdalDataset.GetGeoTransform(geoTrans); // no rotation...use default transform if (!_useRotation && !_haveSpot || (geoTrans[0] == 0 && geoTrans[3] == 0)) geoTrans = new[] { 999.5, 1, 0, 1000.5, 0, -1 }; points[0] = new GeoPoint(geoTrans[0], geoTrans[3]); points[1] = new GeoPoint(geoTrans[0] + (geoTrans[1] * _imagesize.Width), geoTrans[3] + (geoTrans[4] * _imagesize.Width)); points[2] = new GeoPoint(geoTrans[0] + (geoTrans[1] * _imagesize.Width) + (geoTrans[2] * _imagesize.Height), geoTrans[3] + (geoTrans[4] * _imagesize.Width) + (geoTrans[5] * _imagesize.Height)); points[3] = new GeoPoint(geoTrans[0] + (geoTrans[2] * _imagesize.Height), geoTrans[3] + (geoTrans[5] * _imagesize.Height)); // transform to map's projection if (_transform != null) { for (var i = 0; i < 4; i++) { #if !DotSpatialProjections dblPoint = _transform.MathTransform.Transform(new[] { points[i].X, points[i].Y }); #else dblPoint = points[i].ToDoubleArray(); Reproject.ReprojectPoints(dblPoint, null, _transform.Source, _transform.Target, 0, 1); #endif points[i] = new GeoPoint(dblPoint[0], dblPoint[1]); } } } return points; }
private void MainMapImage_MouseMove(GeoPoint WorldPos, MouseEventArgs ImagePos) { CoordinatesLabel.Text = String.Format("Coordinates: {0:N5}, {1:N5}", WorldPos.X, WorldPos.Y); }
void mapBox1_MouseMove(GeoAPI.Geometries.Coordinate worldPos, MouseEventArgs imagePos) { this.label2.Text = worldPos.X.ToString("N4") + "/" + worldPos.Y.ToString("N4"); }
/// <summary> /// Returns the data associated with the centroid of the bounding box. /// </summary> /// <param name="box">BoundingBox to intersect with</param> /// <param name="ds">FeatureDataSet to fill data into</param> public void ExecuteIntersectionQuery(BoundingBox box, FeatureDataSet ds) { var pt = new GeoPoint(box.MinX + 0.5 * box.Width, box.MaxY - 0.5 * box.Height); ExecuteIntersectionQuery(pt, ds); }
/// <summary> /// Initializes a new map /// </summary> /// <param name="size">Size of map in pixels</param> public Map(Size size) { _mapViewportGuard = new MapViewPortGuard(size, 0d, Double.MaxValue); Factory = GeoAPI.GeometryServiceProvider.Instance.CreateGeometryFactory(_srid); _layers = new LayerCollection(); _backgroundLayers = new LayerCollection(); _variableLayers = new VariableLayerCollection(_layers); BackColor = Color.Transparent; _mapTransform = new Matrix(); MapTransformInverted = new Matrix(); _center = new Point(0, 0); _zoom = 1; WireEvents(); if (_logger.IsDebugEnabled) _logger.DebugFormat("Map initialized with size {0},{1}", size.Width, size.Height); }