Example #1
0
        /// <summary>
        /// Deletes the incorect routes.
        /// </summary>
        /// <param name="startMarker">The start marker.</param>
        /// <param name="endMarker">The end marker.</param>
        /// <param name="possibleRoutes">The possible routes.</param>
        /// <returns>Delete incorect routes in possible list of routes.</returns>
        public List<Route> DeleteIncorectRoutes(SqlGeography startMarker, SqlGeography endMarker, List<Route> possibleRoutes)
        {
            List<double> startWalkLength =
                possibleRoutes.Select(route => (double)startMarker.STDistance(route.StartStop.StopGeography)).ToList();
            List<double> endWalkLength =
                possibleRoutes.Select(route => (double)endMarker.STDistance(route.EndStop.StopGeography)).ToList();
            var times = new List<double>();
            for (int i = 0; i < possibleRoutes.Count; i++)
            {
                possibleRoutes[i].Length = this.GetLengthOfPartRoute(possibleRoutes[i]);
                double routeTime = this.GetTimeInMinutes(
                    possibleRoutes[i].Speed, possibleRoutes[i].Length, (int)possibleRoutes[i].WaitingTime.TotalMinutes);
                double summaryWalkLength = startWalkLength[i] + endWalkLength[i];
                double walkTime = this.GetTimeInMinutes(GeneralSettings.WalkingSpeed, summaryWalkLength);
                double summaryTime = routeTime + walkTime;
                times.Add(summaryTime);
            }

            for (int i = 0; i < possibleRoutes.Count; i++)
            {
                possibleRoutes[i].PossibleTime = times[i];
            }

            possibleRoutes.Add(this.GetWalkingRoute(startMarker, endMarker));
            possibleRoutes.Sort((a, b) => a.PossibleTime.CompareTo(b.PossibleTime));
            double minTime = possibleRoutes.First().Time.TotalMinutes;
            possibleRoutes.RemoveAll(
                route =>
                route.Time.TotalMinutes > minTime * GeneralSettings.MaxTimeConstraint);

            return possibleRoutes;
        }
Example #2
0
        public ActionResult GetCallBoxes()
        {
            List <UICallBox> returnList = new List <UICallBox>();

            try
            {
                var callBoxes = dc.vCallBoxes;

                foreach (var callBox in callBoxes)
                {
                    SqlGeography geo = new SqlGeography();
                    geo = SqlGeography.Parse(callBox.Position);

                    Double lat = Convert.ToDouble(geo.STPointN(1).Lat.ToString());
                    Double lon = Convert.ToDouble(geo.STPointN(1).Long.ToString());

                    returnList.Add(new UICallBox
                    {
                        CallBoxId           = callBox.CallBoxID,
                        FreewayId           = callBox.FreewayID,
                        Lat                 = lat,
                        Lon                 = lon,
                        LocationDescription = callBox.Location,
                        TelephoneNumber     = callBox.TelephoneNumber
                    });
                }
            }
            catch { }

            return(Json(returnList, JsonRequestBehavior.AllowGet));
        }
Example #3
0
        public Orchestrator.WebUI.ws.MappingServices.Point GetPoint(int pointID)
        {
            Orchestrator.Facade.IPoint  facPoint          = new Orchestrator.Facade.Point();
            Orchestrator.Entities.Point selectedPoint     = facPoint.GetPointForPointId(pointID);
            Orchestrator.WebUI.ws.MappingServices.Point p = new Orchestrator.WebUI.ws.MappingServices.Point();
            p.PointID     = selectedPoint.PointId;
            p.Description = selectedPoint.Description;
            p.Latitide    = (double)selectedPoint.Latitude;
            p.Longitude   = (double)selectedPoint.Longitude;


            p.GeofencePoints = new List <double[]>();

            string points = string.Empty;

            for (int i = 0; i < selectedPoint.Geofence.STNumPoints(); i++)
            {
                SqlGeography point  = selectedPoint.Geofence.STPointN(i + 1);
                double[]     latLon = new double[2] {
                    (double)point.Lat, (double)point.Long
                };
                p.GeofencePoints.Add(latLon);

                //points = point.Lat.ToString() + ',' + point.Long.ToString() + '|';
            }

            return(p);
        }
Example #4
0
 public GraphicsPath Build(SqlGeography geography)
 {
     var graphicsPath = new GraphicsPath();
     graphicsPath.FillMode = FillMode.Alternate;
     var geometryType = geography.STGeometryType();
     if (geometryType == "Polygon")
     {
         AddPolygon(geography, graphicsPath);
     }
     else if (geometryType == "MultiPolygon")
     {
         AddMultiPolygon(geography, graphicsPath);
     }
     else if (geometryType == "GeometryCollection")
     {
         for (int i = 0; i < geography.STNumGeometries(); i++)
         {
             var geom = geography.STGeometryN(i + 1);
             if (geom.STGeometryType().Value == "Polygon")
             {
                 AddPolygon(geom, graphicsPath);
             }
             else if (geom.STGeometryType().Value == "MultiPolygon")
             {
                 AddMultiPolygon(geom, graphicsPath);
             }
         }
     }
     else
     {
         throw new NotSupportedException(string.Format("The geometry type {0} is not supported.", geometryType));
     }
     return graphicsPath;
 }
        private void getSectorCoverage()
        {
            dc_tmap.ExecuteCommand(HandleTable.createCellTracing);
            Console.WriteLine(dc_oss.SITE.Count());

            foreach (var site in dc_oss.SITE)
            {

                if (site.latitude == null) continue;

                CellCoverage cc = new CellCoverage();

                #region 这里的算法复杂度高,仿真的过程比较复杂

                cc.pre_rxlev = -94;

                #endregion

                sgeog = cc.MergePoint(site);
                sgeom = SqlGeometry.STGeomFromWKB(sgeog.STAsBinary(), 4326).STConvexHull();

                pencolor = HandleTable.getRandomPenColor(false, false, false);

                CellTracing ct = new CellTracing();
                ct.cell = site.cell;
                ct.MI_STYLE = "Pen (1, 60," + pencolor.ToString() + ")";
                ct.SP_GEOMETRY = sgeom;
                sql = @" INSERT INTO [CELLTRACING]([cell],[MI_STYLE],[SP_GEOMETRY]) VALUES  ('"
                    + ct.cell + "','" + ct.MI_STYLE + "','" + ct.SP_GEOMETRY + "')";
                dc_tmap.ExecuteCommand(sql);

            }
        }
Example #6
0
        public void TestGeography([SqlServerDataContext(false)] string context)
        {
            using (var conn = GetDataContext(context))
            {
                conn.InlineParameters = true;

                conn.GetTable <AllTypes2>()
                .Select(t => new
                {
                    v1 = t.geographyDataType.STSrid,
                    v2 = t.geographyDataType.Lat,
                    v3 = t.geographyDataType.Long,
                    v4 = t.geographyDataType.Z,
                    v5 = t.geographyDataType.M,
                    //v6  = t.geographyDataType.HasZ,
                    //v7  = t.geographyDataType.HasM,
                    v8  = SqlGeography.GeomFromGml(t.geographyDataType.AsGml(), 4326),
                    v9  = t.geographyDataType.AsGml(),
                    v10 = t.geographyDataType.ToString(),
                    v11 = SqlGeography.Parse("LINESTRING(-122.360 47.656, -122.343 47.656)"),
                    v12 = SqlGeography.Point(1, 1, 4326),
                    v13 = SqlGeography.STGeomFromText(new SqlChars("LINESTRING(-122.360 47.656, -122.343 47.656)"), 4326),
                })
                .ToList();
            }
        }
