public static SqlGeography CreatePolygon(Coordinates[] coordinates, int srid)
        {
            var list = coordinates.Distinct().ToList();
            
            var b = new SqlGeographyBuilder();
            b.SetSrid(srid);
            b.BeginGeography(OpenGisGeographyType.Polygon);
            b.BeginFigure(list[0].Latitude, list[0].Longitude);

            for (var i = 1; i < list.Count; i++)
                b.AddLine(list[i].Latitude, list[i].Longitude);

            b.AddLine(list[0].Latitude, list[0].Longitude);
            b.EndFigure();
            b.EndGeography();

            //Fix left-hand rule. We always want left-hand.
            var g = b.ConstructedGeography;
            if (!g.STIsValid())
                throw new SisoDbException(ExceptionMessages.NotAValidPolygon.Inject(g.IsValidDetailed()));

            if (g.EnvelopeAngle() > 90)
                g = g.ReorientObject(); 

            return g;
        }
Exemple #2
0
        /// <summary>
        /// Converts the given value from original representation to alternative one.
        /// </summary>
        /// <param name="value">Value in its original representation.</param>
        /// <returns>Value in its alternative representation.</returns>
        public override object Convert(object value)
        {
            object ret = null;
            Models.Location l = null;
            SqlGeographyBuilder builder = null;

            if (value != null && value is Models.Location)
            {
                l = value as Models.Location;
                builder = new SqlGeographyBuilder();

                builder.SetSrid(4326);

                builder.BeginGeography(OpenGisGeographyType.Point);

                builder.BeginFigure(l.Latitude, l.Longitude);
                builder.EndFigure();

                builder.EndGeography();

                ret = builder.ConstructedGeography;
            }

            return ret;
        }
		private static void Internal_FillGeographyBuilder(SqlGeographyBuilder gb, Point point)
		{
			gb.BeginGeography(OpenGisGeographyType.Point);
			GeographicPosition pos = point.Coordinates as GeographicPosition;
			gb.BeginFigure(pos.Latitude, pos.Longitude);
			gb.EndFigure();
			gb.EndGeography();
		}
Exemple #4
0
 //LONGITUDE=item1, LATITUDE=item2
 public static SqlGeography CreatePoint(this Tuple<double, double> coordinates, int srid = 4326)
 {
     var b = new SqlGeographyBuilder();
     b.SetSrid(srid);
     b.BeginGeography(OpenGisGeographyType.Point);
     b.BeginFigure(coordinates.Item2, coordinates.Item1);
     b.EndFigure();
     b.EndGeography();
     return b.ConstructedGeography;
 }
Exemple #5
0
        public SqlGeography asSqlGeography()
        {
            SqlGeographyBuilder builder = new SqlGeographyBuilder();
            builder.SetSrid(4326);
            builder.BeginGeography(OpenGisGeographyType.Point);
            builder.BeginFigure(latitude, longitude);
            builder.EndFigure();
            builder.EndGeography();

            return builder.ConstructedGeography;
        }
		private static void Internal_FillGeographyBuilder(SqlGeographyBuilder gb, MultiPoint multiPoint)
		{
			gb.BeginGeography(OpenGisGeographyType.MultiPoint);
			List<Point> coords = multiPoint.Coordinates as List<Point>;
			foreach (var coord in coords)
			{
				GeographicPosition pos = coord.Coordinates as GeographicPosition;
				gb.BeginGeography(OpenGisGeographyType.Point);
				gb.BeginFigure(pos.Latitude, pos.Longitude);
				gb.EndFigure();
				gb.EndGeography();
			}
			gb.EndGeography();
		}
Exemple #7
0
 public static SqlGeography CreateGeography(this string points, out OpenGisGeographyType geographyType, int srid = 4326)
 {
     geographyType = OpenGisGeographyType.Point;
     SqlGeography firstPoint = null;
     var pts = points.Trim().Split(new string[] { "\n" }, StringSplitOptions.None).ToList();
     pts.Add(null);
     var b = new SqlGeographyBuilder();
     b.SetSrid(srid);
     b.BeginGeography(OpenGisGeographyType.GeometryCollection);
     var coordinates = new List<Tuple<double, double>>();
     for (int i = 0; i < pts.Count; i++)
     {
         if (string.IsNullOrWhiteSpace(pts[i]))
         {
             if (coordinates.Count == 1)
             {
                 if (firstPoint == null)
                     firstPoint = coordinates[0].CreatePoint();
                 b.BeginGeography(OpenGisGeographyType.Point);
                 b.BeginFigure(coordinates[0].Item2, coordinates[0].Item1);
                 b.EndFigure();
                 b.EndGeography();
             }
             else if (coordinates.Count > 1)
             {
                 geographyType = OpenGisGeographyType.GeometryCollection;
                 var list = coordinates.Distinct().ToList();
                 b.BeginGeography(OpenGisGeographyType.Polygon);
                 b.BeginFigure(list[0].Item2, list[0].Item1);
                 for (var j = 1; j < list.Count; j++)
                     b.AddLine(list[j].Item2, list[j].Item1);
                 b.AddLine(list[0].Item2, list[0].Item1);
                 b.EndFigure();
                 b.EndGeography();
             }
             coordinates = new List<Tuple<double, double>>();
             continue;
         }
         var pt = pts[i].Trim().Split(new string[] { " ", ",", ";", "\t", ":", "\r" }, StringSplitOptions.RemoveEmptyEntries);
         coordinates.Add(new Tuple<double, double>(double.Parse(pt[0]), double.Parse(pt[1])));
     }
     b.EndGeography();
     if (geographyType == OpenGisGeographyType.GeometryCollection)
         return b.ConstructedGeography.EnvelopeAngle() > 90 ? b.ConstructedGeography.ReorientObject() : b.ConstructedGeography;
     else
         return firstPoint;
 }
Exemple #8
0
        public override SqlGeography AsSqlGeography()
        {
            SqlGeographyBuilder b = new SqlGeographyBuilder();

            b.SetSrid(4326);
            b.BeginGeography(OpenGisGeographyType.LineString);
            if (this.Points.Count > 0)
            {
                b.BeginFigure(this.Points[0].Lat, this.Points[0].Long, this.Points[0].Z, this.Points[0].Time.HasValue ? (double?)null : this.Points[0].Time.Value.ToOADate());
            }
            for (int i = 1; i < this.Points.Count; i++)
            {
                b.AddLine(this.Points[i].Lat, this.Points[i].Long, this.Points[i].Z, this.Points[i].Time.HasValue ? (double?)null : this.Points[i].Time.Value.ToOADate());
            }
            b.EndFigure();
            b.EndGeography();
            return(b.ConstructedGeography);
        }
        private SqlGeography CreateGeographyLine()
        {
            var builder = new SqlGeographyBuilder();

            builder.SetSrid(4326);
            builder.BeginGeography(OpenGisGeographyType.LineString);
            builder.BeginFigure(points[0].Latitude, points[0].Longitude);
            for (var i = 1; i != points.Count; ++i)
            {
                builder.AddLine(points[i].Latitude, points[i].Longitude);
            }
            builder.EndFigure();
            builder.EndGeography();

            var res = builder.ConstructedGeography;

            return(res);
        }
