private void TestMercator_2SP() { CoordinateSystemFactory cFac = new SharpMap.CoordinateSystems.CoordinateSystemFactory(); IEllipsoid ellipsoid = cFac.CreateFlattenedSphere("Krassowski 1940", 6378245.0, 298.3, LinearUnit.Metre); IHorizontalDatum datum = cFac.CreateHorizontalDatum("Krassowski 1940", DatumType.HD_Geocentric, ellipsoid, null); IGeographicCoordinateSystem gcs = cFac.CreateGeographicCoordinateSystem("Krassowski 1940", AngularUnit.Degrees, datum, PrimeMeridian.Greenwich, new AxisInfo("Lon", AxisOrientationEnum.East), new AxisInfo("Lat", AxisOrientationEnum.North)); List <ProjectionParameter> parameters = new List <ProjectionParameter>(); parameters.Add(new ProjectionParameter("latitude_of_origin", 42)); parameters.Add(new ProjectionParameter("central_meridian", 51)); parameters.Add(new ProjectionParameter("false_easting", 0)); parameters.Add(new ProjectionParameter("false_northing", 0)); IProjection projection = cFac.CreateProjection("Mercator_2SP", "Mercator_2SP", parameters); IProjectedCoordinateSystem coordsys = cFac.CreateProjectedCoordinateSystem("Pulkovo 1942 / Mercator Caspian Sea", gcs, projection, LinearUnit.Metre, new AxisInfo("East", AxisOrientationEnum.East), new AxisInfo("North", AxisOrientationEnum.North)); ICoordinateTransformation trans = new CoordinateTransformationFactory().CreateFromCoordinateSystems(gcs, coordsys); SharpMap.Geometries.Point pGeo = new SharpMap.Geometries.Point(53, 53); SharpMap.Geometries.Point pUtm = new Point(trans.MathTransform.Transform(pGeo.ToDoubleArray())); SharpMap.Geometries.Point pGeo2 = new Point(trans.MathTransform.Inverse().Transform(pUtm.ToDoubleArray())); result.Text += PrintResultTable(gcs, coordsys, pGeo, pUtm, new Point(165704.29, 5171848.07), pGeo2, "Mercator_2SP test"); }
/// <summary> /// Converts coordinates in projected meters to decimal degrees. /// </summary> /// <param name="p">Point in meters</param> /// <returns>Transformed point in decimal degrees</returns> public override SharpMap.Geometries.Point MetersToDegrees(SharpMap.Geometries.Point p) { double theta = Math.Atan((p.X - _falseEasting) / (ro0 - (p.Y - _falseNorthing))); double ro = Math.Sqrt(Math.Pow(p.X - _falseEasting, 2) + Math.Pow(ro0 - (p.Y - _falseNorthing), 2)); double q = (C - Math.Pow(ro, 2) * Math.Pow(n, 2) / Math.Pow(this._semiMajor, 2)) / n; double b = Math.Sin(q / (1 - ((1 - e_sq) / (2 * e)) * Math.Log((1 - e) / (1 + e)))); double lat = Math.Asin(q * 0.5); double preLat = double.MaxValue; int iterationCounter = 0; while (Math.Abs(lat - preLat) > 0.000001) { preLat = lat; double sin = Math.Sin(lat); double e2sin2 = e_sq * Math.Pow(sin, 2); lat += (Math.Pow(1 - e2sin2, 2) / (2 * Math.Cos(lat))) * ((q / (1 - e_sq)) - sin / (1 - e2sin2) + 1 / (2 * e) * Math.Log((1 - e * sin) / (1 + e * sin))); iterationCounter++; if (iterationCounter > 25) { throw new ApplicationException("Transformation failed to converge in Albers backwards transformation"); } } double lon = lon_center + (theta / n); return(new SharpMap.Geometries.Point(Radians2Degrees(lon), Radians2Degrees(lat))); }
private void TestMercator_1SP() { CoordinateSystemFactory cFac = new SharpMap.CoordinateSystems.CoordinateSystemFactory(); IEllipsoid ellipsoid = cFac.CreateFlattenedSphere("Bessel 1840", 6377397.155, 299.15281, LinearUnit.Metre); IHorizontalDatum datum = cFac.CreateHorizontalDatum("Bessel 1840", DatumType.HD_Geocentric, ellipsoid, null); IGeographicCoordinateSystem gcs = cFac.CreateGeographicCoordinateSystem("Bessel 1840", AngularUnit.Degrees, datum, PrimeMeridian.Greenwich, new AxisInfo("Lon", AxisOrientationEnum.East), new AxisInfo("Lat", AxisOrientationEnum.North)); List <ProjectionParameter> parameters = new List <ProjectionParameter>(); parameters.Add(new ProjectionParameter("latitude_of_origin", 0)); parameters.Add(new ProjectionParameter("central_meridian", 110)); parameters.Add(new ProjectionParameter("scale_factor", 0.997)); parameters.Add(new ProjectionParameter("false_easting", 3900000)); parameters.Add(new ProjectionParameter("false_northing", 900000)); IProjection projection = cFac.CreateProjection("Mercator_1SP", "Mercator_1SP", parameters); IProjectedCoordinateSystem coordsys = cFac.CreateProjectedCoordinateSystem("Makassar / NEIEZ", gcs, projection, LinearUnit.Metre, new AxisInfo("East", AxisOrientationEnum.East), new AxisInfo("North", AxisOrientationEnum.North)); ICoordinateTransformation trans = new CoordinateTransformationFactory().CreateFromCoordinateSystems(gcs, coordsys); SharpMap.Geometries.Point pGeo = new SharpMap.Geometries.Point(120, -3); SharpMap.Geometries.Point pUtm = new Point(trans.MathTransform.Transform(pGeo.ToDoubleArray())); SharpMap.Geometries.Point pGeo2 = new Point(trans.MathTransform.Inverse().Transform(pUtm.ToDoubleArray())); result.Text += PrintResultTable(gcs, coordsys, pGeo, pUtm, new Point(5009726.58, 569150.82), pGeo2, "Mercator_1SP test"); }
/// <summary> /// Method to render the Point to the <see cref="Graphics"/> object. /// </summary> /// <param name="map">The map object</param> /// <param name="point">Location where to render the Symbol</param> /// <param name="g">The graphics object to use.</param> public void Render(Map map, Point point, Graphics g) { foreach (var pointSymbolizer in Items) { pointSymbolizer.Render(map, point, g); } }
public XPoint TransformGeom(double sf, SharpMap.Geometries.Point geom, BoundingBox geomBox) { double xmin = geomBox.Left; double ymin = geomBox.Bottom; return(new XPoint((geom.X - xmin) * sf, -(geom.Y - ymin) * sf)); }
/// <summary> /// Returns the next array of Coordinates in the stream. /// </summary> /// <param name="tokenizer">Tokenizer over a stream of text in Well-known Text format. The /// next element returned by the stream should be "(" (the beginning of "(x1 y1, x2 y2, ..., xn yn)" or /// "EMPTY".</param> /// <returns>The next array of Coordinates in the stream, or an empty array of "EMPTY" is the /// next element returned by the stream.</returns> private static Collection <SharpMap.Geometries.Point> GetCoordinates(WktStreamTokenizer tokenizer) { Collection <SharpMap.Geometries.Point> coordinates = new Collection <SharpMap.Geometries.Point>(); string nextToken = GetNextEmptyOrOpener(tokenizer); if (nextToken == "EMPTY") { return(coordinates); } SharpMap.Geometries.Point externalCoordinate = new SharpMap.Geometries.Point(); SharpMap.Geometries.Point internalCoordinate = new SharpMap.Geometries.Point(); externalCoordinate.X = GetNextNumber(tokenizer); externalCoordinate.Y = GetNextNumber(tokenizer); coordinates.Add(externalCoordinate); nextToken = GetNextCloserOrComma(tokenizer); while (nextToken == ",") { internalCoordinate = new SharpMap.Geometries.Point(); internalCoordinate.X = GetNextNumber(tokenizer); internalCoordinate.Y = GetNextNumber(tokenizer); coordinates.Add(internalCoordinate); nextToken = GetNextCloserOrComma(tokenizer); } return(coordinates); }
public void TestMercator_1SP_Projection() { CoordinateSystemFactory cFac = new SharpMap.CoordinateSystems.CoordinateSystemFactory(); IEllipsoid ellipsoid = cFac.CreateFlattenedSphere("Bessel 1840", 6377397.155, 299.15281, LinearUnit.Metre); IHorizontalDatum datum = cFac.CreateHorizontalDatum("Bessel 1840", DatumType.HD_Geocentric, ellipsoid, null); IGeographicCoordinateSystem gcs = cFac.CreateGeographicCoordinateSystem("Bessel 1840", AngularUnit.Degrees, datum, PrimeMeridian.Greenwich, new AxisInfo("Lon", AxisOrientationEnum.East), new AxisInfo("Lat", AxisOrientationEnum.North)); //System.Collections.ObjectModel.Collection<ProjectionParameter> parameters = new System.Collections.ObjectModel.Collection<ProjectionParameter>(5); System.Collections.ObjectModel.Collection<ProjectionParameter> parameters = new System.Collections.ObjectModel.Collection<ProjectionParameter>(); parameters.Add(new ProjectionParameter("latitude_of_origin", 0)); parameters.Add(new ProjectionParameter("central_meridian", 110)); parameters.Add(new ProjectionParameter("scale_factor", 0.997)); parameters.Add(new ProjectionParameter("false_easting", 3900000)); parameters.Add(new ProjectionParameter("false_northing", 900000)); IProjection projection = cFac.CreateProjection("Mercator_1SP", "Mercator_1SP", parameters); IProjectedCoordinateSystem coordsys = cFac.CreateProjectedCoordinateSystem("Makassar / NEIEZ", gcs, projection, LinearUnit.Metre, new AxisInfo("East", AxisOrientationEnum.East), new AxisInfo("North", AxisOrientationEnum.North)); ICoordinateTransformation trans = new CoordinateTransformationFactory().CreateFromCoordinateSystems(gcs, coordsys); SharpMap.Geometries.Point pGeo = new SharpMap.Geometries.Point(120, -3); SharpMap.Geometries.Point pUtm = trans.MathTransform.Transform(pGeo); SharpMap.Geometries.Point pGeo2 = trans.MathTransform.Inverse().Transform(pUtm); SharpMap.Geometries.Point expected = new Point(5009726.58, 569150.82); Assert.IsTrue(ToleranceLessThan(pUtm, expected, 0.02), String.Format("Mercator_1SP forward transformation outside tolerance, Expected {0}, got {1}", expected.ToString(), pUtm.ToString())); Assert.IsTrue(ToleranceLessThan(pGeo, pGeo2, 0.0000001), String.Format("Mercator_1SP reverse transformation outside tolerance, Expected {0}, got {1}", pGeo.ToString(), pGeo2.ToString())); }
public void TestAlbersProjection() { CoordinateSystemFactory cFac = new SharpMap.CoordinateSystems.CoordinateSystemFactory(); IEllipsoid ellipsoid = cFac.CreateFlattenedSphere("Clarke 1866", 6378206.4, 294.9786982138982, LinearUnit.USSurveyFoot); IHorizontalDatum datum = cFac.CreateHorizontalDatum("Clarke 1866", DatumType.HD_Geocentric, ellipsoid, null); IGeographicCoordinateSystem gcs = cFac.CreateGeographicCoordinateSystem("Clarke 1866", AngularUnit.Degrees, datum, PrimeMeridian.Greenwich, new AxisInfo("Lon", AxisOrientationEnum.East), new AxisInfo("Lat", AxisOrientationEnum.North)); //System.Collections.ObjectModel.Collection<ProjectionParameter> parameters = new System.Collections.ObjectModel.Collection<ProjectionParameter>(5); System.Collections.ObjectModel.Collection<ProjectionParameter> parameters = new System.Collections.ObjectModel.Collection<ProjectionParameter>(); parameters.Add(new ProjectionParameter("central_meridian", -96)); parameters.Add(new ProjectionParameter("latitude_of_origin", 23)); parameters.Add(new ProjectionParameter("standard_parallel_1", 29.5)); parameters.Add(new ProjectionParameter("standard_parallel_2", 45.5)); parameters.Add(new ProjectionParameter("false_easting", 0)); parameters.Add(new ProjectionParameter("false_northing", 0)); IProjection projection = cFac.CreateProjection("Albers Conical Equal Area", "albers", parameters); IProjectedCoordinateSystem coordsys = cFac.CreateProjectedCoordinateSystem("Albers Conical Equal Area", gcs, projection, LinearUnit.Metre, new AxisInfo("East", AxisOrientationEnum.East), new AxisInfo("North", AxisOrientationEnum.North)); ICoordinateTransformation trans = new CoordinateTransformationFactory().CreateFromCoordinateSystems(gcs, coordsys); SharpMap.Geometries.Point pGeo = new SharpMap.Geometries.Point(-75, 35); SharpMap.Geometries.Point pUtm = trans.MathTransform.Transform(pGeo); SharpMap.Geometries.Point pGeo2 = trans.MathTransform.Inverse().Transform(pUtm); SharpMap.Geometries.Point expected = new Point(1885472.7, 1535925); Assert.IsTrue(ToleranceLessThan(pUtm, expected, 0.05), String.Format("Albers forward transformation outside tolerance, Expected {0}, got {1}", expected.ToString(), pUtm.ToString())); Assert.IsTrue(ToleranceLessThan(pGeo, pGeo2, 0.0000001), String.Format("Albers reverse transformation outside tolerance, Expected {0}, got {1}", pGeo.ToString(), pGeo2.ToString())); }
private void TestMercator_2SP() { CoordinateSystemFactory cFac = new SharpMap.CoordinateSystems.CoordinateSystemFactory(); IEllipsoid ellipsoid = cFac.CreateFlattenedSphere("Krassowski 1940", 6378245.0, 298.3, LinearUnit.Metre); IHorizontalDatum datum = cFac.CreateHorizontalDatum("Krassowski 1940", DatumType.HD_Geocentric, ellipsoid, null); IGeographicCoordinateSystem gcs = cFac.CreateGeographicCoordinateSystem("Krassowski 1940", AngularUnit.Degrees, datum, PrimeMeridian.Greenwich, new AxisInfo("Lon", AxisOrientationEnum.East), new AxisInfo("Lat", AxisOrientationEnum.North)); List<ProjectionParameter> parameters = new List<ProjectionParameter>(); parameters.Add(new ProjectionParameter("latitude_of_origin", 42)); parameters.Add(new ProjectionParameter("central_meridian", 51)); parameters.Add(new ProjectionParameter("false_easting", 0)); parameters.Add(new ProjectionParameter("false_northing", 0)); IProjection projection = cFac.CreateProjection("Mercator_2SP", "Mercator_2SP", parameters); IProjectedCoordinateSystem coordsys = cFac.CreateProjectedCoordinateSystem("Pulkovo 1942 / Mercator Caspian Sea", gcs, projection, LinearUnit.Metre, new AxisInfo("East", AxisOrientationEnum.East), new AxisInfo("North", AxisOrientationEnum.North)); ICoordinateTransformation trans = new CoordinateTransformationFactory().CreateFromCoordinateSystems(gcs, coordsys); SharpMap.Geometries.Point pGeo = new SharpMap.Geometries.Point(53,53); SharpMap.Geometries.Point pUtm = new Point(trans.MathTransform.Transform(pGeo.ToDoubleArray())); SharpMap.Geometries.Point pGeo2 = new Point(trans.MathTransform.Inverse().Transform(pUtm.ToDoubleArray())); result.Text += PrintResultTable(gcs, coordsys, pGeo, pUtm, new Point(165704.29, 5171848.07), pGeo2, "Mercator_2SP test"); }
private void TestTransverseMercator() { CoordinateSystemFactory cFac = new SharpMap.CoordinateSystems.CoordinateSystemFactory(); IEllipsoid ellipsoid = cFac.CreateFlattenedSphere("Airy 1830", 6377563.396, 299.32496, LinearUnit.Metre); IHorizontalDatum datum = cFac.CreateHorizontalDatum("Airy 1830", DatumType.HD_Geocentric, ellipsoid, null); IGeographicCoordinateSystem gcs = cFac.CreateGeographicCoordinateSystem("Airy 1830", AngularUnit.Degrees, datum, PrimeMeridian.Greenwich, new AxisInfo("Lon", AxisOrientationEnum.East), new AxisInfo("Lat", AxisOrientationEnum.North)); List <ProjectionParameter> parameters = new List <ProjectionParameter>(); parameters.Add(new ProjectionParameter("latitude_of_origin", 49)); parameters.Add(new ProjectionParameter("central_meridian", -2)); parameters.Add(new ProjectionParameter("scale_factor", 0.9996012717)); parameters.Add(new ProjectionParameter("false_easting", 400000)); parameters.Add(new ProjectionParameter("false_northing", -100000)); IProjection projection = cFac.CreateProjection("Transverse Mercator", "Transverse_Mercator", parameters); IProjectedCoordinateSystem coordsys = cFac.CreateProjectedCoordinateSystem("OSGB 1936 / British National Grid", gcs, projection, LinearUnit.Metre, new AxisInfo("East", AxisOrientationEnum.East), new AxisInfo("North", AxisOrientationEnum.North)); ICoordinateTransformation trans = new CoordinateTransformationFactory().CreateFromCoordinateSystems(gcs, coordsys); SharpMap.Geometries.Point pGeo = new SharpMap.Geometries.Point(0.5, 50.5); SharpMap.Geometries.Point pUtm = new Point(trans.MathTransform.Transform(pGeo.ToDoubleArray())); SharpMap.Geometries.Point pGeo2 = new Point(trans.MathTransform.Inverse().Transform(pUtm.ToDoubleArray())); result.Text += PrintResultTable(gcs, coordsys, pGeo, pUtm, new Point(577274.99, 69740.50), pGeo2, "Transverse Mercator test"); }
/// <summary> /// Converts coordinates in decimal degrees to projected meters. /// </summary> /// <param name="lonlat">The point in decimal degrees.</param> /// <returns>Point in projected meters</returns> public override SharpMap.Geometries.Point DegreesToMeters(SharpMap.Geometries.Point lonlat) { double dLongitude = Degrees2Radians(lonlat.X); double dLatitude = Degrees2Radians(lonlat.Y); double a = alpha(dLatitude); double ro = Ro(a); double theta = n * (dLongitude - lon_center); return(new Point( _falseEasting + ro * Math.Sin(theta), _falseNorthing + ro0 - (ro * Math.Cos(theta)))); /* * double sin_phi,cos_phi; // sine and cos values * double qs; // small q * double theta; // angle * double rh1; // height above ellipsoid * sincos(dLatitude,out sin_phi,out cos_phi); * qs = qsfnz(e,sin_phi,cos_phi); * rh1 = this._semiMajor * Math.Sqrt(C - ns0 * qs)/ns0; * theta = ns0 * adjust_lon(dLongitude - lon_center); * return new SharpMap.Geometries.Point( * rh1 * Math.Sin(theta) + this._falseEasting, * rh - rh1 * Math.Cos(theta) + this._falseNorthing); */ }
public MapZoomChangedEventArgs(double previousZoom, double currentZoom, GeoPoint previousCenter, GeoPoint currentCenter) { _previousZoom = previousZoom; _currentZoom = currentZoom; _previousCenter = previousCenter; _currentCenter = currentCenter; }
/// <summary> /// Function to render the symbol /// </summary> /// <param name="map">The map</param> /// <param name="point">The point to symbolize</param> /// <param name="g">The graphics object</param> public void Render(Map map, Point point, Graphics g) { if (point == null) { return; } PointF pp = Transform.WorldtoMap(point, map); pp = PointF.Add(pp, GetOffset()); if (Rotation != 0f && !Single.IsNaN(Rotation)) { Matrix startingTransform = g.Transform.Clone(); Matrix transform = g.Transform; PointF rotationCenter = pp; transform.RotateAt(Rotation, rotationCenter); g.Transform = transform; OnRenderInternal(pp, g); g.Transform = startingTransform; } else { OnRenderInternal(pp, g); } }
private void TestAlbers() { CoordinateSystemFactory cFac = new SharpMap.CoordinateSystems.CoordinateSystemFactory(); IEllipsoid ellipsoid = cFac.CreateFlattenedSphere("Clarke 1866", 6378206.4, 294.9786982138982, LinearUnit.USSurveyFoot); IHorizontalDatum datum = cFac.CreateHorizontalDatum("Clarke 1866", DatumType.HD_Geocentric, ellipsoid, null); IGeographicCoordinateSystem gcs = cFac.CreateGeographicCoordinateSystem("Clarke 1866", AngularUnit.Degrees, datum, PrimeMeridian.Greenwich, new AxisInfo("Lon", AxisOrientationEnum.East), new AxisInfo("Lat", AxisOrientationEnum.North)); List <ProjectionParameter> parameters = new List <ProjectionParameter>(); parameters.Add(new ProjectionParameter("central_meridian", -96)); parameters.Add(new ProjectionParameter("latitude_of_origin", 23)); parameters.Add(new ProjectionParameter("standard_parallel_1", 29.5)); parameters.Add(new ProjectionParameter("standard_parallel_2", 45.5)); parameters.Add(new ProjectionParameter("false_easting", 0)); parameters.Add(new ProjectionParameter("false_northing", 0)); IProjection projection = cFac.CreateProjection("Albers Conical Equal Area", "albers", parameters); IProjectedCoordinateSystem coordsys = cFac.CreateProjectedCoordinateSystem("Albers Conical Equal Area", gcs, projection, LinearUnit.Metre, new AxisInfo("East", AxisOrientationEnum.East), new AxisInfo("North", AxisOrientationEnum.North)); ICoordinateTransformation trans = new CoordinateTransformationFactory().CreateFromCoordinateSystems(gcs, coordsys); SharpMap.Geometries.Point pGeo = new SharpMap.Geometries.Point(-75, 35); SharpMap.Geometries.Point pUtm = new Point(trans.MathTransform.Transform(pGeo.ToDoubleArray())); SharpMap.Geometries.Point pGeo2 = new Point(trans.MathTransform.Inverse().Transform(pUtm.ToDoubleArray())); result.Text += PrintResultTable(gcs, coordsys, pGeo, pUtm, new Point(1885472.7, 1535925), pGeo2, "Albers Conical Equal Area test"); }
public static FeatureDataRow LocatePolygon2(SharpMap.Geometries.Point punto, SharpMap.Data.FeatureDataTable fdt) { FeatureDataRow fdr = null; if ((fdt as DataTable).Rows.Count == 1) { fdr = (FeatureDataRow)(fdt as DataTable).Rows[0]; } else { GisSharpBlog.NetTopologySuite.Geometries.GeometryFactory f = new GeometryFactory(new PrecisionModel()); foreach (DataRow r in (fdt as DataTable).Rows) { if ((r as FeatureDataRow).Geometry.GetType() == typeof(SharpMap.Geometries.MultiPolygon)) { // Doble cast: de Geometria a MultiPolygon, y de DataRow a FeatureDataRow. SharpMap.Geometries.MultiPolygon SharpMultiPol = (SharpMap.Geometries.MultiPolygon)(r as FeatureDataRow).Geometry; GisSharpBlog.NetTopologySuite.Geometries.Geometry[] NTSGeom = GeometryConverter.ToNTSGeometry(new SharpMap.Geometries.Geometry[1] { SharpMultiPol }, f); GisSharpBlog.NetTopologySuite.Geometries.MultiPolygon NTSMultiPol = (GisSharpBlog.NetTopologySuite.Geometries.MultiPolygon)NTSGeom[0]; if (NTSMultiPol.Contains(new GisSharpBlog.NetTopologySuite.Geometries.Point(punto.X, punto.Y)) == true) { fdr = (FeatureDataRow)r; break; } } } } return(fdr); }
private Bitmap GeneratePartialBitmap(SharpMap.Geometries.Point center, XPosition xPos, YPosition yPos) { double x = center.X, y = center.Y; switch (xPos) { case XPosition.Right: x += _Map.Envelope.Width; break; case XPosition.Left: x -= _Map.Envelope.Width; break; } switch (yPos) { case YPosition.Top: y += _Map.Envelope.Height; break; case YPosition.Bottom: y -= _Map.Envelope.Height; break; } _Map.Center = new SharpMap.Geometries.Point(x, y); // new SharpMap.Geometries.Point(x, y); return(_Map.GetMap() as Bitmap); }
private void TestLambertConicConformal_2SP() { CoordinateSystemFactory cFac = new SharpMap.CoordinateSystems.CoordinateSystemFactory(); IEllipsoid ellipsoid = cFac.CreateFlattenedSphere("Clarke 1866", 20925832.16, 294.97470, LinearUnit.USSurveyFoot); IHorizontalDatum datum = cFac.CreateHorizontalDatum("Clarke 1866", DatumType.HD_Geocentric, ellipsoid, null); IGeographicCoordinateSystem gcs = cFac.CreateGeographicCoordinateSystem("Clarke 1866", AngularUnit.Degrees, datum, PrimeMeridian.Greenwich, new AxisInfo("Lon", AxisOrientationEnum.East), new AxisInfo("Lat", AxisOrientationEnum.North)); List <ProjectionParameter> parameters = new List <ProjectionParameter>(); parameters.Add(new ProjectionParameter("latitude_of_origin", 27.833333333)); parameters.Add(new ProjectionParameter("central_meridian", -99)); parameters.Add(new ProjectionParameter("standard_parallel_1", 28.3833333333)); parameters.Add(new ProjectionParameter("standard_parallel_2", 30.2833333333)); parameters.Add(new ProjectionParameter("false_easting", 2000000)); parameters.Add(new ProjectionParameter("false_northing", 0)); IProjection projection = cFac.CreateProjection("Lambert Conic Conformal (2SP)", "lambert_conformal_conic_2sp", parameters); IProjectedCoordinateSystem coordsys = cFac.CreateProjectedCoordinateSystem("NAD27 / Texas South Central", gcs, projection, LinearUnit.USSurveyFoot, new AxisInfo("East", AxisOrientationEnum.East), new AxisInfo("North", AxisOrientationEnum.North)); ICoordinateTransformation trans = new CoordinateTransformationFactory().CreateFromCoordinateSystems(gcs, coordsys); SharpMap.Geometries.Point pGeo = new SharpMap.Geometries.Point(-96, 28.5); SharpMap.Geometries.Point pUtm = new Point(trans.MathTransform.Transform(pGeo.ToDoubleArray())); SharpMap.Geometries.Point pGeo2 = new Point(trans.MathTransform.Inverse().Transform(pUtm.ToDoubleArray())); result.Text += PrintResultTable(gcs, coordsys, pGeo, pUtm, new Point(2963503.91, 254759.80), pGeo2, "Lambert Conic Conformal 2SP test"); }
private void TestMercator_1SP() { CoordinateSystemFactory cFac = new SharpMap.CoordinateSystems.CoordinateSystemFactory(); IEllipsoid ellipsoid = cFac.CreateFlattenedSphere("Bessel 1840", 6377397.155, 299.15281, LinearUnit.Metre); IHorizontalDatum datum = cFac.CreateHorizontalDatum("Bessel 1840", DatumType.HD_Geocentric, ellipsoid, null); IGeographicCoordinateSystem gcs = cFac.CreateGeographicCoordinateSystem("Bessel 1840", AngularUnit.Degrees, datum, PrimeMeridian.Greenwich, new AxisInfo("Lon", AxisOrientationEnum.East), new AxisInfo("Lat", AxisOrientationEnum.North)); List<ProjectionParameter> parameters = new List<ProjectionParameter>(); parameters.Add(new ProjectionParameter("latitude_of_origin", 0)); parameters.Add(new ProjectionParameter("central_meridian", 110)); parameters.Add(new ProjectionParameter("scale_factor", 0.997)); parameters.Add(new ProjectionParameter("false_easting", 3900000)); parameters.Add(new ProjectionParameter("false_northing", 900000)); IProjection projection = cFac.CreateProjection("Mercator_1SP", "Mercator_1SP", parameters); IProjectedCoordinateSystem coordsys = cFac.CreateProjectedCoordinateSystem("Makassar / NEIEZ", gcs, projection, LinearUnit.Metre, new AxisInfo("East", AxisOrientationEnum.East), new AxisInfo("North", AxisOrientationEnum.North)); ICoordinateTransformation trans = new CoordinateTransformationFactory().CreateFromCoordinateSystems(gcs, coordsys); SharpMap.Geometries.Point pGeo = new SharpMap.Geometries.Point(120, -3); SharpMap.Geometries.Point pUtm = new Point(trans.MathTransform.Transform(pGeo.ToDoubleArray())); SharpMap.Geometries.Point pGeo2 = new Point(trans.MathTransform.Inverse().Transform(pUtm.ToDoubleArray())); result.Text += PrintResultTable(gcs, coordsys, pGeo, pUtm, new Point(5009726.58, 569150.82), pGeo2, "Mercator_1SP test"); }
private void generateLines(Collection <Geometry> geometry, Random rndGen) { int numLines = rndGen.Next(10, 100); for (int lineIndex = 0; lineIndex < numLines; lineIndex++) { LineString line = new LineString(); Collection <GeoPoint> verticies = new Collection <GeoPoint>(); int numVerticies = rndGen.Next(4, 15); GeoPoint lastPoint = new GeoPoint(rndGen.NextDouble() * 1000, rndGen.NextDouble() * 1000); verticies.Add(lastPoint); for (int vertexIndex = 0; vertexIndex < numVerticies; vertexIndex++) { GeoPoint nextPoint = new GeoPoint(lastPoint.X + rndGen.Next(-50, 50), lastPoint.Y + rndGen.Next(-50, 50)); verticies.Add(nextPoint); lastPoint = nextPoint; } line.Vertices = verticies; geometry.Add(line); } }
public void AddLine(double x, double y, double? z) { SmGeometries.Point point=null; if (z.HasValue) point=new SmGeometries.Point3D(x, y, z.Value); else point=new SmGeometries.Point(x, y); _CurrentPoints.Add(point); }
public static void DrawPoint(IPointSymbolizer symbolizer, Graphics g, Point point, Map map) { if (point == null) { return; } symbolizer.Render(map, point, g); }
void MapImage_MouseMove(Point worldPos, MouseEventArgs e) { if (m_ToolPhase == ToolPhase.WaitFirst) { return; } System.Drawing.Point p = e.Location; DrawTerminalSegments(m_LastMousePosition, p); m_LastMousePosition = p; }
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 void generatePoints(Collection <Geometry> geometry, Random rndGen) { int numPoints = rndGen.Next(10, 100); for (int pointIndex = 0; pointIndex < numPoints; pointIndex++) { GeoPoint point = new GeoPoint(rndGen.NextDouble() * 1000, rndGen.NextDouble() * 1000); geometry.Add(point); } }
public override void OnMouseDown(int x, int y, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { n++; if (n == 1) { SharpMap.Geometries.Point P0 = new SharpMap.Geometries.Point(x, y); SharpMap.Geometries.Point P1 = new SharpMap.Geometries.Point(x, y); SharpMap.Geometries.Point P2 = new SharpMap.Geometries.Point(x, y); vertices.Add(P0); vertices.Add(P1); vertices.Add(P2); line = new LinearRing(vertices); } else if (n == 2) { vertices[1] = new SharpMap.Geometries.Point(x, y); PointF p1 = new PointF((float)vertices[0].X, (float)vertices[0].Y); PointF p2 = new PointF(x, y); mScreenDisplay.DrawPolyline(Pens.Blue, p1, p2); //n = 0; } else if (n == 3) { vertices[2] = new SharpMap.Geometries.Point(x, y); polygon.ExteriorRing = line; if (line != null) { SolidBrush brush = new SolidBrush(Color.Blue); Pen pen = new Pen(brush); // mScreenDisplay.DrawPolygon(polygon, brush, pen, false); mScreenDisplay.NewObject = polygon; } } else { SharpMap.Geometries.Point P4 = new SharpMap.Geometries.Point(x, y); vertices.Add(P4); SolidBrush brush = new SolidBrush(Color.Blue); Pen pen = new Pen(brush); // mScreenDisplay.DrawPolygon(polygon, brush, pen, false); mScreenDisplay.NewObject = polygon; } mMapCtrl.Refresh(); } else if (e.Button == MouseButtons.Right) { mMapCtrl.Refresh(); vertices = new List <SharpMap.Geometries.Point>(); polygon = new Polygon(); tempPolygon = new Polygon(); n = 0; } }
public override List <SharpMap.Geometries.Point> TransformList(List <SharpMap.Geometries.Point> ord) { List <SharpMap.Geometries.Point> result = new List <SharpMap.Geometries.Point>(ord.Count); for (int i = 0; i < ord.Count; i++) { SharpMap.Geometries.Point point = ord[i]; result.Add(Transform(point)); } return(result); }
public override SharpMap.Geometries.Point Transform(SharpMap.Geometries.Point point) { if (!_isInverse) { return(this.DegreesToMeters(point)); } else { return(this.MetersToDegrees(point)); } }
public override void NavigationTick(NavigationObject navigationObject) { geometries.Clear(); //Add two points SharpMap.Geometries.Point point = new SharpMap.Geometries.Point(navigationObject.CurrentImage.Longitude, navigationObject.CurrentImage.Latitude); SharpMap.Geometries.Point pointTranformed = (SharpMap.Geometries.Point)TransformGeo(point); geometries.Add(pointTranformed); MainMapImage.Map.Center.X = pointTranformed.X; MainMapImage.Map.Center.Y = pointTranformed.Y; MainMapImage.Refresh(); }
/// <summary> /// Transforms from world coordinate system (WCS) to image coordinates /// NOTE: This method DOES NOT take the MapTransform property into account (use SharpMap.Map.MapToWorld instead) /// </summary> /// <param name="p">Point in WCS</param> /// <param name="map">Map reference</param> /// <returns>Point in image coordinates</returns> public static PointF WorldtoMap(Point p, Map map) { //if (map.MapTransform != null && !map.MapTransform.IsIdentity) // map.MapTransform.TransformPoints(new System.Drawing.PointF[] { p }); PointF result = new System.Drawing.Point(); double Height = (map.Zoom*map.Size.Height)/map.Size.Width; double left = map.Center.X - map.Zoom*0.5; double top = map.Center.Y + Height*0.5*map.PixelAspectRatio; result.X = (float) ((p.X - left)/map.PixelWidth); result.Y = (float) ((top - p.Y)/map.PixelHeight); return result; }
/// <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> /// <param name="careAboutMapTransform">Indicates whether MapTransform should be taken into account</param> /// <returns>Point in image coordinates</returns> public PointF WorldToImage(Point p, bool careAboutMapTransform) { PointF pTmp = Transform.WorldtoMap(p, this); if (careAboutMapTransform && !MapTransform.IsIdentity) { PointF[] pts = new PointF[] { pTmp }; MapTransform.TransformPoints(pts); pTmp = pts[0]; } return(pTmp); }
public override SharpMap.Geometries.Point Transform(SharpMap.Geometries.Point cp) { Point projectedPoint = new Point(); if (!_isInverse) { return(this.DegreesToMeters(cp)); } else { return(this.MetersToDegrees(cp)); } }
public void AddLine(double x, double y, double?z) { SmGeometries.Point point = null; if (z.HasValue) { point = new SmGeometries.Point3D(x, y, z.Value); } else { point = new SmGeometries.Point(x, y); } _CurrentPoints.Add(point); }
/// <summary> /// Transforms from image coordinates to world coordinate system (WCS). /// NOTE: This method DOES NOT take the MapTransform property into account (use SharpMap.Map.MapToWorld instead) /// </summary> /// <param name="p">Point in image coordinate system</param> /// <param name="map">Map reference</param> /// <returns>Point in WCS</returns> public static Point MapToWorld(PointF p, Map map) { if (map.Center.IsEmpty() || double.IsNaN(map.MapHeight)) { return(new Point(0, 0)); } else { Point ul = new Point(map.Center.X - map.Zoom * .5, map.Center.Y + map.MapHeight * .5); return(new Point(ul.X + p.X * map.PixelWidth, ul.Y - p.Y * map.PixelHeight)); } }
/// <summary> /// Transforms from image coordinates to world coordinate system (WCS). /// NOTE: This method DOES NOT take the MapTransform property into account (use SharpMap.Map.MapToWorld instead) /// </summary> /// <param name="p">Point in image coordinate system</param> /// <param name="map">Map reference</param> /// <returns>Point in WCS</returns> public static Point MapToWorld(PointF p, Map map) { if (map.Center.IsEmpty() || double.IsNaN(map.MapHeight)) { return new Point(0, 0); } else { Point ul = new Point(map.Center.X - map.Zoom * .5, map.Center.Y + map.MapHeight * .5); return new Point(ul.X + p.X * map.PixelWidth, ul.Y - p.Y * map.PixelHeight); } }
/// <summary> /// Transforms from world coordinate system (WCS) to image coordinates /// NOTE: This method DOES NOT take the MapTransform property into account (use SharpMap.Map.MapToWorld instead) /// </summary> /// <param name="p">Point in WCS</param> /// <param name="map">Map reference</param> /// <returns>Point in image coordinates</returns> public static PointF WorldtoMap(Point p, Map map) { //if (map.MapTransform != null && !map.MapTransform.IsIdentity) // map.MapTransform.TransformPoints(new System.Drawing.PointF[] { p }); PointF result = new System.Drawing.Point(); double height = (map.Zoom * map.Size.Height) / map.Size.Width; double left = map.Center.X - map.Zoom * 0.5; double top = map.Center.Y + height * 0.5 * map.PixelAspectRatio; result.X = (float)((p.X - left) / map.PixelWidth); result.Y = (float)((top - p.Y) / map.PixelHeight); return(result); }
void MapImage_MouseDown(SharpMap.Geometries.Point worldPos, MouseEventArgs e) { if (m_TargetLayerGuid == Guid.Empty) { return; } if (!m_IsMoveMode) { var area = GIS_V4.Utils.GeometryUtils.PointToArea(worldPos, 3, MapImage.Map.PixelWidth); var fds = new FeatureDataSet(); var zoneLayer = UserDbLayersManager.GetUserLayer(m_TargetLayerGuid); zoneLayer.DataSource.ExecuteIntersectionQuery(area.GetBoundingBox(), fds); if (fds.Tables.Count <= 0) { m_SelectedFeature = null; return; } if (fds.Tables[0].Rows.Count <= 0) { m_SelectedFeature = null; MapImage.RefreshFromCache(); return; } m_SelectedFeature = fds.Tables[0][0]; MapImage.RefreshFromCache(); } else { //tool in move mode if (e.Button == MouseButtons.Left) { //start shifting on mouse move m_IsShifting = true; m_ShiftBeginPnt = worldPos; m_LastShiftPnt = new SharpMap.Geometries.Point(worldPos.X, worldPos.Y); } } if (m_SelectedFeature != null && e.Button == MouseButtons.Right) { if (m_SelectedFeature.Geometry.GetBoundingBox().Contains(worldPos)) { m_CMenu.Show(MapImage, e.Location); } } }
void m_MapImage_MouseUp(SharpMap.Geometries.Point worldPos, MouseEventArgs imagePos) { if (m_IsShifting && m_IsMoveMode && imagePos.Button == MouseButtons.Left) { //stop shifting m_IsShifting = false; //save last shift-position into buffer zone var zone = m_BufZoneLayer.FeatureRowToStruct(m_SelectedFeature); var deltaX = worldPos.X - m_ShiftBeginPnt.X; var deltaY = worldPos.Y - m_ShiftBeginPnt.Y; if (zone.Radius > 0) { //circle zone.Center.X = zone.Center.X + deltaX; zone.Center.Y = zone.Center.Y + deltaY; zone.Geometry = GIS_V4.Utils.GeometryUtils.CreateBuffer(zone.Center, zone.Radius); m_BufZoneLayer.UpdateZone(zone); m_SelectedFeature.Geometry = zone.Geometry; m_SelectedFeature["dblCenterX"] = zone.Center.X; m_SelectedFeature["dblCenterY"] = zone.Center.Y; } else { //polygon if (m_SelectedFeature.Geometry is Polygon) { var geom = (Polygon)m_SelectedFeature.Geometry; //foreach (var vertex in geom.ExteriorRing.Vertices) //{ // vertex.X = vertex.X + deltaX; // vertex.Y = vertex.Y + deltaY; //} zone.Geometry = new Polygon(geom.ExteriorRing); m_SelectedFeature.Geometry = zone.Geometry; m_BufZoneLayer.UpdateZone(zone); } } MapImage.Refresh(); } }
/// <summary> /// Initializes a new map /// </summary> /// <param name="size">Size of map in pixels</param> public Map(Size size) { Size = size; _Layers = new LayerCollection(); _Layers.ListChanged += new System.ComponentModel.ListChangedEventHandler(_Layers_ListChanged); _variableLayers = new VariableLayerCollection(_Layers); BackColor = Color.Transparent; _MaximumZoom = double.MaxValue; _MinimumZoom = 0; _MapTransform = new Matrix(); MapTransformInverted = new Matrix(); _Center = new Point(0, 0); _Zoom = 1; _PixelAspectRatio = 1.0; }
/// <summary> /// Transforms from image coordinates to world coordinate system (WCS). /// NOTE: This method DOES NOT take the MapTransform property into account (use SharpMap.Map.MapToWorld instead) /// </summary> /// <param name="p">Point in image coordinate system</param> /// <param name="map">Map reference</param> /// <returns>Point in WCS</returns> public static Point MapToWorld(PointF p, Map map) { //if (this.MapTransform != null && !this.MapTransform.IsIdentity) //{ // System.Drawing.PointF[] p2 = new System.Drawing.PointF[] { p }; // this.MapTransform.TransformPoints(new System.Drawing.PointF[] { p }); // this.MapTransformInverted.TransformPoints(p2); // return Utilities.Transform.MapToWorld(p2[0], this); //} //else Point ul = new Point(map.Center.X - map.Zoom * .5, map.Center.Y + map.MapHeight * .5); return new Point(ul.X + p.X * map.PixelWidth, ul.Y - p.Y * map.PixelHeight); //BoundingBox env = map.Envelope; //return new Point(env.Min.X + p.X*map.PixelWidth, // env.Max.Y - p.Y*map.PixelHeight); }
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 { Center = new Point(0, 0); Zoom = 360; //Create the map GenerateMap(); } PrintWmsInfo(); }
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(); }
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.Left, myMap.Center.Y); Point right = new Point(myMap.Envelope.Right, myMap.Center.Y); Point center = myMap.Center; if (PreviousProj != "Pseudo") { //Transform current view back to geographic coordinates ProjNet.CoordinateSystems.Transformations.ICoordinateTransformation trans = GetTransform(PreviousProj); left = GeometryTransform.TransformPoint(new Point(myMap.Envelope.Left, myMap.Center.Y), trans.MathTransform.Inverse()); right = GeometryTransform.TransformPoint(new Point(myMap.Envelope.Right, myMap.Center.Y), trans.MathTransform.Inverse()); center = GeometryTransform.TransformPoint(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 ProjNet.CoordinateSystems.Transformations.ICoordinateTransformation trans = GetTransform(SelectedProj); left = GeometryTransform.TransformPoint(left, trans.MathTransform); right = GeometryTransform.TransformPoint(right, trans.MathTransform); center = GeometryTransform.TransformPoint(center, trans.MathTransform); myMap.Center = center; myMap.Zoom = Math.Abs(right.X - left.X); BoundingBox envelopeGcs = GeometryTransform.TransformBox(myMap.Envelope, trans.MathTransform.Inverse()); litEnvelopeLatLong.Text = envelopeGcs.ToString(); } GenerateMap(); }
/// <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> /// <param name="careAboutMapTransform">Indicates whether MapTransform should be taken into account</param> /// <returns>Point in image coordinates</returns> public PointF WorldToImage(Point p, bool careAboutMapTransform) { PointF pTmp = Transform.WorldtoMap(p, this); lock (MapTransform) { if (careAboutMapTransform && !MapTransform.IsIdentity) { PointF[] pts = new PointF[] { pTmp }; MapTransform.TransformPoints(pts); pTmp = pts[0]; } } return pTmp; }
public static void DrawPoint(Graphics g, Point point, Image symbol, float symbolscale, PointF offset, float rotation, Map map) { if (point == null) return; if (symbol == null) //We have no point style - Use a default symbol symbol = Defaultsymbol; PointF pp = Transform.WorldtoMap(point, map); if (rotation != 0 && !Single.IsNaN(rotation)) { Matrix startingTransform = g.Transform.Clone(); Matrix transform = g.Transform; PointF rotationCenter = pp; //Matrix transform = new Matrix(); transform.RotateAt(rotation, rotationCenter); g.Transform = transform; if (symbolscale == 1f) { g.DrawImageUnscaled(symbol, (int)(pp.X - symbol.Width / 2f + offset.X), (int)(pp.Y - symbol.Height / 2f + offset.Y)); } else { float width = symbol.Width * symbolscale; float height = symbol.Height * symbolscale; g.DrawImage(symbol, (int)pp.X - width / 2 + offset.X * symbolscale, (int)pp.Y - height / 2 + offset.Y * symbolscale, width, height); } g.Transform = startingTransform; } else { if (symbolscale == 1f) { lock (symbol) { g.DrawImageUnscaled(symbol, (int)(pp.X - symbol.Width / 2f + offset.X), (int)(pp.Y - symbol.Height / 2f + offset.Y)); } } else { float width = symbol.Width * symbolscale; float height = symbol.Height * symbolscale; g.DrawImage(symbol, (int)pp.X - width / 2 + offset.X * symbolscale, (int)pp.Y - height / 2 + offset.Y * symbolscale, width, height); } } }
public static void DrawPoint(IPointSymbolizer symbolizer, Graphics g, Point point, Map map) { if (point == null) return; symbolizer.Render(map, point, g); }
public static void DrawPoint(Graphics g, Point point, Brush b, float size, PointF offset, Map map) { if (point == null) return; PointF pp = Transform.WorldtoMap(point, map); Matrix startingTransform = g.Transform; float width = size; float height = size; g.FillEllipse(b, (int)pp.X - width / 2 + offset.X , (int)pp.Y - height / 2 + offset.Y , width, height); System.Diagnostics.Debug.WriteLine(string.Format("DP {0}", new PointF(pp.X-width * 0.5f, pp.Y-height * 0.5f))); }
private void MainMapImage_MouseMove(GeoPoint WorldPos, MouseEventArgs ImagePos) { CoordinatesLabel.Text = String.Format("Coordinates: {0:N5}, {1:N5}", WorldPos.X, WorldPos.Y); }
/// <summary> /// Function to render the symbol /// </summary> /// <param name="map">The map</param> /// <param name="point">The point to symbolize</param> /// <param name="g">The graphics object</param> public void Render(Map map, Point point, Graphics g) { if (point == null) return; PointF pp = Transform.WorldtoMap(point, map); pp = PointF.Add(pp, GetOffset()); if (Rotation != 0f && !Single.IsNaN(Rotation)) { Matrix startingTransform = g.Transform.Clone(); Matrix transform = g.Transform; PointF rotationCenter = pp; transform.RotateAt(Rotation, rotationCenter); g.Transform = transform; OnRenderInternal(pp, g); g.Transform = startingTransform; } else { OnRenderInternal(pp, g); } }
private void generateLines(Collection<Geometry> geometry, Random rndGen) { int numLines = rndGen.Next(10, 100); for (int lineIndex = 0; lineIndex < numLines; lineIndex++) { LineString line = new LineString(); Collection<GeoPoint> verticies = new Collection<GeoPoint>(); int numVerticies = rndGen.Next(4, 15); GeoPoint lastPoint = new GeoPoint(rndGen.NextDouble()*1000, rndGen.NextDouble()*1000); verticies.Add(lastPoint); for (int vertexIndex = 0; vertexIndex < numVerticies; vertexIndex++) { GeoPoint nextPoint = new GeoPoint(lastPoint.X + rndGen.Next(-50, 50), lastPoint.Y + rndGen.Next(-50, 50)); verticies.Add(nextPoint); lastPoint = nextPoint; } line.Vertices = verticies; geometry.Add(line); } }
private void generatePolygons(Collection<Geometry> geometry, Random rndGen) { int numPolygons = rndGen.Next(10, 100); for (int polyIndex = 0; polyIndex < numPolygons; polyIndex++) { Polygon polygon = new Polygon(); Collection<GeoPoint> verticies = new Collection<GeoPoint>(); GeoPoint upperLeft = new GeoPoint(rndGen.NextDouble()*1000, rndGen.NextDouble()*1000); double sideLength = rndGen.NextDouble()*50; // Make a square verticies.Add(upperLeft); verticies.Add(new GeoPoint(upperLeft.X + sideLength, upperLeft.Y)); verticies.Add(new GeoPoint(upperLeft.X + sideLength, upperLeft.Y - sideLength)); verticies.Add(new GeoPoint(upperLeft.X, upperLeft.Y - sideLength)); polygon.ExteriorRing = new LinearRing(verticies); geometry.Add(polygon); } }
// get 4 corners of image public Collection<SMPoint> GetFourCorners() { Collection<SMPoint> points = new Collection<SMPoint>(); double[] dblPoint; if (_GdalDataset != null) { double[] geoTrans = new double[6]; _GdalDataset.GetGeoTransform(geoTrans); // no rotation...use default transform if (!_useRotation && !_haveSpot || (geoTrans[0] == 0 && geoTrans[3] == 0)) geoTrans = new double[] { 999.5, 1, 0, 1000.5, 0, -1 }; points.Add(new SMPoint(geoTrans[0], geoTrans[3])); points.Add(new SMPoint(geoTrans[0] + (geoTrans[1] * _imagesize.Width), geoTrans[3] + (geoTrans[4] * _imagesize.Width))); points.Add(new SMPoint(geoTrans[0] + (geoTrans[1] * _imagesize.Width) + (geoTrans[2] * _imagesize.Height), geoTrans[3] + (geoTrans[4] * _imagesize.Width) + (geoTrans[5] * _imagesize.Height))); points.Add(new SMPoint(geoTrans[0] + (geoTrans[2] * _imagesize.Height), geoTrans[3] + (geoTrans[5] * _imagesize.Height))); // transform to map's projection if (_transform != null) { for (int i = 0; i < 4; i++) { dblPoint = _transform.MathTransform.Transform(new double[] { points[i].X, points[i].Y }); points[i] = new SMPoint(dblPoint[0], dblPoint[1]); } } } return points; }
/// <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> /// Generates a WMS 1.3.0 compliant response based on a <see cref="SharpMap.Map"/> and the current HttpRequest. /// </summary> /// <remarks> /// <para> /// The Web Map Server implementation in SharpMap requires v1.3.0 compatible clients, /// and support the basic operations "GetCapabilities" and "GetMap" /// as required by the WMS v1.3.0 specification. SharpMap does not support the optional /// GetFeatureInfo operation for querying. /// </para> /// <example> /// Creating a WMS server in ASP.NET is very simple using the classes in the SharpMap.Web.Wms namespace. /// <code lang="C#"> /// void page_load(object o, EventArgs e) /// { /// //Get the path of this page /// string url = (Request.Url.Query.Length>0?Request.Url.AbsoluteUri.Replace(Request.Url.Query,""):Request.Url.AbsoluteUri); /// SharpMap.Web.Wms.Capabilities.WmsServiceDescription description = /// new SharpMap.Web.Wms.Capabilities.WmsServiceDescription("Acme Corp. Map Server", url); /// /// // The following service descriptions below are not strictly required by the WMS specification. /// /// // Narrative description and keywords providing additional information /// description.Abstract = "Map Server maintained by Acme Corporation. Contact: [email protected]. High-quality maps showing roadrunner nests and possible ambush locations."; /// description.Keywords.Add("bird"); /// description.Keywords.Add("roadrunner"); /// description.Keywords.Add("ambush"); /// /// //Contact information /// description.ContactInformation.PersonPrimary.Person = "John Doe"; /// description.ContactInformation.PersonPrimary.Organisation = "Acme Inc"; /// description.ContactInformation.Address.AddressType = "postal"; /// description.ContactInformation.Address.Country = "Neverland"; /// description.ContactInformation.VoiceTelephone = "1-800-WE DO MAPS"; /// //Impose WMS constraints /// description.MaxWidth = 1000; //Set image request size width /// description.MaxHeight = 500; //Set image request size height /// /// //Call method that sets up the map /// //We just add a dummy-size, since the wms requests will set the image-size /// SharpMap.Map myMap = MapHelper.InitializeMap(new System.Drawing.Size(1,1)); /// /// //Parse the request and create a response /// SharpMap.Web.Wms.WmsServer.ParseQueryString(myMap,description); /// } /// </code> /// </example> /// </remarks> /// <param name="map">Map to serve on WMS</param> /// <param name="description">Description of map service</param> public static void ParseQueryString(Map map, Capabilities.WmsServiceDescription description) { if (_pixelSensitivity ==-1) _pixelSensitivity = 1; if (map == null) throw (new ArgumentException("Map for WMS is null")); if (map.Layers.Count == 0) throw (new ArgumentException("Map doesn't contain any layers for WMS service")); if (HttpContext.Current == null) throw (new ApplicationException( "An attempt was made to access the WMS server outside a valid HttpContext")); HttpContext context = HttpContext.Current; //IgnoreCase value should be set according to the VERSION parameter //v1.3.0 is case sensitive, but since it causes a lot of problems with several WMS clients, we ignore casing anyway. bool ignorecase = true; //Check for required parameters //Request parameter is mandatory if (context.Request.Params["REQUEST"] == null) { WmsException.ThrowWmsException("Required parameter REQUEST not specified"); return; } //Check if version is supported if (context.Request.Params["VERSION"] != null) { if (String.Compare(context.Request.Params["VERSION"], "1.3.0", ignorecase) != 0) { WmsException.ThrowWmsException("Only version 1.3.0 supported"); return; } } else //Version is mandatory if REQUEST!=GetCapabilities. Check if this is a capabilities request, since VERSION is null { if (String.Compare(context.Request.Params["REQUEST"], "GetCapabilities", ignorecase) != 0) { WmsException.ThrowWmsException("VERSION parameter not supplied"); return; } } //If Capabilities was requested if (String.Compare(context.Request.Params["REQUEST"], "GetCapabilities", ignorecase) == 0) { //Service parameter is mandatory for GetCapabilities request if (context.Request.Params["SERVICE"] == null) { WmsException.ThrowWmsException("Required parameter SERVICE not specified"); return; } if (String.Compare(context.Request.Params["SERVICE"], "WMS") != 0) WmsException.ThrowWmsException( "Invalid service for GetCapabilities Request. Service parameter must be 'WMS'"); XmlDocument capabilities = Capabilities.GetCapabilities(map, description); context.Response.Clear(); context.Response.ContentType = "text/xml"; XmlWriter writer = XmlWriter.Create(context.Response.OutputStream); capabilities.WriteTo(writer); writer.Close(); context.Response.End(); } else if (String.Compare(context.Request.Params["REQUEST"], "GetFeatureInfo", ignorecase) == 0) //FeatureInfo Requested { if (context.Request.Params["LAYERS"] == null) { WmsException.ThrowWmsException("Required parameter LAYERS not specified"); return; } if (context.Request.Params["STYLES"] == null) { WmsException.ThrowWmsException("Required parameter STYLES not specified"); return; } if (context.Request.Params["CRS"] == null) { WmsException.ThrowWmsException("Required parameter CRS not specified"); return; } else if (context.Request.Params["CRS"] != "EPSG:" + map.Layers[0].TargetSRID) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidCRS, "CRS not supported"); return; } if (context.Request.Params["BBOX"] == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter BBOX not specified"); return; } if (context.Request.Params["WIDTH"] == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter WIDTH not specified"); return; } if (context.Request.Params["HEIGHT"] == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter HEIGHT not specified"); return; } if (context.Request.Params["FORMAT"] == null) { WmsException.ThrowWmsException("Required parameter FORMAT not specified"); return; } if (context.Request.Params["QUERY_LAYERS"] == null) { WmsException.ThrowWmsException("Required parameter QUERY_LAYERS not specified"); return; } if (context.Request.Params["INFO_FORMAT"] == null) { WmsException.ThrowWmsException("Required parameter INFO_FORMAT not specified"); return; } //parameters X&Y are not part of the 1.3.0 specification, but are included for backwards compatability with 1.1.1 (OpenLayers likes it when used together with wms1.1.1 services) if (context.Request.Params["X"] == null && context.Request.Params["I"] == null) { WmsException.ThrowWmsException("Required parameter I not specified"); return; } if (context.Request.Params["Y"] == null && context.Request.Params["J"] == null) { WmsException.ThrowWmsException("Required parameter J not specified"); return; } //sets the map size to the size of the client in order to calculate the coordinates of the projection of the client try { map.Size = new System.Drawing.Size(System.Convert.ToInt16(context.Request.Params["WIDTH"]), System.Convert.ToInt16(context.Request.Params["HEIGHT"])); } catch { WmsException.ThrowWmsException("Invalid parameters for HEIGHT or WITDH"); return; } //sets the boundingbox to the boundingbox of the client in order to calculate the coordinates of the projection of the client BoundingBox bbox = ParseBBOX(context.Request.Params["bbox"]); if (bbox == null) { WmsException.ThrowWmsException("Invalid parameter BBOX"); return; } map.ZoomToBox(bbox); //sets the point clicked by the client SharpMap.Geometries.Point p = new SharpMap.Geometries.Point(); Single x = 0; Single y = 0; //tries to set the x to the Param I, if the client send an X, it will try the X, if both fail, exception is thrown if (context.Request.Params["X"] != null) try { x = System.Convert.ToSingle(context.Request.Params["X"]); } catch { WmsException.ThrowWmsException("Invalid parameters for I"); } if (context.Request.Params["I"] != null) try { x = System.Convert.ToSingle(context.Request.Params["I"]); } catch { WmsException.ThrowWmsException("Invalid parameters for I"); } //same procedure for J (Y) if (context.Request.Params["Y"] != null) try { y = System.Convert.ToSingle(context.Request.Params["Y"]); } catch { WmsException.ThrowWmsException("Invalid parameters for I"); } if (context.Request.Params["J"] != null) try { y = System.Convert.ToSingle(context.Request.Params["J"]); } catch { WmsException.ThrowWmsException("Invalid parameters for I"); } p = map.ImageToWorld(new System.Drawing.PointF(x, y)); int fc; try { fc = System.Convert.ToInt16(context.Request.Params["FEATURE_COUNT"]); if (fc < 1) fc = 1; } catch { fc = 1; } //default to text if an invalid format is requested string infoFormat = context.Request.Params["INFO_FORMAT"]; string cqlFilter = null; if (context.Request.Params["CQL_FILTER"] != null) { cqlFilter = context.Request.Params["CQL_FILTER"]; } string vstr = ""; string[] requestLayers = context.Request.Params["QUERY_LAYERS"].Split(new[] { ',' }); if (String.Compare(context.Request.Params["INFO_FORMAT"], "text/json", ignorecase) == 0) { vstr = CreateFeatureInfoGeoJSON(map, requestLayers, x, y, fc, cqlFilter); context.Response.ContentType = "text/json"; } else { vstr = CreateFeatureInfoPlain(map, requestLayers, x, y, fc, cqlFilter); context.Response.ContentType = "text/plain"; } context.Response.Clear(); context.Response.Charset = "windows-1252"; context.Response.Write(vstr); context.Response.Flush(); context.Response.End(); } else if (String.Compare(context.Request.Params["REQUEST"], "GetMap", ignorecase) == 0) //Map requested { //Check for required parameters if (context.Request.Params["LAYERS"] == null) { WmsException.ThrowWmsException("Required parameter LAYERS not specified"); return; } if (context.Request.Params["STYLES"] == null) { WmsException.ThrowWmsException("Required parameter STYLES not specified"); return; } if (context.Request.Params["CRS"] == null) { WmsException.ThrowWmsException("Required parameter CRS not specified"); return; } else if (context.Request.Params["CRS"] != "EPSG:" + map.Layers[0].TargetSRID) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidCRS, "CRS not supported"); return; } if (context.Request.Params["BBOX"] == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter BBOX not specified"); return; } if (context.Request.Params["WIDTH"] == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter WIDTH not specified"); return; } if (context.Request.Params["HEIGHT"] == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter HEIGHT not specified"); return; } if (context.Request.Params["FORMAT"] == null) { WmsException.ThrowWmsException("Required parameter FORMAT not specified"); return; } //Set background color of map if (String.Compare(context.Request.Params["TRANSPARENT"], "TRUE", ignorecase) == 0) map.BackColor = Color.Transparent; else if (context.Request.Params["BGCOLOR"] != null) { try { map.BackColor = ColorTranslator.FromHtml(context.Request.Params["BGCOLOR"]); } catch { WmsException.ThrowWmsException("Invalid parameter BGCOLOR"); return; } ; } else map.BackColor = Color.White; //Get the image format requested ImageCodecInfo imageEncoder = GetEncoderInfo(context.Request.Params["FORMAT"]); if (imageEncoder == null) { WmsException.ThrowWmsException("Invalid MimeType specified in FORMAT parameter"); return; } //Parse map size int width = 0; int height = 0; if (!int.TryParse(context.Request.Params["WIDTH"], out width)) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Invalid parameter WIDTH"); return; } else if (description.MaxWidth > 0 && width > description.MaxWidth) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Parameter WIDTH too large"); return; } if (!int.TryParse(context.Request.Params["HEIGHT"], out height)) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Invalid parameter HEIGHT"); return; } else if (description.MaxHeight > 0 && height > description.MaxHeight) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Parameter HEIGHT too large"); return; } map.Size = new Size(width, height); BoundingBox bbox = ParseBBOX(context.Request.Params["bbox"]); if (bbox == null) { WmsException.ThrowWmsException("Invalid parameter BBOX"); return; } map.PixelAspectRatio = (width / (double)height) / (bbox.Width / bbox.Height); map.Center = bbox.GetCentroid(); map.Zoom = bbox.Width; //set Styles for layers //first, if the request == STYLES=, set all the vectorlayers with Themes not null the Theme to the first theme from Themes if (String.IsNullOrEmpty(context.Request.Params["STYLES"])) { foreach (ILayer layer in map.Layers) { if (layer.GetType() == typeof(VectorLayer)) { if ((layer as VectorLayer).Themes != null) { if ((layer as VectorLayer).Themes.Count > 0) { foreach (KeyValuePair<string, SharpMap.Rendering.Thematics.ITheme> kvp in (layer as VectorLayer).Themes) { (layer as VectorLayer).Theme = kvp.Value; break; } } } } } } else { if (!String.IsNullOrEmpty(context.Request.Params["LAYERS"])) { string[] layerz = context.Request.Params["LAYERS"].Split(new[] { ',' }); string[] styles = context.Request.Params["STYLES"].Split(new[] { ',' }); //test whether the lengt of the layers and the styles is the same. WMS spec is unclear on what to do if there is no one-to-one correspondence if (layerz.Length == styles.Length) { foreach (ILayer layer in map.Layers) { if (layer.GetType() == typeof(VectorLayer)) { if ((layer as VectorLayer).Themes != null) { if ((layer as VectorLayer).Themes.Count > 0) { for (int i = 0; i < layerz.Length; i++) { if (String.Equals(layer.LayerName, layerz[i], StringComparison.InvariantCultureIgnoreCase)) { //take default style if style is empty if (styles[i] =="") { foreach (KeyValuePair<string, SharpMap.Rendering.Thematics.ITheme> kvp in (layer as VectorLayer).Themes) { (layer as VectorLayer).Theme = kvp.Value; break; } } else { if ((layer as VectorLayer).Themes.ContainsKey(styles[i])) { (layer as VectorLayer).Theme = (layer as VectorLayer).Themes[styles[i]]; } else { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.StyleNotDefined, "Style not advertised for this layer"); } } } } } } } } } } } if (context.Request.Params["CQL_FILTER"] != null) { foreach (ILayer layer in map.Layers) { if (layer.GetType() == typeof(VectorLayer)) { if (typeof(SharpMap.Data.Providers.FilterProvider).IsAssignableFrom((layer as VectorLayer).DataSource.GetType())) { SharpMap.Data.Providers.FilterProvider shape = (SharpMap.Data.Providers.FilterProvider)(layer as VectorLayer).DataSource; shape.FilterDelegate = new Data.Providers.FilterProvider.FilterMethod(delegate(SharpMap.Data.FeatureDataRow row) { return CQLFilter(row, context.Request.Params["CQL_FILTER"]); }); } } else if(layer.GetType() == typeof(LabelLayer)) { if (typeof(SharpMap.Data.Providers.FilterProvider).IsAssignableFrom((layer as VectorLayer).DataSource.GetType())) { SharpMap.Data.Providers.FilterProvider shape = (SharpMap.Data.Providers.FilterProvider)(layer as VectorLayer).DataSource; shape.FilterDelegate = new Data.Providers.FilterProvider.FilterMethod(delegate(SharpMap.Data.FeatureDataRow row) { return CQLFilter(row, context.Request.Params["CQL_FILTER"]); }); } } } } //Set layers on/off if (!String.IsNullOrEmpty(context.Request.Params["LAYERS"])) //If LAYERS is empty, use default layer on/off settings { string[] layers = context.Request.Params["LAYERS"].Split(new[] { ',' }); if (description.LayerLimit > 0) { if (layers.Length == 0 && map.Layers.Count > description.LayerLimit || layers.Length > description.LayerLimit) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Too many layers requested"); return; } } foreach (ILayer layer in map.Layers) layer.Enabled = false; foreach (string layer in layers) { //SharpMap.Layers.ILayer lay = map.Layers.Find(delegate(SharpMap.Layers.ILayer findlay) { return findlay.LayerName == layer; }); ILayer lay = null; for (int i = 0; i < map.Layers.Count; i++) if (String.Equals(map.Layers[i].LayerName, layer, StringComparison.InvariantCultureIgnoreCase)) lay = map.Layers[i]; if (lay == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.LayerNotDefined, "Unknown layer '" + layer + "'"); return; } else lay.Enabled = true; } } //Render map Image img = map.GetMap(); //Png can't stream directy. Going through a memorystream instead MemoryStream MS = new MemoryStream(); img.Save(MS, imageEncoder, null); img.Dispose(); byte[] buffer = MS.ToArray(); context.Response.Clear(); context.Response.ContentType = imageEncoder.MimeType; context.Response.OutputStream.Write(buffer, 0, buffer.Length); //context.Response.End(); } else WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Invalid request"); }
private void generatePoints(Collection<Geometry> geometry, Random rndGen) { int numPoints = rndGen.Next(10, 100); for (int pointIndex = 0; pointIndex < numPoints; pointIndex++) { GeoPoint point = new GeoPoint(rndGen.NextDouble()*1000, rndGen.NextDouble()*1000); geometry.Add(point); } }
/// <summary> /// Generates a WMS 1.3.0 compliant response based on a <see cref="SharpMap.Map"/> and the current HttpRequest. /// </summary> /// <remarks> /// <para> /// The Web Map Server implementation in SharpMap requires v1.3.0 compatible clients, /// and support the basic operations "GetCapabilities" and "GetMap" /// as required by the WMS v1.3.0 specification. SharpMap does not support the optional /// GetFeatureInfo operation for querying. /// </para> /// <example> /// Creating a WMS server in ASP.NET is very simple using the classes in the SharpMap.Web.Wms namespace. /// <code lang="C#"> /// void page_load(object o, EventArgs e) /// { /// //Get the path of this page /// string url = (Request.Url.Query.Length>0?Request.Url.AbsoluteUri.Replace(Request.Url.Query,""):Request.Url.AbsoluteUri); /// SharpMap.Web.Wms.Capabilities.WmsServiceDescription description = /// new SharpMap.Web.Wms.Capabilities.WmsServiceDescription("Acme Corp. Map Server", url); /// /// // The following service descriptions below are not strictly required by the WMS specification. /// /// // Narrative description and keywords providing additional information /// description.Abstract = "Map Server maintained by Acme Corporation. Contact: [email protected]. High-quality maps showing roadrunner nests and possible ambush locations."; /// description.Keywords.Add("bird"); /// description.Keywords.Add("roadrunner"); /// description.Keywords.Add("ambush"); /// /// //Contact information /// description.ContactInformation.PersonPrimary.Person = "John Doe"; /// description.ContactInformation.PersonPrimary.Organisation = "Acme Inc"; /// description.ContactInformation.Address.AddressType = "postal"; /// description.ContactInformation.Address.Country = "Neverland"; /// description.ContactInformation.VoiceTelephone = "1-800-WE DO MAPS"; /// //Impose WMS constraints /// description.MaxWidth = 1000; //Set image request size width /// description.MaxHeight = 500; //Set image request size height /// /// //Call method that sets up the map /// //We just add a dummy-size, since the wms requests will set the image-size /// SharpMap.Map myMap = MapHelper.InitializeMap(new System.Drawing.Size(1,1)); /// /// //Parse the request and create a response /// SharpMap.Web.Wms.WmsServer.ParseQueryString(myMap,description); /// } /// </code> /// </example> /// </remarks> /// <param name="map">Map to serve on WMS</param> /// <param name="description">Description of map service</param> public static void ParseQueryString(Map map, Capabilities.WmsServiceDescription description) { _pixelSensitivity = 1; if (map == null) throw (new ArgumentException("Map for WMS is null")); if (map.Layers.Count == 0) throw (new ArgumentException("Map doesn't contain any layers for WMS service")); if (HttpContext.Current == null) throw (new ApplicationException( "An attempt was made to access the WMS server outside a valid HttpContext")); HttpContext context = HttpContext.Current; //IgnoreCase value should be set according to the VERSION parameter //v1.3.0 is case sensitive, but since it causes a lot of problems with several WMS clients, we ignore casing anyway. bool ignorecase = true; //Check for required parameters //Request parameter is mandatory if (context.Request.Params["REQUEST"] == null) { WmsException.ThrowWmsException("Required parameter REQUEST not specified"); return; } //Check if version is supported if (context.Request.Params["VERSION"] != null) { if (String.Compare(context.Request.Params["VERSION"], "1.3.0", ignorecase) != 0) { WmsException.ThrowWmsException("Only version 1.3.0 supported"); return; } } else //Version is mandatory if REQUEST!=GetCapabilities. Check if this is a capabilities request, since VERSION is null { if (String.Compare(context.Request.Params["REQUEST"], "GetCapabilities", ignorecase) != 0) { WmsException.ThrowWmsException("VERSION parameter not supplied"); return; } } //If Capabilities was requested if (String.Compare(context.Request.Params["REQUEST"], "GetCapabilities", ignorecase) == 0) { //Service parameter is mandatory for GetCapabilities request if (context.Request.Params["SERVICE"] == null) { WmsException.ThrowWmsException("Required parameter SERVICE not specified"); return; } if (String.Compare(context.Request.Params["SERVICE"], "WMS") != 0) WmsException.ThrowWmsException( "Invalid service for GetCapabilities Request. Service parameter must be 'WMS'"); XmlDocument capabilities = Capabilities.GetCapabilities(map, description); context.Response.Clear(); context.Response.ContentType = "text/xml"; XmlWriter writer = XmlWriter.Create(context.Response.OutputStream); capabilities.WriteTo(writer); writer.Close(); context.Response.End(); } else if (String.Compare(context.Request.Params["REQUEST"], "GetFeatureInfo", ignorecase) == 0) //FeatureInfo Requested { if (context.Request.Params["LAYERS"] == null) { WmsException.ThrowWmsException("Required parameter LAYERS not specified"); return; } if (context.Request.Params["STYLES"] == null) { WmsException.ThrowWmsException("Required parameter STYLES not specified"); return; } if (context.Request.Params["CRS"] == null) { WmsException.ThrowWmsException("Required parameter CRS not specified"); return; } else if (context.Request.Params["CRS"] != "EPSG:" + map.Layers[0].SRID) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidCRS, "CRS not supported"); return; } if (context.Request.Params["BBOX"] == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter BBOX not specified"); return; } if (context.Request.Params["WIDTH"] == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter WIDTH not specified"); return; } if (context.Request.Params["HEIGHT"] == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter HEIGHT not specified"); return; } if (context.Request.Params["FORMAT"] == null) { WmsException.ThrowWmsException("Required parameter FORMAT not specified"); return; } if (context.Request.Params["QUERY_LAYERS"] == null) { WmsException.ThrowWmsException("Required parameter QUERY_LAYERS not specified"); return; } if (context.Request.Params["INFO_FORMAT"] == null) { WmsException.ThrowWmsException("Required parameter INFO_FORMAT not specified"); return; } //parameters X&Y are not part of the 1.3.0 specification, but are included for backwards compatability with 1.1.1 (OpenLayers likes it when used together with wms1.1.1 services) if (context.Request.Params["X"] == null && context.Request.Params["I"] == null) { WmsException.ThrowWmsException("Required parameter I not specified"); return; } if (context.Request.Params["Y"] == null && context.Request.Params["J"] == null) { WmsException.ThrowWmsException("Required parameter J not specified"); return; } //sets the map size to the size of the client in order to calculate the coordinates of the projection of the client try { map.Size = new System.Drawing.Size(System.Convert.ToInt16(context.Request.Params["WIDTH"]), System.Convert.ToInt16(context.Request.Params["HEIGHT"])); } catch { WmsException.ThrowWmsException("Invalid parameters for HEIGHT or WITDH"); return; } //sets the boundingbox to the boundingbox of the client in order to calculate the coordinates of the projection of the client BoundingBox bbox = ParseBBOX(context.Request.Params["bbox"]); if (bbox == null) { WmsException.ThrowWmsException("Invalid parameter BBOX"); return; } map.ZoomToBox(bbox); //sets the point clicked by the client SharpMap.Geometries.Point p = new SharpMap.Geometries.Point(); Single x = 0; Single y = 0; //tries to set the x to the Param I, if the client send an X, it will try the X, if both fail, exception is thrown if (context.Request.Params["X"] != null) try { x = System.Convert.ToSingle(context.Request.Params["X"]); } catch { WmsException.ThrowWmsException("Invalid parameters for I"); } if (context.Request.Params["I"] != null) try { x = System.Convert.ToSingle(context.Request.Params["I"]); } catch { WmsException.ThrowWmsException("Invalid parameters for I"); } //same procedure for J (Y) if (context.Request.Params["Y"] != null) try { y = System.Convert.ToSingle(context.Request.Params["Y"]); } catch { WmsException.ThrowWmsException("Invalid parameters for I"); } if (context.Request.Params["J"] != null) try { y = System.Convert.ToSingle(context.Request.Params["J"]); } catch { WmsException.ThrowWmsException("Invalid parameters for I"); } p = map.ImageToWorld(new System.Drawing.PointF(x, y)); int fc; try { fc = System.Convert.ToInt16(context.Request.Params["FEATURE_COUNT"]); if (fc < 1) fc = 1; } catch { fc = 1; } String vstr = "GetFeatureInfo results: \n"; string[] requestLayers = context.Request.Params["QUERY_LAYERS"].Split(new[] { ',' }); foreach (string requestLayer in requestLayers) { bool found = false; foreach (ILayer mapLayer in map.Layers) { if (String.Equals(mapLayer.LayerName, requestLayer, StringComparison.InvariantCultureIgnoreCase)) { found = true; if (!(mapLayer is ICanQueryLayer)) continue; ICanQueryLayer queryLayer = mapLayer as ICanQueryLayer; if (queryLayer.IsQueryEnabled) { Single queryBoxMinX = x - (_pixelSensitivity); Single queryBoxMinY = y - (_pixelSensitivity); Single queryBoxMaxX = x + (_pixelSensitivity); Single queryBoxMaxY = y + (_pixelSensitivity); SharpMap.Geometries.Point minXY = map.ImageToWorld(new System.Drawing.PointF(queryBoxMinX, queryBoxMinY)); SharpMap.Geometries.Point maxXY = map.ImageToWorld(new System.Drawing.PointF(queryBoxMaxX, queryBoxMaxY)); BoundingBox queryBox = new BoundingBox(minXY, maxXY); SharpMap.Data.FeatureDataSet fds = new SharpMap.Data.FeatureDataSet(); queryLayer.ExecuteIntersectionQuery(queryBox, fds); if (_intersectDelegate != null) { fds.Tables[0] = _intersectDelegate(fds.Tables[0], queryBox); } if (fds.Tables.Count == 0) { vstr = vstr + "\nSearch returned no results on layer: " + requestLayer; } else { if (fds.Tables[0].Rows.Count == 0) { vstr = vstr + "\nSearch returned no results on layer: " + requestLayer + " "; } else { //if featurecount < fds...count, select smallest bbox, because most likely to be clicked vstr = vstr + "\n Layer: '" + requestLayer + "'\n Featureinfo:\n"; int[] keys = new int[fds.Tables[0].Rows.Count]; double[] area = new double[fds.Tables[0].Rows.Count]; for (int l = 0; l < fds.Tables[0].Rows.Count; l++) { SharpMap.Data.FeatureDataRow fdr = fds.Tables[0].Rows[l] as SharpMap.Data.FeatureDataRow; area[l] = fdr.Geometry.GetBoundingBox().GetArea(); keys[l] = l; } Array.Sort(area, keys); if (fds.Tables[0].Rows.Count < fc) { fc = fds.Tables[0].Rows.Count; } for (int k = 0; k < fc; k++) { for (int j = 0; j < fds.Tables[0].Rows[keys[k]].ItemArray.Length; j++) { vstr = vstr + " '" + fds.Tables[0].Rows[keys[k]].ItemArray[j].ToString() + "'"; } if ((k + 1) < fc) vstr = vstr + ",\n"; } } } } } } if (found == false) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.LayerNotDefined, "Unknown layer '" + requestLayer + "'"); return; } } context.Response.Clear(); context.Response.ContentType = "text/plain"; context.Response.Charset = "windows-1252"; context.Response.Write(vstr); context.Response.Flush(); context.Response.End(); } else if (String.Compare(context.Request.Params["REQUEST"], "GetMap", ignorecase) == 0) //Map requested { //Check for required parameters if (context.Request.Params["LAYERS"] == null) { WmsException.ThrowWmsException("Required parameter LAYERS not specified"); return; } if (context.Request.Params["STYLES"] == null) { WmsException.ThrowWmsException("Required parameter STYLES not specified"); return; } if (context.Request.Params["CRS"] == null) { WmsException.ThrowWmsException("Required parameter CRS not specified"); return; } else if (context.Request.Params["CRS"] != "EPSG:" + map.Layers[0].SRID) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidCRS, "CRS not supported"); return; } if (context.Request.Params["BBOX"] == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter BBOX not specified"); return; } if (context.Request.Params["WIDTH"] == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter WIDTH not specified"); return; } if (context.Request.Params["HEIGHT"] == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter HEIGHT not specified"); return; } if (context.Request.Params["FORMAT"] == null) { WmsException.ThrowWmsException("Required parameter FORMAT not specified"); return; } //Set background color of map if (String.Compare(context.Request.Params["TRANSPARENT"], "TRUE", ignorecase) == 0) map.BackColor = Color.Transparent; else if (context.Request.Params["BGCOLOR"] != null) { try { map.BackColor = ColorTranslator.FromHtml(context.Request.Params["BGCOLOR"]); } catch { WmsException.ThrowWmsException("Invalid parameter BGCOLOR"); return; } ; } else map.BackColor = Color.White; //Get the image format requested ImageCodecInfo imageEncoder = GetEncoderInfo(context.Request.Params["FORMAT"]); if (imageEncoder == null) { WmsException.ThrowWmsException("Invalid MimeType specified in FORMAT parameter"); return; } //Parse map size int width = 0; int height = 0; if (!int.TryParse(context.Request.Params["WIDTH"], out width)) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Invalid parameter WIDTH"); return; } else if (description.MaxWidth > 0 && width > description.MaxWidth) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Parameter WIDTH too large"); return; } if (!int.TryParse(context.Request.Params["HEIGHT"], out height)) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Invalid parameter HEIGHT"); return; } else if (description.MaxHeight > 0 && height > description.MaxHeight) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Parameter HEIGHT too large"); return; } map.Size = new Size(width, height); BoundingBox bbox = ParseBBOX(context.Request.Params["bbox"]); if (bbox == null) { WmsException.ThrowWmsException("Invalid parameter BBOX"); return; } map.PixelAspectRatio = (width / (double)height) / (bbox.Width / bbox.Height); map.Center = bbox.GetCentroid(); map.Zoom = bbox.Width; //Set layers on/off if (!String.IsNullOrEmpty(context.Request.Params["LAYERS"])) //If LAYERS is empty, use default layer on/off settings { string[] layers = context.Request.Params["LAYERS"].Split(new[] { ',' }); if (description.LayerLimit > 0) { if (layers.Length == 0 && map.Layers.Count > description.LayerLimit || layers.Length > description.LayerLimit) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Too many layers requested"); return; } } foreach (ILayer layer in map.Layers) layer.Enabled = false; foreach (string layer in layers) { //SharpMap.Layers.ILayer lay = map.Layers.Find(delegate(SharpMap.Layers.ILayer findlay) { return findlay.LayerName == layer; }); ILayer lay = null; for (int i = 0; i < map.Layers.Count; i++) if (String.Equals(map.Layers[i].LayerName, layer, StringComparison.InvariantCultureIgnoreCase)) lay = map.Layers[i]; if (lay == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.LayerNotDefined, "Unknown layer '" + layer + "'"); return; } else lay.Enabled = true; } } //Render map Image img = map.GetMap(); //Png can't stream directy. Going through a memorystream instead MemoryStream MS = new MemoryStream(); img.Save(MS, imageEncoder, null); img.Dispose(); byte[] buffer = MS.ToArray(); context.Response.Clear(); context.Response.ContentType = imageEncoder.MimeType; context.Response.OutputStream.Write(buffer, 0, buffer.Length); context.Response.End(); } else WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Invalid request"); }
/// <summary> /// Returns the next array of Coordinates in the stream. /// </summary> /// <param name="tokenizer">Tokenizer over a stream of text in Well-known Text format. The /// next element returned by the stream should be "(" (the beginning of "(x1 y1, x2 y2, ..., xn yn)" or /// "EMPTY".</param> /// <returns>The next array of Coordinates in the stream, or an empty array of "EMPTY" is the /// next element returned by the stream.</returns> private static List<SharpMap.Geometries.Point> GetCoordinates(WktStreamTokenizer tokenizer) { List<SharpMap.Geometries.Point> coordinates = new List<SharpMap.Geometries.Point>(); string nextToken = GetNextEmptyOrOpener(tokenizer); if (nextToken=="EMPTY") return coordinates; SharpMap.Geometries.Point externalCoordinate = new SharpMap.Geometries.Point(); SharpMap.Geometries.Point internalCoordinate = new SharpMap.Geometries.Point(); externalCoordinate.X = GetNextNumber(tokenizer); externalCoordinate.Y = GetNextNumber(tokenizer); coordinates.Add(externalCoordinate); nextToken = GetNextCloserOrComma(tokenizer); while (nextToken==",") { internalCoordinate = new SharpMap.Geometries.Point(); internalCoordinate.X = GetNextNumber(tokenizer); internalCoordinate.Y = GetNextNumber(tokenizer); coordinates.Add(internalCoordinate); nextToken = GetNextCloserOrComma(tokenizer); } return coordinates; }
internal static GisSharpBlog.NetTopologySuite.Geometries.Point ToNTSPoint(Point point, GeometryFactory factory) { return factory.CreatePoint(ToNTSCoordinate(point, factory)) as GisSharpBlog.NetTopologySuite.Geometries.Point; }
internal static Coordinate ToNTSCoordinate(Point point, GeometryFactory factory) { return new Coordinate(point.X, point.Y); }
// add image pixels to the map protected virtual void GetPreview(Dataset dataset, System.Drawing.Size size, System.Drawing.Graphics g, BoundingBox displayBbox, ICoordinateSystem mapProjection, Map map) { 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 double[] { 999.5, 1, 0, 1000.5, 0, -1 }; GT = 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; GdiPoint bitmapTL = new GdiPoint(), bitmapBR = new GdiPoint(); SMPoint imageTL = new SMPoint(), imageBR = new SMPoint(); 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.Left > _Envelope.Right) || (displayBbox.Right < _Envelope.Left) || (displayBbox.Top < _Envelope.Bottom) || (displayBbox.Bottom > _Envelope.Top)) 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.Left, _Envelope.Left); top = Math.Min(displayBbox.Top, _Envelope.Top); right = Math.Min(displayBbox.Right, _Envelope.Right); bottom = Math.Max(displayBbox.Bottom, _Envelope.Bottom); trueImageBbox = new BoundingBox(left, bottom, right, top); // put display bounds into current projection if (_transform != null) shownImageBbox = GeometryTransform.TransformBox(trueImageBbox, _transform.MathTransform.Inverse()); else shownImageBbox = trueImageBbox; // find min/max x and y pixels needed from image imageBR.X = (int)(Math.Max(GT.GroundToImage(shownImageBbox.TopLeft).X, Math.Max(GT.GroundToImage(shownImageBbox.TopRight).X, Math.Max(GT.GroundToImage(shownImageBbox.BottomLeft).X, GT.GroundToImage(shownImageBbox.BottomRight).X))) + 1); imageBR.Y = (int)(Math.Max(GT.GroundToImage(shownImageBbox.TopLeft).Y, Math.Max(GT.GroundToImage(shownImageBbox.TopRight).Y, Math.Max(GT.GroundToImage(shownImageBbox.BottomLeft).Y, GT.GroundToImage(shownImageBbox.BottomRight).Y))) + 1); imageTL.X = (int)Math.Min(GT.GroundToImage(shownImageBbox.TopLeft).X, Math.Min(GT.GroundToImage(shownImageBbox.TopRight).X, Math.Min(GT.GroundToImage(shownImageBbox.BottomLeft).X, GT.GroundToImage(shownImageBbox.BottomRight).X))); imageTL.Y = (int)Math.Min(GT.GroundToImage(shownImageBbox.TopLeft).Y, Math.Min(GT.GroundToImage(shownImageBbox.TopRight).Y, Math.Min(GT.GroundToImage(shownImageBbox.BottomLeft).Y, GT.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 SMPoint groundBR = GT.ImageToGround(imageBR); SMPoint groundTL = GT.ImageToGround(imageTL); // convert ground coordinates to map coordinates to figure out where to place the bitmap bitmapBR = new GdiPoint((int)map.WorldToImage(trueImageBbox.BottomRight).X + 1, (int)map.WorldToImage(trueImageBbox.BottomRight).Y + 1); bitmapTL = new GdiPoint((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 yellow, so we can make fill transparent for (int y = 0; y < bitmapHeight; y++) { byte* brow = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride); for (int x = 0; x < bitmapLength; x++) { brow[x * 3 + 0] = 0; brow[x * 3 + 1] = 255; brow[x * 3 + 2] = 255; } } // 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]; // get data from image for (int i = 0; i < Bands; i++) { tempBuffer[i] = new double[displayImageLength * displayImageHeight]; band[i] = dataset.GetRasterBand(i + 1); 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) ch[i] = 3; // infrared else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_GrayIndex) ch[i] = 0; 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.Min.X; double dblMapMaxY = map.Envelope.Max.Y; double geoTop, geoLeft, geoHorzPixRes, geoVertPixRes, geoXRot, geoYRot; // get inverse values geoTop = GT.Inverse[3]; geoLeft = GT.Inverse[0]; geoHorzPixRes = GT.Inverse[1]; geoVertPixRes = GT.Inverse[5]; geoXRot = GT.Inverse[2]; geoYRot = GT.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 IMathTransform inverseTransform = null; if (_transform != null) inverseTransform = _transform.MathTransform.Inverse(); 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 + (double)bitmapTLX) * dblMapPixelWidth; GndY = dblMapMaxY - (PixY + (double)bitmapTLY) * dblMapPixelHeight; // transform ground point if needed if (_transform != null) { dblPoint = inverseTransform.Transform(new double[] { GndX, GndY }); 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 (_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(Color.Yellow); if (_transparentColor != Color.Empty) bitmap.MakeTransparent(_transparentColor); g.DrawImage(bitmap, new System.Drawing.Point(bitmapTL.X, bitmapTL.Y)); }
/// <summary> /// Initializes a new map /// </summary> /// <param name="size">Size of map in pixels</param> public Map(Size size) { Size = size; _Layers = new LayerCollection(); _backgroundLayers = new LayerCollection(); _backgroundLayers.ListChanged += _Layers_ListChanged; //_Layers.ListChanged += new System.ComponentModel.ListChangedEventHandler(_Layers_ListChanged); _variableLayers = new VariableLayerCollection(_Layers); BackColor = Color.Transparent; _MaximumZoom = double.MaxValue; _MinimumZoom = 0; _MapTransform = new Matrix(); MapTransformInverted = new Matrix(); _Center = new Point(0, 0); _Zoom = 1; _PixelAspectRatio = 1.0; }