Example #7
0
 public SqlGeography nLocating(string neighCell, double rxlev, double powerControl)
 {
     LocatingCellBuffer neigh = new LocatingCellBuffer(neighCell, rxlev, powerControl);
     neighcellgeog = neigh.getCellGeo();
     return neighcellgeog;
     //lgeo.Add(lc2.getCellGeo());
 }
        private string CombineZipCodes(List <ZipCode> zipCodes)
        {
            SqlGeography territory = null;

            for (int i = 0; i < zipCodes.Count; i++)
            {
                try {
                    var g = GetZipcodeBoundary(zipCodes[i]);

                    if (territory == null)
                    {
                        territory = g;
                    }
                    else
                    {
                        territory.STUnion(g);
                    }
                }
                catch (Exception ex) {
                    MessageBox.Show(ex.Message);
                }
            }

            if (territory != null && territory != SqlGeography.Null)
            {
                return(territory.ToString());
            }

            return(string.Empty);
        }
Example #9
0
        private void getSectorCoverage()
        {
            dc_tmap.ExecuteCommand(HandleTable.createCellTracing);
            Console.WriteLine(dc_oss.SITE.Count());

            foreach (var site in dc_oss.SITE)
            {
                if (site.latitude == null)
                {
                    continue;
                }

                CellCoverage cc = new CellCoverage();

                #region 这里的算法复杂度高,仿真的过程比较复杂

                cc.pre_rxlev = -94;

                #endregion

                sgeog = cc.MergePoint(site);
                sgeom = SqlGeometry.STGeomFromWKB(sgeog.STAsBinary(), 4326).STConvexHull();

                pencolor = HandleTable.getRandomPenColor(false, false, false);

                CellTracing ct = new CellTracing();
                ct.cell        = site.cell;
                ct.MI_STYLE    = "Pen (1, 60," + pencolor.ToString() + ")";
                ct.SP_GEOMETRY = sgeom;
                sql            = @" INSERT INTO [CELLTRACING]([cell],[MI_STYLE],[SP_GEOMETRY]) VALUES  ('"
                                 + ct.cell + "','" + ct.MI_STYLE + "','" + ct.SP_GEOMETRY + "')";
                dc_tmap.ExecuteCommand(sql);
            }
        }
Example #10
0
        public IGeometry Read(SqlGeography geometry)
        {
            NtsGeographySink builder = new NtsGeographySink();

            geometry.Populate(builder);
            return(builder.ConstructedGeometry);
        }
Example #11
0
        public static SqlGeography ToSqlGeography(SMGeometry smGeometry)
        {
            SqlGeographyBuilder builder = new SqlGeographyBuilder();

            builder.SetSrid(smGeometry.SRID);

            SharpMapGeometryToSqlGeography(builder, smGeometry);

            SqlGeography g = builder.ConstructedGeography;

            if (!g.STIsValid())
            {
                try
                {
                    g = g.Reduce(ReduceTolerance);
                    g = g.MakeValid();
                }
                catch (Exception ex)
                {
                    throw new SqlGeographyConverterException(ex, smGeometry);
                }
            }

            if (!g.STIsValid())
            {
                throw new SqlGeographyConverterException(smGeometry);
            }

            return(g);
        }
Example #12
0
 public void Test_Can_Insert_Spacial_Type()
 {
     Assert.IsTrue(dstore.InsertObject(new TestItemWithGeography()
     {
         Location = SqlGeography.Point(1, 1, 4326)
     }));
 }
Example #13
0
 /// <summary>
 /// Easier to use geometry enumerator than STGeometryN()
 /// </summary>
 /// <param name="geom"></param>
 /// <returns></returns>
 public static IEnumerable <SqlGeography> Geometries(this SqlGeography geom)
 {
     for (int i = 1; i <= geom.STNumGeometries().Value; i++)
     {
         yield return(geom.STGeometryN(i));
     }
 }
Example #14
0
 /// <summary>
 /// Easier to use points enumerator on SqlGeography
 /// </summary>
 /// <param name="geom"></param>
 /// <returns></returns>
 public static IEnumerable <SqlGeography> Points(this SqlGeography geom)
 {
     for (int i = 1; i <= geom.STNumPoints().Value; i++)
     {
         yield return(geom.STPointN(i));
     }
 }
Example #15
0
        /// <summary>
        /// XamlGeometryCollection
        ///     builds XAML string for a MapLayer containing multiple MapPolygons and/or MapPolylines
        /// </summary>
        /// <param name="geo">SqlGeography geo</param>
        /// <param name="table">string layer table</param>
        /// <param name="ID">string ID of current record</param>
        /// <returns>string of XAML</returns>
        private string XamlGeometryCollection(SqlGeography geo, string table, string ID)
        {
            StringBuilder sb = new StringBuilder();

            if (geo.STNumGeometries() > 0)
            {
                totalPoints += (int)geo.STNumPoints();
                sb.AppendLine("<m:MapLayer x:Name=\"" + ID + "\">");
                for (int j = 1; j <= geo.STNumGeometries(); j++)
                {
                    if (geo.STGeometryN(j).NumRings() > 0)
                    {
                        for (int k = 1; k <= geo.STGeometryN(j).NumRings(); k++)
                        {
                            if (geo.STGeometryN(j).RingN(k).STNumPoints() > 1)
                            {
                                sb.Append("<m:MapPolygon Locations=\"");
                                for (int m = 1; m <= geo.STGeometryN(j).RingN(k).STNumPoints(); m++)
                                {
                                    if (m > 1)
                                    {
                                        sb.Append(" ");
                                    }
                                    sb.Append(String.Format("{0:0.#####},{1:0.#####}", (double)geo.STGeometryN(j).RingN(k).STPointN(m).Lat, (double)geo.STGeometryN(j).RingN(k).STPointN(m).Long));
                                }
                                sb.AppendLine("\"/>");
                            }
                        }
                    }
                }
                sb.AppendLine("</m:MapLayer>");
            }
            return(sb.ToString());
        }
Example #16
0
 public void SetUp()
 {
     this.fakeDbContext = new FakeDbContext();
     this.startPoint = new MapPoint(35.048072199999979, 48.437927).ToSqlGeography();
     this.endPoint = new MapPoint(35.045630999999958, 48.46442).ToSqlGeography();
     this.route = new RouteSeach();
 }