Exemple #10
0
        /// <summary>
        /// Build an SqlGeography Polygon from a bounding box.
        /// </summary>
        /// <param name="box">Bounding Box</param>
        /// <returns>SqlGeography Polygon</returns>
        public static SqlGeography GeographyFromBoundingBox(Models.BoundingBox box)
        {
            var geob = new SqlGeographyBuilder();

            geob.SetSrid(SRID);
            geob.BeginGeography(OpenGisGeographyType.Polygon);
            geob.BeginFigure(box.South, box.West);
            geob.AddLine(box.South, box.East);
            geob.AddLine(box.North, box.East);
            geob.AddLine(box.North, box.West);
            geob.AddLine(box.South, box.West);
            geob.EndFigure();
            geob.EndGeography();
            var geog = geob.ConstructedGeography;

            //Trace.WriteLine("GeographyFromBoundingBox : " + geog.AsGml().Value);
            return(geog);
        }
Exemple #11
0
        /// <summary>
        /// Build an SqlGeography Polygon from a GeoJson Polygon.
        /// </summary>
        /// <param name="poly">GeoJson Polygon</param>
        /// <returns>SqlGeography Polygon</returns>
        public static SqlGeography GeographyFromGeoJsonPolygon(DurMap.Site.Models.GeoJson.Polygon poly)
        {
            var geob = new SqlGeographyBuilder();

            geob.SetSrid(SRID);
            geob.BeginGeography(OpenGisGeographyType.Polygon);
            geob.BeginFigure(poly.coordinates[0][0][1], poly.coordinates[0][0][0]);
            foreach (var pair in poly.coordinates[0].Skip(1))
            {
                geob.AddLine(pair[1], pair[0]);
            }
            geob.EndFigure();
            geob.EndGeography();
            var geog = geob.ConstructedGeography;

            //Trace.WriteLine(geog.AsGml().Value);
            return(geog);
        }
Exemple #12
0
        //LONGITUDE=item1, LATITUDE=item2
        public static SqlGeography CreatePolygon(this List<Tuple<double, double>> coordinates, int srid = 4326)
        {
            var list = coordinates.Distinct().ToList();
            var b = new SqlGeographyBuilder();
            b.SetSrid(srid);
            b.BeginGeography(OpenGisGeographyType.Polygon);
            b.BeginFigure(list[0].Item2, list[0].Item1);

            for (var i = 1; i < list.Count; i++)
                b.AddLine(list[i].Item2, list[i].Item1);

            b.AddLine(list[0].Item2, list[0].Item1);
            b.EndFigure();
            b.EndGeography();

            return b.ConstructedGeography.EnvelopeAngle() > 90
                ? b.ConstructedGeography.ReorientObject()
                : b.ConstructedGeography;
        }
Exemple #13
0
        private static void AddMultiPoint(SqlGeographyBuilder builder, GeoJsonMultiPoint geometry, bool isLongitudeFirst)
        {
            builder.BeginGeography(OpenGisGeographyType.MultiPoint);

            foreach (var item in geometry.Coordinates)
            {
                builder.BeginGeography(OpenGisGeographyType.Point);

                var temporaryPoint = IRI.Msh.Common.Primitives.Point.Parse(item, isLongitudeFirst);

                builder.BeginFigure(temporaryPoint.Y, temporaryPoint.X);

                builder.EndFigure();

                builder.EndGeography();
            }

            builder.EndGeography();
        }
Exemple #14
0
        private static SqlGeography BuildLine(List <SqlGeography> data)
        {
            var lineConstructor = new SqlGeographyBuilder();

            lineConstructor.SetSrid(4326);
            lineConstructor.BeginGeography(OpenGisGeographyType.LineString);
            lineConstructor.BeginFigure((double)data[0].Lat, (double)data[0].Long);
            for (var i = 1; i < data.Count; i++)
            {
                var point = data[i];
                lineConstructor.AddLine((double)point.Lat, (double)point.Long);
            }
            lineConstructor.EndFigure();
            lineConstructor.EndGeography();

            var resultLine = lineConstructor.ConstructedGeography;

            return(resultLine.MakeValid());
        }
Exemple #15
0
        private static void AddRing(SqlGeographyBuilder builder, SMLinearRing linearRing)
        {
            if (linearRing.NumPoints < 3)
            {
                return;
            }

            //if (linearRing.Area == 0)
            //    return;

            var coords = linearRing.Coordinates;

            builder.BeginFigure(coords[0].Y, coords[0].X);
            for (var i = 1; i < linearRing.NumPoints; i++)
            {
                var pt = coords[i];
                builder.AddLine(pt.Y, pt.X);
            }
            builder.EndFigure();
        }
        public static SqlGeography CreatePolygon(IEnumerable<Coordinates> coordinates, int srid = 4326)
        {
            var list = coordinates.Distinct().ToList();

            var b = new SqlGeographyBuilder();
            b.SetSrid(srid);
            b.BeginGeography(OpenGisGeographyType.Polygon);
            b.BeginFigure(list[0].Latitude, list[0].Longitude);

            for (var i = 1; i < list.Count; i++)
                b.AddLine(list[i].Latitude, list[i].Longitude);

            b.AddLine(list[0].Latitude, list[0].Longitude);
            b.EndFigure();
            b.EndGeography();

            if(b.ConstructedGeography.EnvelopeAngle() > 90)
                return b.ConstructedGeography.ReorientObject();

            return b.ConstructedGeography;
        }
Exemple #17
0
        private static void Internal_FillGeographyBuilder(SqlGeographyBuilder gb, LineString lineString)
        {
            gb.BeginGeography(OpenGisGeographyType.LineString);
            bool beginFigureCalled = false;

            foreach (var ipos in lineString.Coordinates)
            {
                Position pos = ipos as Position;
                if (!beginFigureCalled)
                {
                    gb.BeginFigure(pos.Latitude, pos.Longitude);
                    beginFigureCalled = true;
                }
                else
                {
                    gb.AddLine(pos.Latitude, pos.Longitude);
                }
            }
            gb.EndFigure();
            gb.EndGeography();
        }
Exemple #18
0
 private SqlGeography TryMakePolygon(IList <SortedPoint> list)
 {
     try
     {
         var builder = new SqlGeographyBuilder();
         builder.SetSrid(4326);
         builder.BeginGeography(OpenGisGeographyType.Polygon);
         builder.BeginFigure(list[0].Latitude, list[0].Longitude);
         for (var i = 1; i != list.Count; ++i)
         {
             builder.AddLine(list[i].Latitude, list[i].Longitude);
         }
         builder.EndFigure();
         builder.EndGeography();
         return(builder.ConstructedGeography);
     }
     catch
     {
         return(null);
     }
 }
Exemple #19
0
        //private static void AddGeometryCollection(SqlGeometryBuilder builder, IGeoJsonGeometry geometry, bool isLongitudeFirst)
        //{
        //    builder.BeginGeometry(OpenGisGeometryType.GeometryCollection);

        //    foreach (var item in geometry.Geometries)
        //    {
        //        if (geometry.IsNullOrEmpty())
        //        {
        //            SqlSpatialExtensions.AddEmptySqlGeometry(builder, item.Type);
        //        }

        //        switch (item.Type)
        //        {
        //            case GeometryType.Point:
        //                AddPoint(builder, item);
        //                break;
        //            case GeometryType.LineString:
        //                AddLineString(builder, item);
        //                break;
        //            case GeometryType.Polygon:
        //                AddPolygon(builder, item);
        //                break;
        //            case GeometryType.MultiPoint:
        //                AddMultiPoint(builder, item);
        //                break;
        //            case GeometryType.MultiLineString:
        //                AddMultiLineString(builder, item);
        //                break;
        //            case GeometryType.MultiPolygon:
        //                AddMultiPolygon(builder, item);
        //                break;
        //            case GeometryType.GeometryCollection:
        //            case GeometryType.CircularString:
        //            case GeometryType.CompoundCurve:
        //            case GeometryType.CurvePolygon:
        //            default:
        //                throw new NotImplementedException();
        //        }
        //    }

        //    builder.EndGeometry();
        //}

        private static void AddLineStringOrRing(SqlGeographyBuilder builder, double[][] geometry, bool isRing, bool isLongitudeFirst)
        {
            var firstPoint = Point.Parse(geometry[0], isLongitudeFirst);

            builder.BeginFigure(firstPoint.Y, firstPoint.X);

            for (int i = 1; i < geometry.Length; i++)
            {
                var point = Point.Parse(geometry[i], isLongitudeFirst);

                builder.AddLine(point.Y, point.X);
            }

            //1399.08.19
            //should not manually repeat the last point
            //if (isRing)
            //{
            //    builder.AddLine(firstPoint.X, firstPoint.Y);
            //}

            builder.EndFigure();
        }
Exemple #20
0
        //LONGITUDE=item1, LATITUDE=item2
        public static SqlGeography CreatePolygon(this List <Tuple <double, double> > coordinates, int srid = 4326)
        {
            var list = coordinates.Distinct().ToList();
            var b    = new SqlGeographyBuilder();

            b.SetSrid(srid);
            b.BeginGeography(OpenGisGeographyType.Polygon);
            b.BeginFigure(list[0].Item2, list[0].Item1);

            for (var i = 1; i < list.Count; i++)
            {
                b.AddLine(list[i].Item2, list[i].Item1);
            }

            b.AddLine(list[0].Item2, list[0].Item1);
            b.EndFigure();
            b.EndGeography();

            return(b.ConstructedGeography.EnvelopeAngle() > 90
                ? b.ConstructedGeography.ReorientObject()
                : b.ConstructedGeography);
        }
Exemple #21
0
        private void AddCoordinate(SqlGeographyBuilder builder, ICoordinateSequence coordinates, int index, int geographyIndex)
        {
            var x = coordinates.GetOrdinate(index, Ordinate.Y);
            var y = coordinates.GetOrdinate(index, Ordinate.X);

            Double?z = null, m = null;

            if ((HandleOrdinates & Ordinates.Z) > 0)
            {
                z = coordinates.GetOrdinate(index, Ordinate.Z);
                if (Double.IsNaN(z.Value))
                {
                    z = 0d;
                }
            }

            if ((HandleOrdinates & Ordinates.M) > 0)
            {
                m = coordinates.GetOrdinate(index, Ordinate.M);
                if (Double.IsNaN(m.Value))
                {
                    m = 0d;
                }
            }

            if (geographyIndex == 0)
            {
                builder.BeginFigure(x, y, z, m);
            }
            else
            {
                builder.AddLine(x, y, z, m);
            }

            if (geographyIndex == coordinates.Count - 1)
            {
                builder.EndFigure();
            }
        }
        public void AddRoadViewWithCoordinates(string imagepath, double lat, double lon)
        {
            SqlGeographyBuilder builder = new SqlGeographyBuilder();

            builder.SetSrid(4326);

            builder.BeginGeography(OpenGisGeographyType.Point);
            builder.BeginFigure(lat, lon);
            builder.EndFigure();
            builder.EndGeography();


            SqlCommand cmd = new SqlCommand();

            SqlConnection conn = GetConn();

            try
            {
                cmd.Connection = conn;

                cmd.CommandText =
                    "INSERT imageWithCoordinates(Coordinates, ImagePath) VALUES(@coordinates, @imagepath)";

                SqlParameter coordinatesParam = new SqlParameter();
                coordinatesParam.ParameterName = "coordinates";
                coordinatesParam.UdtTypeName   = "Geography";
                coordinatesParam.Value         = builder.ConstructedGeography;

                cmd.Parameters.Add(coordinatesParam);
                cmd.Parameters.AddWithValue("imagepath", imagepath);

                cmd.ExecuteNonQuery();
            }
            finally
            {
                conn.Close();
            }
        }
Exemple #23
0
        //Not supporting Z and M values
        public static void ProjectLineString(SqlGeographyBuilder builder, SqlGeometry lineString, Func <IPoint, IPoint> mapFunction)
        {
            if (lineString.IsNull)
            {
                return;
            }

            int numberOfPoints = lineString.STNumPoints().Value;

            //Point startPoint = mapFunction(new Point(lineString.STStartPoint().Long.Value, lineString.STStartPoint().Lat.Value));
            var startPoint = mapFunction(lineString.STStartPoint().AsPoint());

            builder.BeginFigure(startPoint.Y, startPoint.X);

            for (int i = 2; i <= numberOfPoints; i++)
            {
                var point = mapFunction(GetPoint(lineString, i));

                builder.AddLine(point.Y, point.X);
            }

            builder.EndFigure();
        }
Exemple #24
0
        public void BuildLineString()
        {
            SqlGeographyBuilder b = new SqlGeographyBuilder();

            b.SetSrid(4326);
            b.BeginGeography(OpenGisGeographyType.LineString);
            b.BeginFigure(1, 2);
            b.AddLine(3, 4, 10, null);
            b.AddLine(6, 7, 11, 12);
            b.EndFigure();
            b.EndGeography();
            var g = b.ConstructedGeography;

            Assert.AreEqual("LineString", g.STGeometryType());
            Assert.AreEqual(3, g.STNumPoints());
            Assert.AreEqual(1, g.STStartPoint().Lat);
            Assert.AreEqual(2, g.STStartPoint().Long);
            Assert.AreEqual(6, g.STEndPoint().Lat);
            Assert.AreEqual(7, g.STEndPoint().Long);
            Assert.AreEqual(3, g.STPointN(2).Lat);
            Assert.AreEqual(4, g.STPointN(2).Long);
            Assert.IsTrue(g.STPointN(2).HasZ);
            Assert.IsFalse(g.STPointN(2).HasM);
        }