Example #17
0
        /// <summary>
        /// XamlPolygon
        ///     builds XAML string for a MapPolygon
        /// </summary>
        /// <param name="geo">SqlGeography geo</param>
        /// <param name="table">string layer table</param>
        /// <param name="ID">string ID of current record</param>
        /// <returns>string of XAML</returns>
        private string XamlPolygon(SqlGeography geo, string table, string ID)
        {
            //<m:MapPolygon x:Name="test" Fill="Yellow" Locations="40,-105 40,-104 39,-104 39,-105 40,-105"/>
            StringBuilder sb = new StringBuilder();

            if (geo.NumRings() > 0)
            {
                totalPoints += (int)geo.STNumPoints();
                sb.AppendLine("<m:MapLayer x:Name=\"" + ID + "\">");
                for (int j = 1; j <= geo.NumRings(); j++)
                {
                    if (geo.RingN(j).STNumPoints() > 1)
                    {
                        sb.Append("<m:MapPolygon Locations=\"");
                        for (int k = 1; k <= geo.RingN(j).STNumPoints(); k++)
                        {
                            if (k > 1)
                            {
                                sb.Append(" ");
                            }
                            double t1   = (double)geo.RingN(j).STPointN(k).Lat;
                            double t2   = (double)geo.RingN(j).STPointN(k).Long;
                            string test = String.Format("{0:0.#####},{1:0.#####}", (double)geo.RingN(j).STPointN(k).Lat, (double)geo.RingN(j).STPointN(k).Long);
                            sb.Append(String.Format("{0:0.#####},{1:0.#####}", (double)geo.RingN(j).STPointN(k).Lat, (double)geo.RingN(j).STPointN(k).Long));
                        }
                        sb.AppendLine("\"/>");
                    }
                }
                sb.AppendLine("</m:MapLayer>");
            }
            return(sb.ToString());
        }
        public string outputRawPoint(SqlGeography shape)
        {
            StringBuilder coordsString = new StringBuilder("");

            coordsString.Append(string.Format("{0},{1},{2}", shape.Lat.ToString(), shape.Long.ToString(), 0));
            return(coordsString.ToString());
        }
        public void GeographyParametersArePassedCorrectly()
        {
            // single value query
            var point   = SqlGeography.Point(0, 0, 4326);
            var results = Connection().Query <SqlGeography>("MappingTestProcGeography", new { geo = point });

            Assert.That(results[0].STEquals(point).IsTrue);

            // class return value
            var list = Connection().Query <TestGeography>("MappingTestProcGeography", new { geo = point });

            Assert.That(list[0].Geo.STEquals(point).IsTrue);

            // dynamic parameter
            dynamic p = new FastExpando();

            p["Geo"] = point;
            results  = Connection().Query <SqlGeography>("MappingTestProcGeography", (object)p);
            Assert.That(results[0].STEquals(point).IsTrue);

            // dynamic results
            var dynamicList = Connection().Query("MappingTestProcGeography", new { geo = point });

            Assert.That(results[0].STEquals(point).IsTrue);
        }
 public void Read(BinaryReader r)
 {
     if (r.ReadBoolean())
     {
         Init();
     }
     else
     {
         SqlGeography g = new SqlGeography();
         g.Read(r);
         if (g.IsNull)
         {
             m_srid    = -1;
             m_error   = true;
             m_builder = null;
             m_sink    = null;
         }
         else
         {
             m_srid    = g.STSrid.Value;
             m_builder = new SqlGeographyBuilder();
             m_sink    = new StripSRID(m_builder);
             m_builder.SetSrid(m_srid);
             m_builder.BeginGeography(OpenGisGeographyType.GeometryCollection);
             g.Populate(new StripCollection(m_builder));
         }
     }
 }
Example #21
0
        private static GeoJsonMultiPoint SqlMultiPointToGeoJsonMultiPoint(this SqlGeography geometry, bool isLongitudeFirst)
        {
            //This check is required
            if (geometry.IsNullOrEmpty())
            {
                return new GeoJsonMultiPoint()
                       {
                           Type        = GeoJson.MultiPoint,
                           Coordinates = new double[0][],
                       }
            }
            ;

            var numberOfGeometries = geometry.STNumGeometries().Value;

            double[][] points = new double[numberOfGeometries][];

            for (int i = 1; i <= numberOfGeometries; i++)
            {
                points[i - 1] = GetGeoJsonObjectPoint(geometry.STGeometryN(i), isLongitudeFirst);
            }

            return(new GeoJsonMultiPoint()
            {
                Coordinates = points,
                Type = GeoJson.MultiPoint,
            });
        }
Example #22
0
        public static IGeoJsonGeometry AsGeoJson(this SqlGeography geography, bool isLongitudeFirst = true)
        {
            OpenGisGeographyType geometryType = geography.GetOpenGisType();

            switch (geometryType)
            {
            case OpenGisGeographyType.Point:
                return(geography.SqlPointToGeoJsonPoint(isLongitudeFirst));

            case OpenGisGeographyType.MultiPoint:
                return(SqlMultiPointToGeoJsonMultiPoint(geography, isLongitudeFirst));

            case OpenGisGeographyType.LineString:
                return(SqlLineStringToGeoJsonPolyline(geography, isLongitudeFirst));

            case OpenGisGeographyType.MultiLineString:
                return(SqlMultiLineStringToGeoJsonPolyline(geography, isLongitudeFirst));

            case OpenGisGeographyType.Polygon:
                return(SqlPolygonToGeoJsonPolygon(geography, isLongitudeFirst));

            case OpenGisGeographyType.MultiPolygon:
                return(SqlMultiPolygonToGeoJsonMultiPolygon(geography, isLongitudeFirst));

            case OpenGisGeographyType.GeometryCollection:
            case OpenGisGeographyType.CircularString:
            case OpenGisGeographyType.CompoundCurve:
            case OpenGisGeographyType.CurvePolygon:
            case OpenGisGeographyType.FullGlobe:
            default:
                //return null;
                throw new NotImplementedException();
            }
        }
Example #23
0
        /// <summary>
        /// Performs a complete trivial conversion from geography to geometry, simply taking each
        ///point (lat,long) -> (y, x).  The result is assigned the given SRID.
        /// </summary>
        /// <param name="toConvert"></param>
        /// <param name="targetSrid"></param>
        /// <returns></returns>
        public static SqlGeometry VacuousGeographyToGeometry(SqlGeography toConvert, int targetSrid)
        {
            var geomBuilder = new SqlGeometryBuilder();

            toConvert.Populate(new VacuousGeographyToGeometrySink(targetSrid, geomBuilder));
            return(geomBuilder.ConstructedGeometry);
        }
Example #24
0
        public static SqlGeography GetDefaultLocation()
        {
            string centerLat  = ConfigurationManager.AppSettings["mapCenterLat"] ?? "47.592557";
            string centerLong = ConfigurationManager.AppSettings["mapCenterLong"] ?? "-121.837041";

            return(SqlGeography.Point(double.Parse(centerLat), double.Parse(centerLong), SRID));
        }
Example #25
0
        /// <summary>
        /// This function is used for generating a new geography object where additional points are inserted
        /// along every line in such a way that the angle between two consecutive points does not
        /// exceed a prescribed angle. The points are generated between the unit vectors that correspond
        /// to the line's start and end along the great-circle arc on the unit sphere. This follows the
        /// definition of geodetic lines in SQL Server.
        /// </summary>
        /// <param name="geography">Input Sql geography</param>
        /// <param name="maxAngle">Max Angle</param>
        /// <returns></returns>
        public static SqlGeography DensifyGeography(SqlGeography geography, double maxAngle)
        {
            var geogBuilder = new SqlGeographyBuilder();

            geography.Populate(new DensifyGeographySink(geogBuilder, maxAngle));
            return(geogBuilder.ConstructedGeography);
        }