Exemple #25
0
        public static SqlGeography GetPoint(SqlDouble xOrLon, SqlDouble yOrLat)
        {
            if (xOrLon.IsNull || yOrLat.IsNull)
            {
                return(SqlGeography.Null);
            }
            var builder = new SqlGeographyBuilder();

            builder.SetSrid(4326);
            builder.BeginGeography(OpenGisGeographyType.Point);


            if (Math.Abs(xOrLon.Value) <= 180 && Math.Abs(yOrLat.Value) <= 180)
            {
                builder.BeginFigure(yOrLat.Value, xOrLon.Value);
            }
            else
            {
                builder.BeginFigure(GetLat(yOrLat).Value, GetLon(xOrLon).Value);
            }
            builder.EndFigure();
            builder.EndGeography();
            return(builder.ConstructedGeography);
        }
        public List <Orchestrator.WebUI.Services.Point> GetPointsPenetrated(List <LatLong> latLongs)
        {
            List <Orchestrator.WebUI.Services.Point> points = new List <Orchestrator.WebUI.Services.Point>();

            if (latLongs.Count > 0)
            {
                SqlGeographyBuilder geogBuilder = new SqlGeographyBuilder();
                geogBuilder.SetSrid(4326);
                geogBuilder.BeginGeography(OpenGisGeographyType.LineString);

                LatLong firstLatLong       = null;
                bool    firstLatLongStored = false;
                foreach (LatLong latLong in latLongs)
                {
                    if (!firstLatLongStored)
                    {
                        firstLatLong = latLong;
                        geogBuilder.BeginFigure(firstLatLong.Latitude, firstLatLong.Longitude);
                        firstLatLongStored = true;
                    }
                    else
                    {
                        geogBuilder.AddLine(latLong.Latitude, latLong.Longitude);
                    }
                }

                //geogBuilder.AddLine(firstLatLong.Latitude, firstLatLong.Longitude); //Note: Last Point same as First
                geogBuilder.EndFigure();

                geogBuilder.EndGeography();
                SqlGeography rectangle = null;

                try
                {
                    rectangle = geogBuilder.ConstructedGeography;
                }
                catch (Exception ex)
                {
                    //SqlGeometryBuilder gb = new SqlGeometryBuilder();
                    //gb.SetSrid(4326);
                    //gb.BeginGeometry(OpenGisGeometryType.Polygon);

                    //firstLatLong = null;
                    //firstLatLongStored = false;
                    //foreach (LatLong latLong in latLongs)
                    //{
                    //    if (!firstLatLongStored)
                    //    {
                    //        firstLatLong = latLong;
                    //        gb.BeginFigure(firstLatLong.Latitude, firstLatLong.Longitude);
                    //        firstLatLongStored = true;
                    //    }
                    //    else
                    //        gb.AddLine(latLong.Latitude, latLong.Longitude);
                    //}

                    //gb.AddLine(firstLatLong.Latitude, firstLatLong.Longitude); //Note: Last Point same as First
                    //gb.EndFigure();

                    //gb.EndGeometry();

                    //SqlGeometry geom = null;
                    //geom = gb.ConstructedGeometry.MakeValid();

                    ////geom = geom.MakeValid().STUnion(geom.STStartPoint());

                    //rectangle = SqlGeography.STPolyFromText(geom.STAsText(), 4326);
                }

                SqlDataReader dr = null;
                try
                {
                    BusinessLogicLayer.IPoint busPoint = new BusinessLogicLayer.Point();

                    dr = busPoint.GetPointsIntersected(rectangle);

                    while (dr.Read())
                    {
                        Orchestrator.WebUI.Services.Point point = new Orchestrator.WebUI.Services.Point();
                        point.GeofencePoints = new List <LatLong>();
                        point.Description    = dr["PointName"].ToString();
                        point.Latitide       = dr["WGS84Latitude"] != DBNull.Value ? Convert.ToDouble(dr["WGS84Latitude"]) : 0;
                        point.Longitude      = dr["WGS84Longitude"] != DBNull.Value ? Convert.ToDouble(dr["WGS84Longitude"]) : 0;
                        point.PointID        = int.Parse(dr["PointId"].ToString());
                        SqlGeography geofence = (SqlGeography)dr["Geofence"];

                        for (int i = 0; i < geofence.STNumPoints(); i++)
                        {
                            SqlGeography p       = geofence.STPointN(i + 1);
                            LatLong      latLong = new LatLong();
                            latLong.Latitude  = (double)p.Lat;
                            latLong.Longitude = (double)p.Long;
                            point.GeofencePoints.Add(latLong);
                        }
                        points.Add(point);
                    }
                }
                catch (Exception ex)
                {
                    throw;
                }
                finally
                {
                    dr.Close();
                }
            }

            return(points);
        }
Exemple #27
0
        /// <summary>
        /// Builds the route geography.
        /// </summary>
        /// <param name="route">The route.</param>
        /// <returns>
        /// New route geography
        /// </returns>
        private Route BuildRouteGeography(Route route)
        {
            var routeBuilder = new SqlGeographyBuilder();
            routeBuilder.SetSrid(4326);
            routeBuilder.BeginGeography(OpenGisGeographyType.LineString);
            SqlGeography beginPoint = route.StartStop.StopGeography;
            routeBuilder.BeginFigure((double)beginPoint.Lat, (double)beginPoint.Long);

            for (var j = route.StartRouteIndex; j <= route.EndRouteIndex; j++)
            {
                var point = route.RouteGeography.STPointN(j);
                routeBuilder.AddLine((double)point.Lat, (double)point.Long);
            }

            SqlGeography endPoint = route.EndStop.StopGeography;
            routeBuilder.AddLine((double)endPoint.Lat, (double)endPoint.Long);

            routeBuilder.EndFigure();
            routeBuilder.EndGeography();
            route.CurrentPath = routeBuilder.ConstructedGeography;

            return route;
        }
        public static SqlGeography RESTRoute(SqlGeography Start, SqlGeography End, SqlString Mode)
        {
            string feedData = string.Empty;

            if (!(Start.STGeometryType() == "POINT" && Start.STSrid == 4326))
            {
                throw new Exception("Route start must be a single point defined using SRID 4326");
            }
            if (!(End.STGeometryType() == "POINT" && End.STSrid == 4326))
            {
                throw new Exception("Route end must be a single point defined using SRID 4326");
            }
            string travelMode = ((string)Mode).ToUpper();

            if (travelMode != "DRIVING" && travelMode != "WALKING")
            {
                throw new Exception("Mode of travel must be WALKING or DRIVING");
            }

            try
            {
                String key         = "ENTERYOURBINGMAPSKEYHERE";
                String urltemplate = "http://dev.virtualearth.net/REST/V1/Routes/{0}?wp.0={1}&wp.1={2}&rpo=Points&optmz=distance&output=xml&key={3}";
                String Startcoords = String.Concat(Start.Lat, ",", Start.Long);
                String Endcoords   = String.Concat(End.Lat, ",", End.Long);


                // Request the routepoints in the results. See http://msdn.microsoft.com/en-us/library/ff701717.aspx
                String          url          = String.Format(urltemplate, travelMode, Startcoords, Endcoords, key);
                HttpWebRequest  request      = null;
                HttpWebResponse response     = null;
                Stream          stream       = null;
                StreamReader    streamReader = null;

                request               = (HttpWebRequest)WebRequest.Create(url);
                request.Method        = "GET";
                request.ContentLength = 0;
                response              = (HttpWebResponse)request.GetResponse();

                stream       = response.GetResponseStream();
                streamReader = new StreamReader(stream);
                feedData     = streamReader.ReadToEnd();

                response.Close();
                stream.Dispose();
                streamReader.Dispose();
            }


            catch (Exception ex)
            {
                SqlContext.Pipe.Send(ex.Message.ToString());
            }

            // Process the XML response
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(feedData);

            // Define the default XML namespace
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);

            nsmgr.AddNamespace("ab", "http://schemas.microsoft.com/search/local/ws/rest/v1");


            XmlNode routePath = doc.GetElementsByTagName("RoutePath")[0];
            XmlNode line      = routePath["Line"];

            // Create a set of all <Location>s in the response
            XmlNodeList Points = line.SelectNodes("ab:Point", nsmgr);

            SqlGeographyBuilder gb = new SqlGeographyBuilder();

            gb.SetSrid(4326);
            gb.BeginGeography(OpenGisGeographyType.LineString);
            gb.BeginFigure(double.Parse(Points[0]["Latitude"].InnerText), double.Parse(Points[0]["Longitude"].InnerText));

            for (int i = 1; i < Points.Count; i++)
            {
                gb.AddLine(double.Parse(Points[i]["Latitude"].InnerText), double.Parse(Points[i]["Longitude"].InnerText));
            }

            gb.EndFigure();
            gb.EndGeography();

            return(gb.ConstructedGeography);
        }