Example #26
0
        public void TestGeography([IncludeDataSources(TestProvName.AllSqlServer2008Plus)] string context)
        {
            using (var conn = GetDataContext(context))
            {
                conn.InlineParameters = true;

                conn.GetTable <AllTypes2>()
                .Select(t => new
                {
                    v1 = t.geographyDataType.STSrid,
                    v2 = t.geographyDataType.Lat,
                    v3 = t.geographyDataType.Long,
                    v4 = t.geographyDataType.Z,
                    v5 = t.geographyDataType.M,
                    //v6  = t.geographyDataType.HasZ,
                    //v7  = t.geographyDataType.HasM,
                    // missing API
#if !NETSTANDARD2_0
                    v8 = SqlGeography.GeomFromGml(t.geographyDataType.AsGml(), 4326),
                    v9 = t.geographyDataType.AsGml(),
#endif
                    v10 = t.geographyDataType.ToString(),
                    v11 = SqlGeography.Parse("LINESTRING(-122.360 47.656, -122.343 47.656)"),
                    v12 = SqlGeography.Point(1, 1, 4326),
                    v13 = SqlGeography.STGeomFromText(new SqlChars("LINESTRING(-122.360 47.656, -122.343 47.656)"), 4326),
                })
                .ToList();
            }
        }
Example #27
0
        public News PostNews(News news)
        {
            connection.Open();
            var cmd = connection.CreateCommand() as SqlCommand;

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "News_PostNews";

            cmd.Parameters.Add(new SqlParameter("@userid", news.EarthwatcherId));
            cmd.Parameters.Add(new SqlParameter("@NewsItem", news.NewsItem));
            cmd.Parameters.Add(new SqlParameter("@Published", DateTime.UtcNow.ToUniversalTime()));
            cmd.Parameters.Add(new SqlParameter("@shape", SqlGeography.STGeomFromText(new SqlChars(news.Wkt), 4326))
            {
                UdtTypeName = "Geography"
            });
            var idParameter = new SqlParameter("@ID", SqlDbType.Int)
            {
                Direction = ParameterDirection.Output
            };

            cmd.Parameters.Add(idParameter);
            cmd.ExecuteNonQuery();
            connection.Close();
            return(news);
        }
        /// <summary>
        /// Creates a SqlParameter for a SqlGeography.
        /// </summary>
        /// <param name="theValue">the value.</param>
        /// <param name="parameterName">The name of the parameter.</param>
        /// <param name="direction">The direction of the parameter.</param>
        /// <returns>The <see cref="SqlParameter"/></returns>
        public static SqlParameter CreateSqlParameter(this SqlGeography theValue, string parameterName, ParameterDirection direction = DefaultDirectionInputDirection)
        {
            SqlParameter parameter = Factory.CreateParameter(theValue, parameterName, direction);

            parameter.UdtTypeName = "Geography";
            return(parameter);
        }
Example #29
0
 private void insertLocatingGeo(string events, string pen, SqlGeography sgeog)
 {
     sgeom = SqlGeometry.STGeomFromWKB(sgeog.STAsBinary(), 4326);
     sql   = @" INSERT INTO [EventLocating]([events],[MI_STYLE],[SP_GEOMETRY]) VALUES  ('"
             + events + "','" + pen + "','" + sgeom + "')";
     dc.ExecuteCommand(sql);
 }
Example #30
0
        static void Main(string[] args)
        {
            // 1.使用Microsoft.SqlServer.Types计算WGS84坐标的两点距离
            var c = SqlGeography.Point(31.837964, 117.203123, 4326);      //公司的位置
            var d = SqlGeography.Point(31.822426, 117.221662, 4326);      // 合肥市政务中心,4236代表WGS84这种坐标参照系统。

            Console.WriteLine("公司和合肥市政务中心的距离是:" + c.STDistance(d) + "米"); //距离


            // 2.使用把坐标当做平面坐标计算两点距离
            double width  = 31.837964 - 31.822426;
            double height = 117.203123 - 117.221662;
            double result = (width * width) + (height * height);

            result = Math.Sqrt(result);                                //根号
            Console.WriteLine("想象成平面时公司和合肥市政务中心的距离是:" + result + "米"); //距离


            // 3.用haversine公式计算WGS84坐标的两点距离
            WGS84 wgs84       = new WGS84();
            var   coordinateA = new Coordinate()
            {
                Latitude = 31.837964, Longitude = 117.203123
            };
            var coordinateB = new Coordinate()
            {
                Latitude = 31.822426, Longitude = 117.221662
            };
            var xxx = wgs84.Distance(coordinateA, coordinateB);

            Console.WriteLine("用haversine公式时公司和合肥市政务中心的距离是:" + xxx * 1000 + "米"); //距离

            Console.ReadKey();
        }
        public SqlGeography getCellGeo()
        {
            site = dc_oss.SITE.Where(e => e.cell == this.sCell).FirstOrDefault();
            if (site == null) return SqlGeography.Point(0, 0, 4236);
            sitesgeog = SqlGeography.Point((double)site.latitude, (double)site.longitude, 4326);
            double.TryParse(site.ant_gain, out sAntGain);
            double.TryParse(site.height, out sHeight);
            sPathLoss = okumh.PathLoss2Distance((double)site.band, (double)sHeight, (double)mobileHight, (double)(sPowerN + sAntGain - sPowerControl - sRxlev));

            Console.WriteLine(sPathLoss * 1000);

            okumbuffersgeog = sitesgeog.STBuffer(sPathLoss * 1000);

            celltracing = dc_tmap.CellTracing.Where(e => e.cell == sCell).FirstOrDefault();

            //if (abc == null) return ngeo;

            celltracingsgeom = celltracing.SP_GEOMETRY;

            celltracingsgeog = SqlGeography.STGeomFromWKB(celltracingsgeom.STAsBinary(), 4326);

            Console.WriteLine(okumbuffersgeog.STArea());
            Console.WriteLine(celltracingsgeog.STArea());

            if (celltracingsgeog.STArea() > 0)
                return okumbuffersgeog.STIntersection(celltracingsgeog);   // 用圆和扇形相交
            else
                return okumbuffersgeog;    //返回圆
        }
Example #32
0
        //Not supportig Z and M Values
        //todo: 1399.08.19; this method must be checked
        private static GeoJsonPolygon SqlPolygonToGeoJsonPolygon(this SqlGeography geometry, bool isLongitudeFirst)
        {
            //This check is required
            if (geometry.IsNullOrEmpty())
            {
                return new GeoJsonPolygon()
                       {
                           Type        = GeoJson.Polygon,
                           Coordinates = new double[0][][],
                       }
            }
            ;

            //double[][][] rings = new double[1][][] { GetGeoJsonLineStringOrRing(geometry) };
            var numberOfRings = geometry.NumRings().Value;

            // 1400.01.30
            // در ژئوگرافی بر خلاف ژئومتری تعداد رینگ‌ها کل موارد رو شامل
            // می‌شه. در واقع حلقه داخلی و خارجی از هم جدا نشده پس این‌جا
            // نیازی نیست که به علاوه یک کنیم.
            //double[][][] result = new double[numberOfRings + 1][][];

            double[][][] result = new double[numberOfRings][][];

            for (int i = 1; i <= numberOfRings; i++)
            {
                result[i - 1] = GetGeoJsonLineStringOrRing(geometry.RingN(i), isLongitudeFirst);
            }

            return(new GeoJsonPolygon()
            {
                Coordinates = result,
                Type = GeoJson.Polygon,
            });
        }
Example #33
0
        //Not supportig Z and M Values
        private static GeoJsonMultiPolygon SqlMultiPolygonToGeoJsonMultiPolygon(this SqlGeography geometry, bool isLongitudeFirst)
        {
            //This check is required
            if (geometry.IsNullOrEmpty())
            {
                return new GeoJsonMultiPolygon()
                       {
                           Type        = GeoJson.MultiPolygon,
                           Coordinates = new double[0][][][],
                       }
            }
            ;

            int numberOfParts = geometry.STNumGeometries().Value;

            double[][][][] rings = new double[numberOfParts][][][];

            for (int i = 1; i <= numberOfParts; i++)
            {
                rings[i - 1] = geometry.STGeometryN(i).SqlPolygonToGeoJsonPolygon(isLongitudeFirst).Coordinates;
            }

            return(new GeoJsonMultiPolygon()
            {
                Coordinates = rings,
                Type = GeoJson.MultiPolygon,
            });
        }

        #endregion
    }
Example #34
0
        //Not supportig Z and M Values
        private static GeoJsonMultiLineString SqlMultiLineStringToGeoJsonPolyline(this SqlGeography geometry, bool isLongitudeFirst)
        {
            //This check is required
            if (geometry.IsNullOrEmpty())
            {
                return new GeoJsonMultiLineString()
                       {
                           Type        = GeoJson.MultiLineString,
                           Coordinates = new double[0][][],
                       }
            }
            ;

            int numberOfParts = geometry.STNumGeometries().Value;

            double[][][] result = new double[numberOfParts][][];

            for (int i = 1; i <= numberOfParts; i++)
            {
                result[i - 1] = GetGeoJsonLineStringOrRing(geometry.STGeometryN(i), isLongitudeFirst);
            }

            return(new GeoJsonMultiLineString()
            {
                Coordinates = result,
                Type = GeoJson.MultiLineString,
            });
        }
Example #35
0
        /// <summary>
        /// Creates the URL for request.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="start">The start.</param>
        /// <param name="end">The end.</param>
        /// <returns>
        /// Url of google api direction.
        /// </returns>
        public static string CreateUrlForDirectionRequest(string key, SqlGeography start, SqlGeography end)
        {
            var parameters = string.Format(
                "{0}&destination={1}&mode=walking&language=ru&sensor=false&amp;key={2}", CreatePointForRequest(start), CreatePointForRequest(end), key);

            return "http://maps.googleapis.com/maps/api/directions/json?origin=" + parameters;
        }
        private void AddItemsWithPossibleInterior(SqlGeography geog, string shapeName)
        {
            XNamespace ns = "http://www.opengis.net/gml";

            var coordinatesXml = XElement.Parse(geog.AsGml().Value);

            var totalXmlvalue = coordinatesXml.Value;

            var exteriorNode  = (from c in coordinatesXml.Elements(ns + "exterior") select c).Single();
            var interiorNodes = (from c in coordinatesXml.Elements(ns + "interior") select c).ToList();

            if (interiorNodes.Count == 0)
            {
                AddPolygon(shapeName, exteriorNode.Value);
            }
            else
            {
                var           coordinatesString   = exteriorNode.Value;
                List <string> interiorCoordinates = new List <string>();
                foreach (var interiorset in interiorNodes)
                {
                    interiorCoordinates.Add(interiorset.Value);
                }
                AddPolygonWithInteriorRings(shapeName, exteriorNode.Value, interiorCoordinates);
            }
        }