Exemple #29
0
        private async void CalculateBtn_Clicked(object sender, RoutedEventArgs e)
        {
            MyMap.Children.Clear();
            try
            {
                var r = await CalculateRoute(StartTbx.Text, EndTbx.Text);

                if (r != null &&
                    r.ResourceSets != null &&
                    r.ResourceSets.Length > 0 &&
                    r.ResourceSets[0].Resources != null &&
                    r.ResourceSets[0].Resources.Length > 0)
                {
                    Route route = r.ResourceSets[0].Resources[0] as Route;

                    double[][] routePath = route.RoutePath.Line.Coordinates;

                    var locs = new LocationCollection();

                    //Create SqlGeography from route line points.
                    SqlGeographyBuilder geomBuilder = new SqlGeographyBuilder();
                    geomBuilder.SetSrid(4326);
                    geomBuilder.BeginGeography(OpenGisGeographyType.LineString);
                    geomBuilder.BeginFigure(routePath[0][0], routePath[0][1]);

                    for (int i = 0; i < routePath.Length; i++)
                    {
                        locs.Add(new Microsoft.Maps.MapControl.WPF.Location(routePath[i][0], routePath[i][1]));
                        geomBuilder.AddLine(routePath[i][0], routePath[i][1]);
                    }

                    geomBuilder.EndFigure();
                    geomBuilder.EndGeography();

                    //Calculate distances in countries.
                    var routeGeom = geomBuilder.ConstructedGeography;

                    var sb = new StringBuilder();
                    sb.AppendFormat("Total Driving Distance: {0} KM\r\n", route.TravelDistance);

                    foreach (var c in countries)
                    {
                        if (c.Geom.STIntersects(routeGeom))
                        {
                            sb.AppendFormat("Distnance in {0}: {1:0.##} KM\r\n", c.Name, c.Geom.STIntersection(routeGeom).STLength().Value / 1000);
                        }
                    }

                    OutputTbx.Text = sb.ToString();

                    //Display route on map
                    var routeLine = new MapPolyline()
                    {
                        Locations       = locs,
                        Stroke          = new SolidColorBrush(Colors.Blue),
                        StrokeThickness = 5
                    };

                    MyMap.Children.Add(routeLine);

                    MyMap.SetView(locs, new Thickness(30), 0);
                }
            }
            catch (Exception ex)
            {
            }
        }