Example #37
0
        public void TestGeography([IncludeDataSources(TestProvName.AllSqlServer2008Plus)] string context)
        {
#if !NET472
            if (IsMsProvider(context))
            {
                Assert.Inconclusive("Spatial types test disabled for Microsoft.Data.SqlClient");
            }
#endif
            using (new SerializeAssemblyQualifiedName(true))
                using (var conn = GetDataContext(context))
                {
                    conn.InlineParameters = true;

                    conn.GetTable <AllTypes2>()
                    .Select(t => new
                    {
                        v1 = t.geographyDataType !.STSrid,
                        v2 = t.geographyDataType.Lat,
                        v3 = t.geographyDataType.Long,
                        v4 = t.geographyDataType.Z,
                        v5 = t.geographyDataType.M,
                        //v6  = t.geographyDataType.HasZ,
                        //v7  = t.geographyDataType.HasM,
                        // missing API
#if NET472
                        v8 = SqlGeography.GeomFromGml(t.geographyDataType.AsGml(), 4326),
                        v9 = t.geographyDataType.AsGml(),
#endif
                        v10 = t.geographyDataType.ToString(),
                        v11 = SqlGeography.Parse("LINESTRING(-122.360 47.656, -122.343 47.656)"),
                        v12 = SqlGeography.Point(1, 1, 4326),
                        v13 = SqlGeography.STGeomFromText(new SqlChars("LINESTRING(-122.360 47.656, -122.343 47.656)"), 4326),
                    })
Example #38
0
 private void AddPolygon(SqlGeography geography, GraphicsPath graphicsPath)
 {
     for (int r = 0; r < geography.NumRings(); r++)
     {
         var coords = GetCoordinates(geography, r);
         graphicsPath.AddPolygon(coords.ToArray());
     }
 }
Example #39
0
 private void AddMultiPolygon(SqlGeography multiPolygon, GraphicsPath graphicsPath)
 {
     for (int i = 0; i < multiPolygon.STNumGeometries(); i++)
     {
         var geom = multiPolygon.STGeometryN(i + 1);
         AddPolygon(geom, graphicsPath);
     }
 }
Example #40
0
        public bool IsNullOrEmpty(SqlGeography geog)
        {
            if (geog.IsNull)
                return true;

            if (geog.STIsEmpty() == SqlBoolean.Null)
                return true;
            else
                return geog.STIsEmpty().Value;
        }
Example #41
0
 public RouteModel(Route r)
 {
     this.routeID        = r.RouteID;
     this.userID         = r.User_ID;
     this.city           = r.City;
     this.name           = r.Name;
     this.heightmeters   = r.Heightmeters;
     this.description    = r.Description;
     this.routeLineString = RouteModel.getLineString(r.RouteID);
     this.tags           = TagModel.getRouteTags(this);
     this.ratings        = RatingModel.getRating(r.RouteID);
 }
 public IGeometry Read(byte[] bytes)
 {
     using (MemoryStream stream = new MemoryStream(bytes))
     {
         using (BinaryReader reader = new BinaryReader(stream))
         {
             SqlGeography sqlGeography = new SqlGeography();
             sqlGeography.Read(reader);
             return Read(sqlGeography);
         }
     }
 }
Example #43
0
        // 这个方法暂时不用,分别入库
        public void getLocating()
        {
            foreach (var geog in listgeog)
            {
                // Console.WriteLine(sgeo.STIntersects(geo));
                //if (sgeo.STIntersects(geo))
                //   sgeo = sgeo.STIntersection(geo);
                servicecellgeog = servicecellgeog.STUnion(geog);

            }
            //Console.WriteLine(sgeo.STArea());
            //sgeo = sgeo.EnvelopeCenter();
        }
        /// <summary>
        /// Returns geocode matches that fall within the specified region
        /// </summary>
        /// <param name="country"></param>
        /// <param name="locality"></param>
        /// <param name="regionResultMustBeIn"></param>
        /// <returns></returns>
        public List<GeocodeResult> Geocode(Country country, string locality, SqlGeography regionResultMustBeIn)
        {
            var filteredResults = new List<GeocodeResult>();

            //-- Get all geocode results then only include the ones that fall in the region in our filtered results
            foreach (var r in Geocode(country, locality))
            {
                var point = GeogExtensions.GetGeoPoint(double.Parse(r.Lat), double.Parse(r.Lon));

                if (point.STIntersects(regionResultMustBeIn)) { filteredResults.Add(r); }
            }

            return filteredResults;
        }
Example #45
0
        public lineLocating()
        {
            #region //这里用的是通用方法
            ExcuteSqlScript es = new ExcuteSqlScript();
            //es.insertSqltableIntoMapinfo(tableName);
            es.createLocatingTable(tableName);
            #endregion

            eventsLookup = dc.EventLocating.ToLookup(e => e.events);

            eventsKey = eventsLookup.Select(e => e.Key);

            foreach (var p in eventsKey)
            {
                foreach (var q in eventsLookup[p])
                {
                   // Console.WriteLine(".....{0}...{1}....{2}", q.events, 3 * Math.Pow(10, -8), q.SP_GEOMETRY.STArea());

                    //这里剔除天线高度为0的小区,避免定位干扰?
                    if (q.SP_GEOMETRY.STArea() >3 * Math.Pow(10, -8))
                    {
                        //Console.WriteLine("面接多少.....{0}....", q.SP_GEOMETRY.STArea());
                        mrPointsgeom = mrPointsgeom.STUnion(q.SP_GEOMETRY);
                        events = q.events;
                    }
                }

                redindex++;
                if (redindex > 255) redindex = 0;
                pencolor = redindex * 65535 + greenindex * 256 + blueindex;
                pen = "Pen (1, 2," + pencolor.ToString() + ")";

                mrPointsgeom = mrPointsgeom.STConvexHull().STCentroid().STPointN(1);

                if (!mrPointsgeom.STIsValid()) continue;

                tsgeog = SqlGeography.STGeomFromWKB(mrPointsgeom.STAsBinary(), 4326);

                if (tsgeog.IsNull) continue;

                tsgeog = SqlGeography.Point((double)tsgeog.Lat, (double)tsgeog.Long, 4326);
                tsgeog = tsgeog.STBuffer(1);

                mrLinesgeom = SqlGeometry.STGeomFromWKB(tsgeog.STAsBinary(), 4326);

                Console.WriteLine(mrLinesgeom.STArea());
                insertLocating2Sql(events, pen, mrLinesgeom);
            }
        }
		public static bool TryToGeography(this SqlGeometry geom, out SqlGeography outputGeography)
		{
			try
			{
				geom = geom.MakeValidIfInvalid();

				outputGeography = SqlGeography.STGeomFromText(new SqlChars(new SqlString(geom.ToString())), 4326);
				return true;
			}
			catch
			{
				outputGeography = null;
				return false;
			}
		}
Example #47
0
        /// <summary>
        /// Sets the bin from geography.
        /// </summary>
        /// <param name="value">The value of sqlgeography.</param>
        /// <param name="type">The type of retrieved geography.</param>
        /// <returns> The byte array retrieved from SqlGeography. </returns>
        public static byte[] SetBinFromGeography(SqlGeography value, string type)
        {
            byte[] returnBinary = new byte[1];

            switch (type)
            {
                case "stop":
                    returnBinary = value.STNumPoints() > 1
                    ? SqlGeography.STPolyFromText(value.STAsText(), Settings.GeneralSettings.GetSpatialReferenceSystem).STAsBinary().Buffer
                    : SqlGeography.STPointFromText(value.STAsText(), Settings.GeneralSettings.GetSpatialReferenceSystem).STAsBinary().Buffer;
                    break;
                case "route":
                    returnBinary = SqlGeography.STLineFromText(value.STAsText(), Settings.GeneralSettings.GetSpatialReferenceSystem).STAsBinary().Buffer;
                    break;
            }

            return returnBinary;
        }
Example #48
0
        public SqlGeography MergePoint(SITE site)
        {
            //SectorCovarage(6, (double)site.Height, (double)site.Tilt);
            //if (site.SP_GEOMETRY != null)
            //{
            //基站覆盖范围的计算?????
            //Enter Antenna Vertical (3dB) Beamwidth (? =6 °)
            //double.TryParse(site.band, out frequency);
            this.frequency = (double)site.band;
            this.power = (double)site.power;
            double.TryParse(site.ant_gain, out antGain);
            double.TryParse(site.height, out height);
            double.TryParse(site.tilt.ToString(), out this.tilt);

            //this.antGain = (double)site.ant_gain;
            pathLoss = this.power + this.antGain - this.pre_rxlev;

            SectorCoverage sc = new SectorCoverage(frequency, this.height, mobileHight, pathLoss);

            Console.WriteLine("{0}...{1}...", frequency, sc.DistanceOkumuraHata);
            //sc.SectorPoint = SqlGeometry.Point(0, 0, 4326);
            sc.Latitude = (double)site.latitude;
            sc.Longtitude = (double)site.longitude;
            //Console.WriteLine("{0}...", sc.SectorPoint.Long);
            sc.Direction = (double)site.dir;
            sc.DownTilt = this.tilt;
            //sc.SectorPoint = SqlGeography.STGeomFromWKB(site.SP_GEOMETRY.STAsBinary(), 4326);
            sc.HorizontalBeamwidth = (double)site.ant_bw;
            sc.VerticalBeamwidth = verticalBeamwidth;
            sc.getSectorRadius();
            sc.getSectorCoveragePoint();

            sgeog = SqlGeography.Point(sc.Latitude, sc.Longtitude, 4326);
            //SqlGeometry sgeo = new SqlGeometry();
            Console.WriteLine("{0}...{1}...", site.latitude, site.longitude);
            foreach (var m in sc.STSectorCoverageRegion)
            {
                //Console.WriteLine("{0}...{1}", m.Lat, m.Long);
                //SqlGeometry mgeo=SqlGeometry.STPointFromWKB(m.STAsBinary(),4326);
                sgeog = sgeog.STUnion(m);

            }
            return sgeog;
        }
Example #49
0
        public IEnumerable<SqlDataReader> Query(SqlGeography bounds, string layer)
        {
            if (bounds.STIsEmpty())
            {
                yield break;
            }
            var query = string.Format("Select Geom,STATE_NAME,POP2000 From {0} where [Geom].Filter(@Geography) = 1", layer);

            using (var connection = CreateAndOpenConnection())
            using (var command = new SqlCommand(query, connection))
            {
                command.Parameters.AddWithValue("Geography", bounds.STAsText());
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        yield return reader;
                    }
                }
            }
        }
Example #50
0
        /// <summary>
        /// Creates the URL for disntance matrix request.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="startPoint">The start point.</param>
        /// <param name="stops">The stops.</param>
        /// <returns>
        /// Url for request.
        /// </returns>
        public static string CreateUrlForDisntanceMatrixRequest(string key, SqlGeography startPoint, List<Stop> stops)
        {
            string start = CreatePointForRequest(startPoint);
            List<string> end = stops.Select(stop => CreatePointForRequest(stop.StopGeography)).ToList();
            List<SqlGeography> endpoint = stops.Select(stop => stop.StopGeography).ToList();
            var stringBuilder = new StringBuilder();
            stringBuilder.Append(string.Format("{0}&destinations=", start));

            foreach (SqlGeography point in endpoint)
            {
                string points = string.Empty;
                points = string.Format(point.STEquals(endpoint.Last()) ? "{0}" : "{0}|", CreatePointForRequest(point));
                stringBuilder.Append(points);
            }

            stringBuilder.Append("&mode=walking&language=ru&sensor=false");

            return "http://maps.googleapis.com/maps/api/distancematrix/json?origins=" + stringBuilder;
        }
Example #51
0
 /// <summary>
 /// Creates the point for request.
 /// </summary>
 /// <param name="point">The point.</param>
 /// <returns>String f</returns>
 private static string CreatePointForRequest(SqlGeography point)
 {
     return point.GetLatitude() + "," + point.GetLongitude();
 }
Example #52
0
        /// <summary>
        /// Creates the URL for disntance matrix request for routes.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="startPoint">The start point.</param>
        /// <param name="possibleStartStops">The possible start stops.</param>
        /// <returns>
        /// Distance for naerest stops.
        /// </returns>
        public static string CreateUrlForDisntanceMatrixRequestForRoutes(
            string key, SqlGeography startPoint, List<List<Stop>> possibleStartStops)
        {
            string startMarker = CreatePointForRequest(startPoint);
            var possibleStartPoints = possibleStartStops.Select(route => route.Select(r => r.StopGeography)).ToList();
            var stringBuilder = new StringBuilder();
            stringBuilder.Append(string.Format("{0}&destinations=", startMarker));
            var a = possibleStartStops.Last().Last();

            foreach (var route in possibleStartPoints)
            {
                foreach (var stop in route.Select(s => s))
                {
                    var points =
                        string.Format(
                        stop.STEquals(possibleStartPoints.Last().Last()) ? "{0}" : "{0}|",
                            CreatePointForRequest(stop));
                    stringBuilder.Append(points);
                }
            }

            stringBuilder.Append("&mode=walking&language=ru&sensor=false");
            string url = string.Format(
                "http://maps.googleapis.com/maps/api/distancematrix/json?origins=" + "{0}", stringBuilder);

            return url;
        }
Example #53
0
 /// <summary>
 /// XamlPolygon
 ///     builds XAML string for a MapPolygon
 /// </summary>
 /// <param name="geo">SqlGeography geo</param>
 /// <param name="table">string layer table</param>
 /// <param name="ID">string ID of current record</param>
 /// <returns>string of XAML</returns>
 private string XamlPolygon(SqlGeography geo, string table, string ID)
 {
     //<m:MapPolygon x:Name="test" Fill="Yellow" Locations="40,-105 40,-104 39,-104 39,-105 40,-105"/>
     StringBuilder sb = new StringBuilder();
     if (geo.NumRings() > 0)
     {
         totalPoints += (int)geo.STNumPoints();
         sb.AppendLine("<m:MapLayer x:Name=\"" + ID + "\">");
         for (int j = 1; j <= geo.NumRings(); j++)
         {
             if (geo.RingN(j).STNumPoints() > 1)
             {
                 sb.Append("<m:MapPolygon Fill=\"Red\" Locations=\"");
                 for (int k = 1; k <= geo.RingN(j).STNumPoints(); k++)
                 {
                     if (k > 1) sb.Append(" ");
                     double t1 = (double)geo.RingN(j).STPointN(k).Lat;
                     double t2 = (double)geo.RingN(j).STPointN(k).Long;
                     string test = String.Format("{0:0.#####},{1:0.#####}", (double)geo.RingN(j).STPointN(k).Lat, (double)geo.RingN(j).STPointN(k).Long);
                     sb.Append(String.Format("{0:0.#####},{1:0.#####}", (double)geo.RingN(j).STPointN(k).Lat, (double)geo.RingN(j).STPointN(k).Long));
                 }
                 sb.AppendLine("\"/>");
             }
         }
         sb.AppendLine("</m:MapLayer>");
     }
     return sb.ToString();
 }
Example #54
0
 /// <summary>
 /// XamlPoint
 ///     builds XAML string for a Pushpin point
 /// </summary>
 /// <param name="geo">SqlGeography geo</param>
 /// <param name="table">string layer table</param>
 /// <param name="ID">string ID of current record</param>
 /// <returns>string of XAML</returns>
 private string XamlPoint(SqlGeography geo, string table, string ID)
 {
     //<m:Pushpin PositionOrigin="Center" Content="Test" Location="39,-105"/>
     totalPoints++;
     StringBuilder sb = new StringBuilder();
     sb.Append("<m:Pushpin x:Name=\"" + ID + "\" PositionOrigin=\"BottomCenter\" Content=\"" + ID.Split('_')[1] + "\" Location=\"");
     sb.Append(String.Format("{0:0.#####},{1:0.#####}\"/>", (double)geo.Lat, (double)geo.Long));
     return sb.ToString();
 }
Example #55
0
 /// <summary>
 /// XamlMultiPolygon
 ///     builds XAML string for a MapLayer containing multiple MapPolygons
 /// </summary>
 /// <param name="geo">SqlGeography geo</param>
 /// <param name="table">string layer table</param>
 /// <param name="ID">string ID of current record</param>
 /// <returns>string of XAML</returns>
 private string XamlMultiPolygon(SqlGeography geo, string table, string ID)
 {
     //<m:MapPolygon x:Name="test" Fill="Yellow" Locations="40,-105 40,-104 39,-104 39,-105 40,-105"/>
     StringBuilder sb = new StringBuilder();
     if (geo.STNumGeometries() > 0)
     {
         totalPoints += (int)geo.STNumPoints();
         sb.AppendLine("<m:MapLayer x:Name=\"" + ID + "\">");
         for (int j = 1; j <= geo.STNumGeometries(); j++)
         {
             if (geo.STGeometryN(j).NumRings() > 0)
             {
                 for (int k = 1; k <= geo.STGeometryN(j).NumRings(); k++)
                 {
                     if (geo.STGeometryN(j).RingN(k).STNumPoints() > 1)
                     {
                         Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
                         sb.Append("<m:MapPolygon Fill=\"Red\" Locations=\"");
                         for (int m = 1; m <= geo.STGeometryN(j).RingN(k).STNumPoints(); m++)
                         {
                             if (m > 1) sb.Append(" ");
                             sb.Append(String.Format("{0:0.#####},{1:0.#####}", (double)geo.STGeometryN(j).RingN(k).STPointN(m).Lat, (double)geo.STGeometryN(j).RingN(k).STPointN(m).Long));
                         }
                         sb.AppendLine("\"/>");
                     }
                 }
             }
         }
         sb.AppendLine("</m:MapLayer>");
     }
     return sb.ToString();
 }
Example #56
0
 /// <summary>
 /// XamlLinestring
 ///     builds XAML string for a MapPolyline
 /// </summary>
 /// <param name="geo">SqlGeography geo</param>
 /// <param name="table">string layer table</param>
 /// <param name="ID">string ID of current record</param>
 /// <returns>string of XAML</returns>
 private string XamlLinestring(SqlGeography geo, string table, string ID)
 {
     //<m:MapPolyline  Stroke="Red" Locations="40,-105 39,-104 39,-105"/>
     StringBuilder sb = new StringBuilder();
     if (geo.STNumPoints() > 1)
     {
         totalPoints += (int)geo.STNumPoints();
         sb.Append("<m:MapPolyline x:Name=\"" + ID + "\" Locations=\"");
         for (int j = 1; j <= geo.STNumPoints(); j++)
         {
             if (j > 1) sb.Append(" ");
             sb.Append(String.Format("{0:0.#####},{1:0.#####}", (double)geo.STPointN(j).Lat, (double)geo.STPointN(j).Long));
         }
         sb.AppendLine("\"/>");
     }
     return sb.ToString();
 }