Exemple #30
0
        private void UDPListenThread()
        {
            logger = new Logging.EventLogger(); //for the initial dev phase we're going to log a lot, disable this before
            //rolling out to production
            udpListener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint ourEndPoint = new IPEndPoint(IPAddress.Any, 9017);
            IPEndPoint end         = new IPEndPoint(IPAddress.Any, 9017);
            EndPoint   Identifier  = (EndPoint)end;

            udpListener.Bind(ourEndPoint);

            while (true)
            {
                string message = null;;
                try
                {
                    bool fwdThisMessage = true;
                    int  length         = udpListener.ReceiveFrom(data, ref Identifier);
                    message = System.Text.Encoding.UTF8.GetString(data, 0, length);
                    string _ipaddr = ((IPEndPoint)Identifier).Address.ToString();
                    if (message.Contains("<FWD>"))
                    {
                        //it's a forwarded message, remove the <FWD> tags and find the specified IPAddress
                        //then treat it like a normal packet
                        message = message.Replace("<FWD>", "");
                        int firstLT = message.IndexOf('<');
                        _ipaddr        = message.Substring(0, firstLT);
                        message        = message.Replace(_ipaddr + "</FWD>", "");
                        fwdThisMessage = false;
                        //done, let it move on
                    }
                    //JavaScriptSerializer js = new JavaScriptSerializer();
                    TowTruck.TowTruck thisTruck;
                    thisTruck = DataClasses.GlobalData.FindTowTruck(_ipaddr);
                    string type = "";
                    try
                    {
                        if (message.Contains("<GPS>"))
                        {
                            type = "GPS";
                            if (forward == true && fwdThisMessage == true)
                            {
                                string fwdMsg = "<FWD>" + _ipaddr + "</FWD>" + message;
                                foreach (string s in OtherServers)
                                {
                                    udpSend.ForwardMessage(fwdMsg, s);
                                }
                            }
                        }
                    }
                    catch
                    { }
                    try
                    {
                        if (message.Contains("<State>"))
                        {
                            type = "State";
                            if (forward == true && fwdThisMessage == true)
                            {
                                string fwdMsg = "<FWD>" + _ipaddr + "</FWD>" + message;
                                foreach (string s in OtherServers)
                                {
                                    udpSend.ForwardMessage(fwdMsg, s);
                                }
                            }
                        }
                    }
                    catch
                    { }
                    try
                    {
                        if (message.Contains("<IPHistory>"))
                        {
                            type = "IPHistory";
                            if (forward == true && fwdThisMessage == true)
                            {
                                string fwdMsg = "<FWD>" + _ipaddr + "</FWD>" + message;
                                foreach (string s in OtherServers)
                                {
                                    udpSend.ForwardMessage(fwdMsg, s);
                                }
                            }
                        }
                    }
                    catch
                    { }

                    /*
                     * string[] splitMsg = message.Split('|');
                     * string type = splitMsg[0].ToString();
                     * string msg = splitMsg[1].ToString();
                     * */
                    TowTruck.GPS       thisGPS   = null;
                    TowTruck.State     thisState = null;
                    TowTruck.IPHistory history   = null;
                    if (type == "GPS")
                    {
                        //thisGPS = js.Deserialize<TowTruck.GPS>(msg);
                        XmlSerializer ser = new XmlSerializer(typeof(TowTruck.GPS));
                        StringReader  rdr = new StringReader(message);
                        thisGPS = (TowTruck.GPS)ser.Deserialize(rdr);
                        SqlGeographyBuilder builder = new SqlGeographyBuilder();
                        builder.SetSrid(4326);
                        builder.BeginGeography(OpenGisGeographyType.Point);
                        builder.BeginFigure(thisGPS.Lat, thisGPS.Lon);
                        builder.EndFigure();
                        builder.EndGeography();
                        thisGPS.Position = builder.ConstructedGeography;
                    }
                    else if (type == "State")
                    {
                        XmlSerializer ser = new XmlSerializer(typeof(TowTruck.State));
                        //testing, this was causing an error on parse, but couldn't find a reason why
                        message = message.Replace(" xmlns=''", "");
                        StringReader rdr = new StringReader(message);
                        thisState = (TowTruck.State)ser.Deserialize(rdr);
                    }
                    else if (type == "IPHistory")
                    {
                        XmlSerializer ser = new XmlSerializer(typeof(TowTruck.IPHistory));
                        StringReader  rdr = new StringReader(message);
                        history = (TowTruck.IPHistory)ser.Deserialize(rdr);
                    }
                    if (thisTruck != null)
                    {
                        try
                        {
                            thisTruck.LastMessage.LastMessageReceived = DateTime.Now;
                            DataClasses.GlobalData.UpdateTowTruck(_ipaddr, thisTruck);
                            //DataClasses.GlobalData.AddTowTruck(thisTruck);
                            if (string.IsNullOrEmpty(thisTruck.Extended.TruckNumber))
                            {
                                SQL.SQLCode mySQL = new SQL.SQLCode();
                                TowTruck.TowTruckExtended thisExtended = mySQL.GetExtendedData(thisTruck.Identifier);
                                thisTruck.Extended    = thisExtended;
                                thisTruck.TruckNumber = thisExtended.TruckNumber;
                            }

                            /*if (thisTruck.assignedBeat.Loaded == false)  //
                             * {
                             *  SQL.SQLCode mySQL = new SQL.SQLCode();
                             *  TowTruck.AssignedBeat thisAssignedBeat = mySQL.GetAssignedBeat(thisTruck.Extended.FleetVehicleID);
                             *  if (thisAssignedBeat != null)
                             *  {
                             *      thisTruck.assignedBeat = thisAssignedBeat;
                             *  }
                             * }*/
                        }
                        catch { }
                    }
                    else
                    {
                        try
                        {
                            thisTruck = new TowTruck.TowTruck(_ipaddr);
                            DataClasses.GlobalData.AddTowTruck(thisTruck);
                            SQL.SQLCode mySQL = new SQL.SQLCode();
                            TowTruck.TowTruckExtended thisExtended = mySQL.GetExtendedData(thisTruck.Identifier);
                            thisTruck.Extended             = thisExtended;
                            thisTruck.TruckNumber          = thisExtended.TruckNumber;
                            thisTruck.Status.StatusStarted = DateTime.Now;
                        }
                        catch { }
                    }
                    if (type == "GPS")
                    {
                        thisTruck.UpdateGPS(thisGPS);
                        thisTruck.TowTruckGPSUpdate();
                    }
                    if (type == "State")
                    {
                        thisTruck.UpdateState(thisState);
                        thisTruck.TowTruckChanged();
                    }
                    if (type == "IPHistory")
                    {
                        if (thisTruck.State != null && string.IsNullOrEmpty(thisTruck.State.IPList))
                        {
                            thisTruck.State.IPList += history.IP;
                        }
                        else if (thisTruck.State != null && !string.IsNullOrEmpty(thisTruck.State.IPList))
                        {
                            thisTruck.State.IPList += "," + history.IP;
                        }
                    }
                    thisTruck.TTQueue.Enqueue(message);
                }
                catch (Exception ex)
                {
                    logger.LogEvent(DateTime.Now.ToString() + " Error in UDP Listening Thread" + Environment.NewLine + ex.ToString() +
                                    Environment.NewLine + "Original Message:" + Environment.NewLine + message, true);
                }
            }
        }
		private SqlGeography Sample_PolygonGeography()
		{
			SqlGeographyBuilder geoBuilder = new SqlGeographyBuilder();
			geoBuilder.SetSrid(4326);
			geoBuilder.BeginGeography(OpenGisGeographyType.Polygon);
			geoBuilder.BeginFigure(40, -10);
			geoBuilder.AddLine(40, 10);
			geoBuilder.AddLine(50, 0);
			geoBuilder.AddLine(40, -10);
			geoBuilder.EndFigure();
			geoBuilder.EndGeography();
			return geoBuilder.ConstructedGeography;
		}
        public async void CalculateAndShowOnMap(Map MyMap, string StartTbx, string EndTbx)
        {
            MyMap.Children.Clear();
            try
            {
                var r = await CalculateRoute(StartTbx, EndTbx);

                if (r != null &&
                    r.ResourceSets != null &&
                    r.ResourceSets.Length > 0 &&
                    r.ResourceSets[0].Resources != null &&
                    r.ResourceSets[0].Resources.Length > 0)
                {
                    Route route = r.ResourceSets[0].Resources[0] as Route;

                    double[][] routePath = route?.RoutePath.Line.Coordinates;

                    var locs = new LocationCollection();

                    //Create SqlGeography from route line points.
                    var geomBuilder = new SqlGeographyBuilder();
                    geomBuilder.SetSrid(4326);
                    geomBuilder.BeginGeography(OpenGisGeographyType.LineString);
                    geomBuilder.BeginFigure(routePath[0][0], routePath[0][1]);

                    foreach (var t in routePath)
                    {
                        locs.Add(new Microsoft.Maps.MapControl.WPF.Location(t[0], t[1]));
                        geomBuilder.AddLine(t[0], t[1]);
                    }

                    geomBuilder.EndFigure();
                    geomBuilder.EndGeography();

                    //Calculate distances in countries.
                    //var routeGeom = geomBuilder.ConstructedGeography;

                    var sb = new StringBuilder();
                    sb.AppendFormat("Total Driving Distance: {0} KM\r\n", route.TravelDistance);



                    //Display route on map
                    var routeLine = new MapPolyline()
                    {
                        Locations       = locs,
                        Stroke          = new SolidColorBrush(Colors.Blue),
                        StrokeThickness = 5
                    };

                    MyMap.Children.Add(routeLine);

                    MyMap.SetView(locs, new Thickness(30), 0);
                    MessageBox.Show(sb.ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("In Calculate  " + ex.Message);
            }
        }
        /// <summary>
        /// Create the SqlGeography line string from the points given
        /// </summary>
        /// <param name="linePoints">List of LatLong that represents the start and end of the line</param>
        /// <returns>SqlGeography line string</returns>
        private SqlGeography CreateLineFromPoints(List<LatLong> linePoints)
        {
            SqlGeographyBuilder geoLine = new SqlGeographyBuilder();

            //build the sql geography representation of the linestring
            geoLine.SetSrid(4326);
            geoLine.BeginGeography(OpenGisGeographyType.LineString);
            geoLine.BeginFigure(linePoints.First().Latitude, linePoints.First().Longitude);
            geoLine.AddLine(linePoints.Last().Latitude, linePoints.Last().Longitude);
            geoLine.EndFigure();
            geoLine.EndGeography();

            return geoLine.ConstructedGeography;
        }
		private static void Internal_FillGeographyBuilder(SqlGeographyBuilder gb, Polygon polygon)
		{
			gb.BeginGeography(OpenGisGeographyType.Polygon);
			bool isExteriorRing = true;
			foreach (var lineString in polygon.Coordinates)
			{
				List<GeographicPosition> listGeoCoords = lineString.Coordinates.Select(p => p as GeographicPosition).ToList();
				IEnumerable<GeographicPosition> orderedPositions = EnsureCorrectWinding(listGeoCoords, isExteriorRing); // exterior ring must be anti clockwise for SqlGeography
				isExteriorRing = false;
				bool beginFigureCalled = false;
				foreach (var pos in orderedPositions)
				{
					if (!beginFigureCalled)
					{
						gb.BeginFigure(pos.Latitude, pos.Longitude);
						beginFigureCalled = true;
					}
					else
					{
						gb.AddLine(pos.Latitude, pos.Longitude);
					}
				}
				gb.EndFigure();
			}
			gb.EndGeography();
		}
        static void Main(string[] args)
        {
            // EXAMPLE 1 : POINT

            // Create a new instance of the SqlGeographyBuilder
            SqlGeometryBuilder gb = new SqlGeometryBuilder();

            // Set the spatial reference identifier
            gb.SetSrid(27700);

            // Declare the type of geometry to be created
            gb.BeginGeometry(OpenGisGeometryType.Point);

            // Add the coordinates of the first (and only) point
            gb.BeginFigure(300500, 600200);

            // End the figure
            gb.EndFigure();

            // End the geometry
            gb.EndGeometry();

            // Retrieve the constructed geometry
            SqlGeometry Point = gb.ConstructedGeometry;

            // Print WKT of the geometry to the console window
            Console.WriteLine(Point.ToString());



            // EXAMPLE 2 : MULTIPOINT

            // Create a new instance of the SqlGeographyBuilder
            SqlGeographyBuilder gb2 = new SqlGeographyBuilder();

            // Set the spatial reference identifier
            gb2.SetSrid(4269);

            // Declare the type of collection to be created
            gb2.BeginGeography(OpenGisGeographyType.MultiPoint);

            // Create the first point in the collection
            gb2.BeginGeography(OpenGisGeographyType.Point);
            gb2.BeginFigure(40, -120);
            gb2.EndFigure();
            gb2.EndGeography();

            // Create the second point in the collection
            gb2.BeginGeography(OpenGisGeographyType.Point);
            gb2.BeginFigure(45, -100);
            gb2.EndFigure();
            gb2.EndGeography();

            // Create the second point in the collection
            gb2.BeginGeography(OpenGisGeographyType.Point);
            gb2.BeginFigure(42, -110);
            gb2.EndFigure();
            gb2.EndGeography();

            // End the geometry and retrieve the constructed instance
            gb2.EndGeography();
            SqlGeography MultiPoint = gb2.ConstructedGeography;

            Console.WriteLine(MultiPoint.ToString());



            // EXAMPLE 3: POLYGON WITH INTERIOR RING
            // Create a new instance of the SqlGeometryBuilder
            SqlGeometryBuilder gb3 = new SqlGeometryBuilder();

            // Set the spatial reference identifier
            gb3.SetSrid(0);

            // Declare the type of geometry to be created
            gb3.BeginGeometry(OpenGisGeometryType.Polygon);

            // Exterior ring
            gb3.BeginFigure(0, 0);
            gb3.AddLine(10, 0);
            gb3.AddLine(10, 20);
            gb3.AddLine(0, 20);
            gb3.AddLine(0, 0);
            gb3.EndFigure();

            // Interior ring
            gb3.BeginFigure(3, 3);
            gb3.AddLine(7, 3);
            gb3.AddLine(5, 17);
            gb3.AddLine(3, 3);
            gb3.EndFigure();

            // End the geometry and retrieve the constructed instance
            gb3.EndGeometry();
            SqlGeometry Polygon = gb3.ConstructedGeometry;



            // EXAMPLE 4: CURVED GEOMETRIES

            // Create a new instance of the SqlGeographyBuilder
            SqlGeometryBuilder gb4 = new SqlGeometryBuilder();

            // Set the spatial reference identifier
            gb4.SetSrid(0);

            // Declare the type of geometry to be created
            gb4.BeginGeometry(OpenGisGeometryType.CompoundCurve);

            // Begin the figure at a point
            gb4.BeginFigure(50, 0);

            // Draw a straight line edge
            gb4.AddLine(50, 10);

            // Draw a circular curved edge
            gb4.AddCircularArc(55, 5, 60, 0);

            // End the figure
            gb4.EndFigure();

            // End the geometry
            gb4.EndGeometry();

            SqlGeometry CompoundCurve = gb4.ConstructedGeometry;

            Console.WriteLine(CompoundCurve.ToString());



            // EXAMPLE 5: 3- AND 4- DIMENSIONAL COORDINATES

            // Create a new instance of the SqlGeographyBuilder
            SqlGeographyBuilder gb5 = new SqlGeographyBuilder();

            // Set the spatial reference identifier
            gb5.SetSrid(4326);

            // Declare the type of collection to be created
            gb5.BeginGeography(OpenGisGeographyType.Point);
            gb5.BeginFigure(52, 0.15, 140, null);
            gb5.EndFigure();
            gb5.EndGeography();

            SqlGeography PointZ = gb5.ConstructedGeography;

            Console.WriteLine(PointZ.ToString());

            Console.ReadLine();
        }
Exemple #36
0
        /// <summary>
        /// Builds the route geography.
        /// </summary>
        /// <param name="startIndex">The start index.</param>
        /// <param name="endIndex">The end index.</param>
        /// <param name="nearestStop">The nearest stop.</param>
        /// <param name="furtherStop">The further stop.</param>
        /// <param name="route">The route.</param>
        /// <returns>Geography of appropriate route</returns>
        private static Route BuildRouteGeography(int startIndex,int endIndex,Stop nearestStop, Stop furtherStop,Route route)
        {
            var geographyBuilder = new SqlGeographyBuilder();
                geographyBuilder.SetSrid(4326);
                geographyBuilder.BeginGeography(OpenGisGeographyType.LineString);
                SqlGeography beginGb = nearestStop.StopGeography;
                geographyBuilder.BeginFigure((double) beginGb.Lat, (double) beginGb.Long);
                for (var j = startIndex; j <= endIndex; j++)
                {

                    var point = route.RouteGeography.STPointN(j);
                    geographyBuilder.AddLine((double) point.Lat, (double) point.Long);

                }
                SqlGeography endFigure = furtherStop.StopGeography;
                geographyBuilder.AddLine((double) endFigure.Lat, (double) endFigure.Long);
                geographyBuilder.EndFigure();
                geographyBuilder.EndGeography();
                route.RouteGeography = geographyBuilder.ConstructedGeography;

            return route;
        }
Exemple #37
0
        public SqlGeography generateLineString(IList<RoutePointModel> points)
        {
            SqlGeographyBuilder builder = new SqlGeographyBuilder();
            builder.SetSrid(4326);
            builder.BeginGeography(OpenGisGeographyType.LineString);
            for (int i = 0; i < points.Count; i++)
            {
                if (i == 0)
                {
                    // First element, create figure
                    builder.BeginFigure(points.ElementAt(0).latitude, points.ElementAt(0).longitude);
                }
                else
                {
                    builder.AddLine(points.ElementAt(i).latitude, points.ElementAt(i).longitude);
                }
            }
            builder.EndFigure();
            builder.EndGeography();

            return builder.ConstructedGeography;
        }
        /// <summary>
        /// Create a SqlGeography instance for the point specified by the LatLong object
        /// </summary>
        /// <param name="point">LatLong object representing the point</param>
        /// <returns>SqlGeography point</returns>
        private SqlGeography CreatePoint(LatLong point)
        {
            SqlGeographyBuilder geoPoint = new SqlGeographyBuilder();

            //set the SRID and build the sql geography point for the centroid
            geoPoint.SetSrid(4326);
            geoPoint.BeginGeography(OpenGisGeographyType.Point);
            geoPoint.BeginFigure(point.Latitude, point.Longitude);
            geoPoint.EndFigure();
            geoPoint.EndGeography();

            return geoPoint.ConstructedGeography;
        }
        /// <summary>
        /// Create a SqlGeography builder for the polygon specified by the points
        /// </summary>
        /// <param name="points">Latitude longitude points for the polygon</param>
        /// <returns>SqlGeographyBuilder for the polygon</returns>
        private SqlGeography CreatePolygonFromPoints(List<LatLong> points)
        {
            SqlGeographyBuilder polygon = new SqlGeographyBuilder();
            polygon.SetSrid(4326);

            polygon.BeginGeography(OpenGisGeographyType.Polygon);

            //set the initial point to skip, and use that to begin the figure
            LatLong initialPoint = points.First();
            polygon.BeginFigure(initialPoint.Latitude, initialPoint.Longitude);

            foreach (var point in points)
            {
                if (point != initialPoint)
                {
                    //add each point to the geography poly
                    polygon.AddLine(point.Latitude, point.Longitude);
                }
            }

            //end the configuration of the geography
            polygon.EndFigure();
            polygon.EndGeography();

            return polygon.ConstructedGeography;
        }
		private static void Internal_FillGeographyBuilder(SqlGeographyBuilder gb, LineString lineString)
		{
			gb.BeginGeography(OpenGisGeographyType.LineString);
			bool beginFigureCalled = false;
			foreach (var ipos in lineString.Coordinates)
			{
				GeographicPosition pos = ipos as GeographicPosition;
				if (!beginFigureCalled)
				{
					gb.BeginFigure(pos.Latitude, pos.Longitude);
					beginFigureCalled = true;

				}
				else
				{
					gb.AddLine(pos.Latitude, pos.Longitude);
				}

			}
			gb.EndFigure();
			gb.EndGeography();
		}
Exemple #41
0
        public static List <InterchangeParsed> SortInterchanges(List <InterchangeParsed> ics)
        {
            var srid = 4326;

            if (ics == null || !ics.Any())
            {
                return(ics);
            }
            if (ics.Count() == 1)
            {
                ics[0].SortOrder = 1;
                return(ics);
            }
            List <Tuple <InterchangeParsed, SqlGeography, double> > allLines = new List <Tuple <InterchangeParsed, SqlGeography, double> >();

            foreach (var startingIC in ics)
            {
                List <SqlGeography> remainingICs = ics.OrderBy(s => s.IC_Kanji == startingIC.IC_Kanji ? 0 : 1).Select(s => SqlGeography.Point(s.Latitude, s.Longitude, srid)).ToList();
                SqlGeography        currentIC    = remainingICs[0];

                SqlGeographyBuilder Builder = new SqlGeographyBuilder();
                Builder.SetSrid(4326);
                Builder.BeginGeography(OpenGisGeographyType.LineString);
                Builder.BeginFigure((double)currentIC.Lat, (double)currentIC.Long);
                remainingICs.Remove(currentIC);
                // While there are still unvisited cities
                while (remainingICs.Count > 0)
                {
                    remainingICs.Sort(delegate(SqlGeography p1, SqlGeography p2)
                                      { return(p1.STDistance(currentIC).CompareTo(p2.STDistance(currentIC))); });

                    // Move to the closest destination
                    currentIC = remainingICs[0];

                    // Add this city to the tour route
                    Builder.AddLine((double)currentIC.Lat, (double)currentIC.Long);

                    // Update the list of remaining cities
                    remainingICs.Remove(currentIC);
                }

                // End the geometry
                Builder.EndFigure();
                Builder.EndGeography();

                // Return the constructed geometry
                var resultingLine = Builder.ConstructedGeography;
                allLines.Add(Tuple.Create(startingIC, resultingLine, resultingLine.STLength().Value));
            }
            var rankedRoute = allLines.OrderBy(s => s.Item3).Take(2).ToList();
            var bestRoute   = rankedRoute.OrderBy(s => SqlGeography.Point(s.Item1.Latitude, s.Item1.Longitude, 4326).STDistance(tokyoKouKyo)).First().Item2;
            //var bestRoute = (rankedRoute.First()).Item2;

            var sortingBoard = new List <Tuple <string, int> >();
            var numOfPoints  = bestRoute.STNumPoints();

            for (var i = 1; i <= numOfPoints; i++)
            {
                var point = bestRoute.STPointN(i);
                sortingBoard.Add(Tuple.Create(point.ToString(), i));
            }

            var result = ics.Aggregate(new List <InterchangeParsed>(), (acc, item) =>
            {
                var f          = sortingBoard.First(x => x.Item1 == SqlGeography.Point(item.Latitude, item.Longitude, srid).ToString());
                item.SortOrder = f.Item2;
                acc.Add(item);
                return(acc);
            }).ToList();

            return(result);
        }
        public static System.Collections.IEnumerable GeocodeTVF(
            SqlString addressLine,
            SqlString locality,
            SqlString adminDistrict,
            SqlString postalCode,
            SqlString countryRegion
            )
        {
            XmlDocument geocodeResponse = new XmlDocument();

            try
            {
                geocodeResponse = Geocode(
                    (string)countryRegion,
                    (string)adminDistrict,
                    (string)locality,
                    (string)postalCode,
                    (string)addressLine
                    );
            }
            // Failed to geocode the address
            catch (Exception ex)
            {
                SqlContext.Pipe.Send(ex.Message.ToString());
            }

            // Define the default XML namespace
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(geocodeResponse.NameTable);

            nsmgr.AddNamespace("ab", "http://schemas.microsoft.com/search/local/ws/rest/v1");

            // Create a set of all <Location>s in the response
            XmlNodeList Locations = geocodeResponse.GetElementsByTagName("Location");

            // Set up a list to hold results
            List <object[]> items = new List <object[]>();

            // Loop through each location in the response
            foreach (XmlNode locationNode in Locations)
            {
                // Create a new object for this result
                object[] item = new object[3];

                // Retrieve the name of this location
                string Name = locationNode["Name"].InnerText;
                item.SetValue(Name, 0);

                // Create a point for this location
                double       Latitude  = double.Parse(locationNode["Point"]["Latitude"].InnerText);
                double       Longitude = double.Parse(locationNode["Point"]["Longitude"].InnerText);
                SqlGeography Point     = SqlGeography.Point(Latitude, Longitude, 4326);
                item.SetValue(Point, 1);

                // Create a polygon for this location's bounding box
                if (locationNode.SelectSingleNode("ab:BoundingBox", nsmgr) != null)
                {
                    // Retrieve the latitude/longitude extents of the box
                    double BBSLatitude  = double.Parse(locationNode.SelectSingleNode("ab:BoundingBox/ab:SouthLatitude", nsmgr).InnerText);
                    double BBNLatitude  = double.Parse(locationNode.SelectSingleNode("ab:BoundingBox/ab:NorthLatitude", nsmgr).InnerText);
                    double BBWLongitude = double.Parse(locationNode.SelectSingleNode("ab:BoundingBox/ab:WestLongitude", nsmgr).InnerText);
                    double BBELongitude = double.Parse(locationNode.SelectSingleNode("ab:BoundingBox/ab:EastLongitude", nsmgr).InnerText);

                    // Build a geography polygon of the box
                    SqlGeographyBuilder gb = new SqlGeographyBuilder();
                    gb.SetSrid(4326);
                    gb.BeginGeography(OpenGisGeographyType.Polygon);
                    gb.BeginFigure(BBSLatitude, BBWLongitude);
                    gb.AddLine(BBSLatitude, BBELongitude);
                    gb.AddLine(BBNLatitude, BBELongitude);
                    gb.AddLine(BBNLatitude, BBWLongitude);
                    gb.AddLine(BBSLatitude, BBWLongitude);
                    gb.EndFigure();
                    gb.EndGeography();
                    SqlGeography Polygon = gb.ConstructedGeography;
                    item.SetValue(Polygon, 2);
                }
                // Add this result to the set of results
                items.Add(item);
            }
            return(items);
        }