Example #57
0
 /// <summary>
 /// XamlGeometryCollection
 ///     builds XAML string for a MapLayer containing multiple MapPolygons and/or MapPolylines
 /// </summary>
 /// <param name="geo">SqlGeography geo</param>
 /// <param name="table">string layer table</param>
 /// <param name="ID">string ID of current record</param>
 /// <returns>string of XAML</returns>
 private string XamlGeometryCollection(SqlGeography geo, string table, string ID)
 {
     StringBuilder sb = new StringBuilder();
     if (geo.STNumGeometries() > 0)
     {
         totalPoints += (int)geo.STNumPoints();
         sb.AppendLine("<m:MapLayer x:Name=\"" + ID + "\">");
         for (int j = 1; j <= geo.STNumGeometries(); j++)
         {
             if (geo.STGeometryN(j).NumRings() > 0)
             {
                 for (int k = 1; k <= geo.STGeometryN(j).NumRings(); k++)
                 {
                     if (geo.STGeometryN(j).RingN(k).STNumPoints() > 1)
                     {
                         sb.Append("<m:MapPolygon Locations=\"");
                         for (int m = 1; m <= geo.STGeometryN(j).RingN(k).STNumPoints(); m++)
                         {
                             if (m > 1) sb.Append(" ");
                             sb.Append(String.Format("{0:0.#####},{1:0.#####}", (double)geo.STGeometryN(j).RingN(k).STPointN(m).Lat, (double)geo.STGeometryN(j).RingN(k).STPointN(m).Long));
                         }
                         sb.AppendLine("\"/>");
                     }
                 }
             }
         }
         sb.AppendLine("</m:MapLayer>");
     }
     return sb.ToString();
 }
Example #58
0
        /// <summary>
        /// GeoLocationText, Latitude, Longitude并不关联到数据库中的列.
        /// Geolocation (二进制)关联到TravelView表中的GeoLocation列.
        /// 如果GeoLocation的二进制值改变了, 相应那些值也会改变.
        /// 这可能在查询集合时发生.
        /// </summary>
partial         void OnGeoLocationChanging(global::System.Byte[] value)
        {
            if (value != null)
            {
                using (MemoryStream ms = new MemoryStream(value))
                {
                    using (BinaryReader reader = new BinaryReader(ms))
                    {
                        SqlGeography sqlGeography = new SqlGeography();
                        sqlGeography.Read(reader);
                        this.GeoLocationText = new string(sqlGeography.STAsText().Value);
                        this.Latitude = sqlGeography.Lat.Value;
                        this.Longitude = sqlGeography.Long.Value;
                    }
                }
            }
        }
Example #59
0
        /// <summary>
        /// RenderGeometryCollection
        ///     Render a GeometryCollection to Graphics
        /// </summary>
        /// <param name="geo">SqlGeography geo</param>
        /// <param name="table">string layer table</param>
        /// <param name="g">Graphics used to draw to</param>
        /// <param name="id">int record id</param>
        /// <param name="valueFill">Color the fill color style</param>
        private void RenderGeometryCollection(SqlGeography geo, string table, Graphics g, int id, Color valueFill)
        {
            int numGeom = (int)geo.STNumGeometries();
            if (geo.STNumGeometries() > 0)
            {
                for (int j = 1; j <= geo.STNumGeometries(); j++)
                {
                    if (geo.STGeometryN(j).NumRings() > 0)
                    {
                        for (int k = 1; k <= geo.STGeometryN(j).NumRings(); k++)
                        {
                            if (geo.STGeometryN(j).RingN(k).STNumPoints() > 1)
                            {
                                double lon1 = 0.0;
                                Point[] ptArray = new Point[(int)geo.STGeometryN(j).RingN(k).STNumPoints()];
                                for (int m = 1; m <= geo.STGeometryN(j).RingN(k).STNumPoints(); m++)
                                {
                                    double lat = (double)geo.STGeometryN(j).RingN(k).STPointN(m).Lat;
                                    double lon = (double)geo.STGeometryN(j).RingN(k).STPointN(m).Long;

                                    if (m > 1)
                                    {
                                        lon = HemisphereCorrection(lon, lon1, id);
                                    }

                                    LatLongToPixelXY(lat, lon, lvl, out pixelX, out pixelY);
                                    ptArray[m - 1] = new Point(pixelX - nwX, pixelY - nwY);
                                    lon1 = lon;
                                }
                                if (valueFill.Equals(Color.White)) valueFill = ColorFromInt(LayerStyle[table].fill);
                                GraphicsPath extRingRegion = new GraphicsPath();
                                extRingRegion.AddPolygon(ptArray);
                                Region region = new Region(extRingRegion);
                                g.FillRegion(new SolidBrush(valueFill), region);
                                Pen myPen = new Pen(ColorFromInt(LayerStyle[table].stroke));
                                myPen.Width = 1;
                                g.DrawPolygon(myPen, ptArray);
                            }
                        }
                    }
                }
            }
        }
Example #60
0
        /// <summary>
        /// RenderMultiLinestring
        ///     Render a MultiLinestring to Graphics
        /// </summary>
        /// <param name="geo">SqlGeography geo</param>
        /// <param name="table">string layer table</param>
        /// <param name="g">Graphics used to draw to</param>
        /// <param name="id">int record id</param>
        /// <param name="valueFill">Color the stroke color style</param>
        private void RenderMultiLinestring(SqlGeography geo, string table, Graphics g, int id, Color valueFill)
        {

            if (geo.STNumGeometries() > 0)
            {
                totalPoints += (int)geo.STNumPoints();

                for (int j = 1; j <= geo.STNumGeometries(); j++)
                {
                    if (geo.STGeometryN(j).NumRings() > 0)
                    {
                        for (int k = 1; k <= geo.STGeometryN(j).NumRings(); k++)
                        {
                            if (geo.STGeometryN(j).RingN(k).STNumPoints() > 1)
                            {
                                Point[] ptArray = new Point[(int)geo.STNumPoints()];
                                double lon1 = 0.0;
                                for (int m = 1; m <= geo.STGeometryN(j).RingN(k).STNumPoints(); m++)
                                {
                                    double lat = (double)geo.STGeometryN(j).RingN(k).STPointN(m).Lat;
                                    double lon = (double)geo.STGeometryN(j).RingN(k).STPointN(m).Long;
                                    if (m > 1)
                                    {
                                        lon = HemisphereCorrection(lon, lon1, id);
                                    }
                                    LatLongToPixelXY(lat, lon, lvl, out pixelX, out pixelY);
                                    ptArray[m - 1] = new Point(pixelX - nwX, pixelY - nwY);
                                    lon1 = lon;
                                }
                                if (valueFill.Equals(Color.White)) valueFill = ColorFromInt(LayerStyle[table].fill);
                                GraphicsPath linePath = new GraphicsPath();
                                linePath.AddLines(ptArray);
                                Pen myPen = new Pen(valueFill);
                                myPen.Width = 2;
                                g.DrawPath(myPen, linePath);
                            }
                        }
                    }
                }

            }

        }