static void Main(string[] args)
        {
            IoC.Register();
            _repo = IoC.Resolve<IRepository>();

            var geos = _repo.Find<City>().ToList();
            Console.WriteLine(string.Format("{0} total cities...", geos.Count()));

            int i =0;
            foreach (var geo in geos)
            {
                if (geo.Geography.GetType() == typeof(NetTopologySuite.Geometries.MultiPoint))
                {
                    Console.WriteLine(string.Format("{0} is a MultiPoint...", geo.Name));
                    var point = new NetTopologySuite.Geometries.Point(geo.Geography.Coordinates.First());
                    geo.Geography = point;
                    _repo.Save<City>(geo);
                    _repo.SubmitChanges();
                    Console.WriteLine(string.Format("{0} updated to Point...", geo.Name));
                    i++;
                }
            }
            Console.WriteLine(string.Format("{0} total Cities updated...", i));
            Console.Read();
        }
Exemple #2
0
        public Hop GetByCoordinates(double Y, double X)
        {
            NetTopologySuite.Geometries.Point tmpPoint = new NetTopologySuite.Geometries.Point(X, Y)
            {
                SRID = 4326
            };
            Hop hop = context.Hops.OfType <Truck>().FirstOrDefault(c => c.RegionGeoJson.Contains(tmpPoint));

            if (hop == null)
            {
                hop = context.Hops.OfType <Transferwarehouse>().FirstOrDefault(c => c.RegionGeoJson.Contains(tmpPoint));
                if (hop == null)
                {
                    hop = context.Hops.OfType <Warehouse>().FirstOrDefault(c => c.RegionGeoJson.Contains(tmpPoint));
                }
            }
            if (hop == null)
            {
                tmpPoint = new NetTopologySuite.Geometries.Point(Y, X);
                hop      = context.Hops.OfType <Truck>().FirstOrDefault(c => c.RegionGeoJson.Contains(tmpPoint));
                if (hop == null)
                {
                    hop = context.Hops.OfType <Transferwarehouse>().FirstOrDefault(c => c.RegionGeoJson.Contains(tmpPoint));
                }
            }
            return(hop);
        }
 private AddRoadNode(RecordNumber recordNumber, RoadNodeId temporaryId, RoadNodeType type, NetTopologySuite.Geometries.Point geometry)
 {
     RecordNumber = recordNumber;
     TemporaryId  = temporaryId;
     Type         = type;
     Geometry     = geometry;
 }
Exemple #4
0
        /// <summary>
        /// Converts a WGS-84 Lat/Long coordinate to the tile XY of the tile containing
        /// that point at the given levelOfDetail
        /// </summary>
        /// <param name="coord">WGS-84 Lat/Long</param>
        /// <param name="levelOfDetail">Level of detail, from 1 (lowest detail)
        /// to 23 (highest detail).  </param>
        /// <returns>Tile XY Point</returns>
        public static MWPoint LatLongToTileXY(Coordinate coord, int levelOfDetail)
        {
            MWPoint pixelXY = LatLongToPixelXY(coord.Y, coord.X, levelOfDetail);
            MWPoint tileXY  = PixelXYToTileXY(pixelXY);

            return(tileXY);
        }
Exemple #5
0
        private Tuple <IFeature, Coordinate> ComputSnapEdegeModeFeature(IFeatureLayer layer, Extent extent, Coordinate mouseCoord)
        {
            Tuple <IFeature, Coordinate> tuple = null;

            if (SnapMode == SnapMode.None || layer == null || mouseCoord == null)
            {
                return(tuple);
            }
            var point0 = new NetTopologySuite.Geometries.Point(mouseCoord);

            if ((SnapMode & SnapMode.Edege) > 0 && (layer.DataSet.FeatureType == FeatureType.Line || layer.DataSet.FeatureType == FeatureType.Polygon))
            {
                var    features    = layer.DataSet.Select(extent);
                double minDistance = extent.Width / 2;
                foreach (var feature in features)
                {
                    IGeometry geo      = feature.Geometry;
                    var       distance = geo.Distance(point0);
                    if (distance < minDistance)
                    {
                        var coord = NetTopologySuite.Operation.Distance.DistanceOp.NearestPoints(geo, point0)?.FirstOrDefault();
                        if (coord != null)
                        {
                            tuple = new Tuple <IFeature, Coordinate>(feature, coord);
                            break;
                        }
                    }
                }
            }
            return(tuple);
        }
Exemple #6
0
        /// <summary>
        /// Converts a WGS-84 Lat/Long coordinate to the tile XY of the tile containing that point at the given levelOfDetail.
        /// </summary>
        /// <param name="coord">WGS-84 Lat/Long</param>
        /// <param name="levelOfDetail">Level of detail, from 1 (lowest detail) to 23 (highest detail).</param>
        /// <returns>Tile XY Point</returns>
        public static NtsPoint LatLongToTileXy(Coordinate coord, int levelOfDetail)
        {
            NtsPoint pixelXy = LatLongToPixelXy(coord.Y, coord.X, levelOfDetail);
            NtsPoint tileXy  = PixelXyToTileXy(pixelXy);

            return(tileXy);
        }
 public FullyDisconnectedRoadNodeTests()
 {
     _fixture = new Fixture();
     _fixture.CustomizePoint();
     _id       = _fixture.Create <RoadNodeId>();
     _geometry = _fixture.Create <NetTopologySuite.Geometries.Point>();
     _sut      = new RoadNode(_id, _geometry);
 }
Exemple #8
0
        public void Constructor_WithCoordinate()
        {
            var coordinate = new NetTopologySuite.Geometries.Point(new NetTopologySuite.Geometries.Coordinate(1, 2));
            var location   = new Location("KY11 9YU", coordinate);

            location.Postcode.Should().Be("ky119yu");
            location.Coordinate.Should().Be(coordinate);
        }
 public static Point FromGeometryPoint(NetTopologySuite.Geometries.Point point)
 {
     if (point == null)
     {
         throw new ArgumentNullException(nameof(point));
     }
     return(new Point(point.X, point.Y));
 }
 public AddRoadNode WithGeometry(NetTopologySuite.Geometries.Point geometry)
 {
     if (geometry == null)
     {
         throw new ArgumentNullException(nameof(geometry));
     }
     return(new AddRoadNode(RecordNumber, TemporaryId, Type, geometry));
 }
 public ConnectedRoadNodeTests()
 {
     _fixture = new Fixture();
     _fixture.CustomizePoint();
     _id       = _fixture.Create <RoadNodeId>();
     _geometry = _fixture.Create <NetTopologySuite.Geometries.Point>();
     _link1    = _fixture.Create <RoadSegmentId>();
     _link2    = _fixture.Create <RoadSegmentId>();
     _sut      = new RoadNode(_id, _geometry).ConnectWith(_link1).ConnectWith(_link2);
 }
Exemple #12
0
        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("Girilen veriler veri tabanına yazılacak, onaylıyor musunuz?", "My App", MessageBoxButton.YesNoCancel);

            switch (result)
            {
            case MessageBoxResult.Yes:

                double lat = Convert.ToDouble(txtBoxPlaceLatitude.Text);
                double lng = Convert.ToDouble(txtBoxPlaceLongitude.Text);

                NetTopologySuite.Geometries.Point point = new NetTopologySuite.Geometries.Point(lat, lng)
                {
                    SRID = 4326
                };
                Places place = new Places()
                {
                    Type     = txtBoxPlaceType.Text,
                    Name     = txtBoxPlaceName.Text,
                    Tel      = txtPhone.Text,
                    Address  = txtAddress.Text,
                    Location = point,
                };

                using (mycityDbContext context = new mycityDbContext())
                {
                    context.Add(place);
                    context.SaveChanges();
                }


                MessageBox.Show("Veriler başarıyla aktarıldı...");
                txtBoxPlaceType.Text      = "";
                txtBoxPlaceName.Text      = "";
                txtBoxPlaceLatitude.Text  = "";
                txtBoxPlaceLongitude.Text = "";
                myMap.Mode = new AerialMode(true);

                break;

            case MessageBoxResult.No:
                // MessageBox.Show("Oh well, too bad!", "My App");
                break;

            case MessageBoxResult.Cancel:
                txtBoxPlaceType.Text      = "";
                txtBoxPlaceName.Text      = "";
                txtBoxPlaceLatitude.Text  = "";
                txtBoxPlaceLongitude.Text = "";
                myMap.Mode = new AerialMode(true);
                break;
            }
        }
Exemple #13
0
        public Hop GetByCoordinates(IPoint point)
        {
            NetTopologySuite.Geometries.Point tmpPoint = new NetTopologySuite.Geometries.Point(point.X, point.Y);
            Hop hop = context.Hops.OfType <Truck>().FirstOrDefault(c => c.RegionGeoJson.Contains(tmpPoint));

            if (hop == null)
            {
                hop = context.Hops.OfType <Transferwarehouse>().FirstOrDefault(c => c.RegionGeoJson.Contains(tmpPoint));
            }

            return(hop);
        }
Exemple #14
0
        //https://www.npgsql.org/doc/copy.html

        public void AddPhysicalContacts(IEnumerable <PhysicalContact> contacts)
        {
            Check.CallerLog <CommonCitizenRepository>(Logger, LoggerExecutionPositions.Entrance, $"contacts: {contacts}");
            Check.NotNull(contacts, nameof(contacts));

            if (contacts.Count() < 1)
            {
                Check.CallerLog <CommonCitizenRepository>(Logger, LoggerExecutionPositions.Exit, $"contacts does not have any item.");
                return;
            }

            using (var connection_ = new NpgsqlConnection(RepoOptions.PgsqlPassword))
            {
                try
                {
                    using (var writer = connection_.BeginBinaryImport("COPY physical_contacts (user_id, date, time, contact_type, coordinate) FROM STDIN (FORMAT BINARY)"))
                    {
                        foreach (var contact in contacts)
                        {
                            Check.CallerLog <CommonCitizenRepository>(Logger, LoggerExecutionPositions.Body, $"Writting contact: {contact} to bulk copy");
                            var userId      = Convert.ToInt32(contact.UserId);
                            var time        = contact.DateTime.TimeOfDay;
                            var contactType = contact.Contacts.ToString();
                            var point       = new NetTopologySuite.Geometries.Point(new NetTopologySuite.Geometries.Coordinate(contact.Latitude, contact.Longitude));
                            writer.StartRow();
                            writer.Write(userId, NpgsqlDbType.Integer);
                            writer.Write(contact.DateTime, NpgsqlDbType.Date);
                            writer.Write(time, NpgsqlDbType.Time);
                            writer.Write(contactType, NpgsqlDbType.Varchar);
                            writer.Write(point, NpgsqlDbType.Point);
                        }

                        writer.Complete();
                    }
                }
                catch (Exception exception)
                {
                    Check.CallerLog <CommonCitizenRepository>(Logger, LoggerExecutionPositions.Body, $"Exception {exception}", LogLevel.Warning);

                    if (exception is BackendException)
                    {
                        throw exception;
                    }

                    throw new BackendException(Convert.ToInt32(HttpStatusCode.InternalServerError), exception.Message);
                }
            }

            Check.CallerLog <CommonCitizenRepository>(Logger, LoggerExecutionPositions.Exit);
        }
        public static async Task <Challenge> GetNewChallenge(this Group group, DbSet <Challenge> chals, double longitude, double latitude, bool isNewUser = false)
        {
            //Group Extension method to generate new random challenge (not in prev challenge), add current challenge if one exists to prev challenge list of group + all members

            var coord = new NetTopologySuite.Geometries.Point(longitude, latitude);

            coord.SRID = chals.FirstOrDefault()?.LongLat.SRID ?? 4326;

            var query = chals.OrderBy(c => c.LongLat.Distance(coord));

            if (!isNewUser)
            {
                query = (IOrderedQueryable <Challenge>)query.Where(chal => !group.PrevChallenges.Contains(chal));
            }

            return(await query.FirstOrDefaultAsync());
        }
        public static Messages.RoadNodeGeometry Translate(NetTopologySuite.Geometries.Point geometry)
        {
            if (geometry == null)
            {
                throw new ArgumentNullException(nameof(geometry));
            }

            return(new Messages.RoadNodeGeometry
            {
                SpatialReferenceSystemIdentifier = geometry.SRID,
                Point = new Messages.Point
                {
                    X = geometry.X,
                    Y = geometry.Y
                }
            });
        }
        public void ConvertAPointUsingNetTopologySuiteTransformGeometry()
        {
            //SETUP
            var factory = NetTopologySuite.Geometries.GeometryFactory.Default;
            var pointNatGrid = new NetTopologySuite.Geometries.Point(532248.29992272425, 181560.30052819476);

            //ATTEMPT
            var transform = new DotSpatialMathTransform(
                _britishNationalGridOsgb36, _wgs84);
            var result = GeometryTransform.TransformGeometry(
                factory, pointNatGrid, transform);

            //VERIFY            
            Assert.AreEqual("Point", result.GeometryType);
            Assert.AreEqual(1, result.Coordinates.Length);
            Assert.AreEqual(-0.095399303,result.Coordinate.X,  0.001);
            Assert.AreEqual(51.517489, result.Coordinates[0].Y, 0.001);
        }
        public void ConvertAPointUsingNetTopologySuiteTransformGeometry()
        {
            //SETUP
            var factory      = NetTopologySuite.Geometries.GeometryFactory.Default;
            var pointNatGrid = new NetTopologySuite.Geometries.Point(532248.29992272425, 181560.30052819476);

            //ATTEMPT
            var transform = new DotSpatialMathTransform(
                _britishNationalGridOsgb36, _wgs84);
            var result = GeometryTransform.TransformGeometry(
                factory, pointNatGrid, transform);

            //VERIFY
            Assert.AreEqual("Point", result.GeometryType);
            Assert.AreEqual(1, result.Coordinates.Length);
            Assert.AreEqual(-0.095399303, result.Coordinate.X, 0.001);
            Assert.AreEqual(51.517489, result.Coordinates[0].Y, 0.001);
        }
        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            if (this.txtSavePath.Text == "")
            {
                MessageBox.Show("Please select a save path");
                return;
            }
            if (this.cboX.Text == "" || this.cboY.Text == "")
            {
                MessageBox.Show("Please select x y field");
                return;
            }
            string      xField  = this.cboX.Text;
            string      yField  = this.cboY.Text;
            IFeatureSet pFeaSet = new FeatureSet(FeatureType.Point);

            //使用当前视图的空间参考
            pFeaSet.Projection = MainWindow.m_DotMap.Projection;
            pFeaSet.DataTable  = m_DataTable.Clone();
            pFeaSet.Name       = this.txtName.Text;
            for (int i = 0; i < m_DataTable.Rows.Count; i++)
            {
                string xValue = m_DataTable.Rows[i][xField].ToString();
                string yValue = m_DataTable.Rows[i][yField].ToString();
                double x, y;
                //尝试转换成double类型
                if (double.TryParse(xValue, out x) && double.TryParse(yValue, out y))
                {
                    Coordinate coor    = new Coordinate(x, y);
                    IPoint     point   = new NetTopologySuite.Geometries.Point(coor);
                    IFeature   feature = pFeaSet.AddFeature(point);
                    feature.DataRow = m_DataTable.Rows[i];
                }
                else
                {
                    MessageBox.Show("第" + (i + 1) + "行中X或Y坐标不是数值");
                    return;
                }
            }
            pFeaSet.SaveAs(this.txtSavePath.Text, true);
            ResultFeaSet      = pFeaSet;
            this.DialogResult = true;
        }
Exemple #20
0
        public async Task <IEnumerable <NearbyLocationModel> > GetLocations(NetTopologySuite.Geometries.Point targetPoint, int maxDistance, int maxResults)
        {
            IQueryable <Location> locations =
                _dbContext.Locations.AsNoTracking();

            var distance = (double)maxDistance;
            IQueryable <Location> nearbyLocations =
                locations
                .Where(x => x.Coordinates.IsWithinDistance(targetPoint, distance))
                .OrderBy(x => x.Coordinates.Distance(targetPoint));

            nearbyLocations =
                nearbyLocations.Take(maxResults);

            var nearbyLocationModels =
                ProjectToNearbyLocationModel(nearbyLocations, targetPoint);

            return(await nearbyLocationModels.ToListAsync());
        }
Exemple #21
0
            public void TestMatrix()
            {
                var p = new NetTopologySuite.Geometries.Point(10, 10);
                var b = p.AsBinary();

                System.Drawing.Drawing2D.Matrix mat = new System.Drawing.Drawing2D.Matrix();
                mat.Rotate(30);
                mat.Translate(-20, 20);
                System.Drawing.PointF[] pts = new System.Drawing.PointF[] { new System.Drawing.PointF(50, 50) };

                mat.TransformPoints(pts);
                System.Diagnostics.Debug.WriteLine(string.Format("POINT ({0} {1})", pts[0].X, pts[0].Y));
                System.Drawing.PointF           ptt  = pts[0];
                System.Drawing.PointF[]         ptts = new System.Drawing.PointF[] { new System.Drawing.PointF(ptt.X, ptt.Y) };
                System.Drawing.Drawing2D.Matrix inv  = mat.Clone();
                inv.Invert();
                inv.TransformPoints(ptts);
                NUnit.Framework.Assert.LessOrEqual(System.Math.Abs(ptts[0].X - 50f), 0.01);
                NUnit.Framework.Assert.LessOrEqual(System.Math.Abs(ptts[0].Y - 50f), 0.01);
            }
Exemple #22
0
        /// <summary>
        /// Reads WKT from the <paramref name="str"/> via NTS's <see cref="WKTReader"/>.
        /// </summary>
        /// <param name="str"></param>
        /// <param name="reader"><c>new WKTReader(ctx.GeometryFactory)</c></param>
        /// <returns>Non-Null</returns>
        protected virtual IShape ParseIfSupported(string str, WKTReader reader)
        {
            try
            {
                IGeometry geom = reader.Read(str);

                //Normalizes & verifies coordinates
                CheckCoordinates(geom);

                if (geom is NetTopologySuite.Geometries.Point)
                {
                    NetTopologySuite.Geometries.Point ptGeom = (NetTopologySuite.Geometries.Point)geom;
                    if (m_ctx.UseNtsPoint)
                    {
                        return(new NtsPoint(ptGeom, m_ctx));
                    }
                    else
                    {
                        return(m_ctx.MakePoint(ptGeom.X, ptGeom.Y));
                    }
                }
                else if (geom.IsRectangle)
                {
                    return(base.MakeRectFromPoly(geom));
                }
                else
                {
                    return(base.MakeShapeFromGeometry(geom));
                }
            }
            catch (InvalidShapeException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw new InvalidShapeException("error reading WKT: " + e.ToString(), e);
            }
        }
Exemple #23
0
        public async Task <IEnumerable <Route> > GetRoutesAsync(RoutesQuery query)
        {
            var currentLocation = new Point(query.CurrentLongitude, query.CurrentLatitude)
            {
                SRID = 4326
            };
            var routes = _context.Routes
                         .Where(r => r.Properties.PavedPercentage >= query.SurfacePavedPercentageFrom &&
                                r.Properties.PavedPercentage <= query.SurfacePavedPercentageTo)
                         .Where(r => r.Properties.Distance >= query.RouteLengthFrom && r.Properties.Distance <= query.RouteLengthTo)
                         .Where(r => r.Checkpoints.First(cp => cp.Number == 0).Coordinates.IsWithinDistance(currentLocation, query.SearchRadiusInMeters));

            if (query.SurfaceLevel > 0)
            {
                routes = routes.Where(r => r.Properties.TerrainLevel == (TerrainLevel)query.SurfaceLevel);
            }

            return(await routes
                   .Include(r => r.Checkpoints)
                   .Include(r => r.Properties)
                   .Include(r => r.Ranking).ThenInclude(rr => rr.User)
                   .ToListAsync());
        }
Exemple #24
0
        private static IPoint ReadPoint(JsonTextReader jreader)
        {
            if (jreader == null)
            {
                throw new ArgumentNullException("reader", "A valid JSON reader object is required.");
            }

            IPoint point = null;

            if (jreader.TokenClass == JsonTokenClass.Array)
            {
                jreader.ReadToken(JsonTokenClass.Array);
                double x = Convert.ToDouble(jreader.ReadNumber());
                double y = Convert.ToDouble(jreader.ReadNumber());
                double z = double.NaN;
                if (jreader.TokenClass == JsonTokenClass.Number)
                {
                    z = Convert.ToDouble(jreader.ReadNumber());
                }
                jreader.ReadToken(JsonTokenClass.EndArray);
                point = new NetTopologySuite.Geometries.Point(x, y, z);
            }
            return(point);
        }
Exemple #25
0
 internal Point(NTSPoint point)
 {
     X = point.X;
     Y = point.Y;
 }
        public void TestMatrix()
        {
            var p = new NetTopologySuite.Geometries.Point(10, 10);
            var b = p.AsBinary();
            
            System.Drawing.Drawing2D.Matrix mat = new System.Drawing.Drawing2D.Matrix();
            mat.Rotate(30);
            mat.Translate(-20, 20);
            System.Drawing.PointF[] pts = new System.Drawing.PointF[] { new System.Drawing.PointF(50, 50) };

            mat.TransformPoints(pts);
            System.Diagnostics.Debug.WriteLine(string.Format("POINT ({0} {1})", pts[0].X, pts[0].Y));
            System.Drawing.PointF ptt = pts[0];
            System.Drawing.PointF[] ptts = new System.Drawing.PointF[] { new System.Drawing.PointF(ptt.X, ptt.Y) };
            System.Drawing.Drawing2D.Matrix inv = mat.Clone();
            inv.Invert();
            inv.TransformPoints(ptts);
            NUnit.Framework.Assert.LessOrEqual(System.Math.Abs(ptts[0].X - 50f), 0.01);
            NUnit.Framework.Assert.LessOrEqual(System.Math.Abs(ptts[0].Y - 50f), 0.01);
        
        }
Exemple #27
0
 /// <summary>
 /// Converts pixel XY coordinates into tile XY coordinates of the tile containing the specified pixel.
 /// </summary>
 /// <param name="point">Pixel X,Y point.</param>
 /// <returns>Tile XY coordinate</returns>
 public static NtsPoint PixelXyToTileXy(NtsPoint point)
 {
     return(PixelXyToTileXy((int)point.X, (int)point.Y));
 }
Exemple #28
0
        public void ReturnPOIResultsInBoundingBox()
        {
            var api = new OCM.API.Common.POIManager();

            // mongodb cache results
            var searchParams = new Common.APIRequestParams
            {
                AllowMirrorDB    = true,
                AllowDataStoreDB = false,
                IsVerboseOutput  = false,
                IsCompactOutput  = true,
                MaxResults       = 100000,
                BoundingBox      = new List <Common.LatLon> {
                    new Common.LatLon {
                        Latitude = 51.45580747856863, Longitude = -0.27510331130017107
                    },
                    new Common.LatLon {
                        Latitude = 51.53701250046424, Longitude = 0.009162470112983101
                    }
                }
            };

            var stopwatch    = Stopwatch.StartNew();
            var cacheResults = api.GetPOIList(searchParams);

            stopwatch.Stop();

            var msAllowance = 2;

            Assert.True(stopwatch.ElapsedMilliseconds < cacheResults.Count() * msAllowance, $"Results must return in less than {cacheResults.Count() * msAllowance} ms (numResults * {msAllowance}ms) actual: {stopwatch.ElapsedMilliseconds}");
            Assert.True(cacheResults.Count() > 0);
            Assert.True(cacheResults.Count() <= searchParams.MaxResults, $"Result count must be less than {searchParams.MaxResults})");

            var poi = cacheResults.FirstOrDefault();

            Assert.NotNull(poi);

            // ensure all points are within the bounding box
            var bbox = Core.Util.PolylineEncoder.ConvertPointsToBoundingBox(searchParams.BoundingBox);


            foreach (var p in cacheResults)
            {
                var testPoint = new NetTopologySuite.Geometries.Point(p.AddressInfo.Longitude, p.AddressInfo.Latitude);
                testPoint.SRID = Common.GeoManager.StandardSRID;
                if (!bbox.Intersects(testPoint))
                {
                    if (bbox.IsWithinDistance(testPoint, 100))
                    {
                        // point is outside box but not far away
                    }
                    else
                    {
                        Assert.True(bbox.Intersects(testPoint), "Location must intersect the given bounding box.");
                    }
                }
            }

            if (_enableSQLSpatialTests)
            {
                // database results
                searchParams = new Common.APIRequestParams
                {
                    AllowMirrorDB    = false,
                    AllowDataStoreDB = true,
                    IsVerboseOutput  = false,
                    IsCompactOutput  = true,
                    MaxResults       = 100000,
                    BoundingBox      = new List <Common.LatLon> {
                        new Common.LatLon {
                            Latitude = 51.45580747856863, Longitude = -0.27510331130017107
                        },
                        new Common.LatLon {
                            Latitude = 51.53701250046424, Longitude = 0.009162470112983101
                        }
                    }
                };

                var dbresults = api.GetPOIList(searchParams);
                Assert.True(dbresults.Count() > 0);
                Assert.True(dbresults.Count() <= searchParams.MaxResults, $"Result count must be less than {searchParams.MaxResults})");

                poi = dbresults.FirstOrDefault();
                Assert.NotNull(poi);

                // ensure all points are within the bounding box
                bbox = Core.Util.PolylineEncoder.ConvertPointsToBoundingBox(searchParams.BoundingBox);

                foreach (var p in cacheResults)
                {
                    Assert.True(bbox.Intersects(new NetTopologySuite.Geometries.Point(p.AddressInfo.Longitude, p.AddressInfo.Latitude)));
                }


                Assert.True(cacheResults.Count() == dbresults.Count(), "Cached results and db results should be the same");
            }
        }
        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            if (this.cboLayer.Text == "")
            {
                MessageBox.Show("Please select a polyline layer");
                return;
            }
            IFeatureLayer layer  = m_Layers[this.cboLayer.SelectedIndex];
            IFeatureSet   feaset = (layer as FeatureLayer).FeatureSet;
            ProgressBox   p      = new ProgressBox(0, 100, "Suspension point check progress");

            p.ShowPregress();
            p.SetProgressValue(0);
            p.SetProgressDescription("Checking suspension point...");
            Dictionary <int, List <GeoAPI.Geometries.IPoint> > AllPoints = new Dictionary <int, List <GeoAPI.Geometries.IPoint> >();//线图层所有端点

            for (int i = 0; i < feaset.Features.Count; i++)
            {
                IFeature pFea = feaset.Features[i];
                if (pFea.Geometry.GeometryType == "LineString")
                {
                    GeoAPI.Geometries.Coordinate coord1  = pFea.Geometry.Coordinates[0];
                    GeoAPI.Geometries.IPoint     pPoint1 = new NetTopologySuite.Geometries.Point(coord1);
                    int count = pFea.Geometry.Coordinates.Count() - 1;
                    GeoAPI.Geometries.Coordinate coord2  = pFea.Geometry.Coordinates[count];
                    GeoAPI.Geometries.IPoint     pPoint2 = new NetTopologySuite.Geometries.Point(coord2);
                    AllPoints.Add(pFea.Fid, new List <GeoAPI.Geometries.IPoint>()
                    {
                        pPoint1, pPoint2
                    });
                }
                else//多线
                {
                    for (int j = 0; j < pFea.Geometry.NumGeometries; j++)
                    {
                        var geometry = pFea.Geometry.GetGeometryN(j);
                        GeoAPI.Geometries.Coordinate coord1  = geometry.Coordinates[0];
                        GeoAPI.Geometries.IPoint     pPoint1 = new NetTopologySuite.Geometries.Point(coord1);
                        int count = geometry.Coordinates.Count() - 1;
                        GeoAPI.Geometries.Coordinate coord2  = geometry.Coordinates[count];
                        GeoAPI.Geometries.IPoint     pPoint2 = new NetTopologySuite.Geometries.Point(coord2);
                        if (AllPoints.ContainsKey(pFea.Fid))
                        {
                            if (!AllPoints[pFea.Fid].Contains(pPoint1))
                            {
                                AllPoints[pFea.Fid].Add(pPoint1);
                            }
                            if (!AllPoints[pFea.Fid].Contains(pPoint2))
                            {
                                AllPoints[pFea.Fid].Add(pPoint2);
                            }
                        }
                        else
                        {
                            AllPoints.Add(pFea.Fid, new List <GeoAPI.Geometries.IPoint>()
                            {
                                pPoint1, pPoint2
                            });
                        }
                    }
                }
            }
            List <GeoAPI.Geometries.IPoint> resultPoint = new List <GeoAPI.Geometries.IPoint>();
            double pi     = Math.Round((double)(1.0 * 100 / feaset.Features.Count), 2);
            int    number = 1;

            foreach (var value in AllPoints)
            {
                p.SetProgressValue(number * pi);
                p.SetProgressDescription2(string.Format("{0} feature(s) is(are) checked, the remaining {1} feature(s) is(are) being queried", number, feaset.Features.Count - number));
                number++;
                foreach (var point in value.Value)
                {
                    bool IsSuspension = true;
                    foreach (var fea in feaset.Features)
                    {
                        if (fea.Fid == value.Key)
                        {
                            continue;
                        }
                        //一旦相交,必不是悬点
                        if (fea.Geometry.Intersects(point))
                        {
                            IsSuspension = false;
                            break;
                        }
                    }
                    if (IsSuspension && !resultPoint.Contains(point))
                    {
                        resultPoint.Add(point);
                    }
                }
            }
            AllPoints.Clear();
            p.CloseProgress();
            if (resultPoint.Count == 0)
            {
                MessageBox.Show(string.Format("{0} has no suspension point.", layer.LegendText));
            }
            else
            {
                IFeatureSet pSet   = new FeatureSet(FeatureType.Point);
                string[]    Fields = new string[3] {
                    "ID", "X", "Y"
                };
                foreach (string field in Fields)
                {
                    pSet.DataTable.Columns.Add(field);
                }
                int s = 0;
                foreach (var point in resultPoint)
                {
                    IFeature pFea = pSet.AddFeature(point);
                    pFea.DataRow[0] = s;
                    pFea.DataRow[1] = point.X;
                    pFea.DataRow[2] = point.Y;
                    s++;
                }
                pSet.Projection = MainWindow.m_DotMap.Projection;
                pSet.Name       = m_Layers[this.cboLayer.SelectedIndex].LegendText + "_suspenion points";
                var             feaLayer = MainWindow.m_DotMap.Layers.Add(pSet);
                PointSymbolizer symbol   = new PointSymbolizer(System.Drawing.Color.Red, DotSpatial.Symbology.PointShape.Ellipse, 5);
                feaLayer.Symbolizer = symbol;
                MessageBox.Show(string.Format("{0} has {1} suspension point.", layer.LegendText, resultPoint.Count.ToString()));
            }
            this.Close();
        }
Exemple #30
0
        public static (Feature pand, double distance) GetNearestPand(List <Feature> panden, NetTopologySuite.Geometries.Point loc1, NetTopologySuite.Geometries.LineString line, double MinimumDistance)
        {
            Feature nearestPand     = null;
            double  distanceNearest = Double.MaxValue;

            foreach (var pand in panden)
            {
                var geom       = pand.Geometry;
                var pandGeom   = GeometryConverter.GetGeoApiGeometry(geom);
                var intersects = pandGeom.Intersects(line);

                if (intersects)
                {
                    var dist = loc1.Distance(pandGeom);

                    if (dist < distanceNearest && dist > MinimumDistance / 111000)
                    {
                        distanceNearest = dist;
                        nearestPand     = pand;
                    }
                }
            }
            return(nearestPand, distanceNearest);
        }
Exemple #31
0
        private static object ConvertParameterValue(string paramName, SqlDbType sqlType, string value, string udtType)
        {
            // if the expected value is a string return as is
            if (SqlStringTypes.Contains(sqlType))
            {
                return(value);
            }

            if (string.IsNullOrWhiteSpace(value))
            {
                return(DBNull.Value);
            }

            switch (sqlType)
            {
            case SqlDbType.UniqueIdentifier:
                return(new Guid((string)value));

            case SqlDbType.DateTime:
                var expectedFormat = "yyyy-MM-dd'T'HH:mm:ss.FFFK";

                // DateTimeOffset expect the Date & Time to be in LOCAL time
                if (DateTimeOffset.TryParseExact(value, expectedFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var dto))
                {
                    return(dto.DateTime);
                }
                else
                {
                    throw new JsdalServerParameterValueException(paramName, $"Invalid DateTime value of {value ?? "(null)"}. Expected format is: {expectedFormat} e.g. {DateTime.Now.ToString(expectedFormat)}");
                }

            case SqlDbType.Bit:
                return(ConvertToSqlBit(value));

            case SqlDbType.VarBinary:
                return(ConvertToSqlVarbinary(value));

            case SqlDbType.Timestamp:
                return(BitConverter.GetBytes(long.Parse(value)).Reverse().ToArray() /*have to reverse to match the endianness*/);

            case SqlDbType.Time:
                return(value);

            case SqlDbType.Float:
                return(double.Parse(value));

            case SqlDbType.Decimal:
                return(decimal.Parse(value));

            case SqlDbType.Udt:
            {
                // TODO: Refractor into separate function
                // TODO: Add support for geometry
                // TODO: Throw if unable to convert? (e.g. see DateTime section)
                if (udtType.Equals("geography", StringComparison.OrdinalIgnoreCase))
                {
                    // for geography we only support { lat: .., lng: ...} for now - in future we might support WKT strings
                    var obj  = JsonConvert.DeserializeObject <dynamic>(value);
                    int srid = 4326;

                    if (obj["srid"] != null)
                    {
                        srid = (int)obj.srid;
                    }

                    // Use NetTopologySuite until MS adds support for Geography/Geometry in dotcore sql client
                    // See https://github.com/dotnet/SqlClient/issues/30


                    var geometry = new NetTopologySuite.Geometries.Point((double)obj.lng, (double)obj.lat)
                    {
                        SRID = srid
                    };

                    var geometryWriter = new NetTopologySuite.IO.SqlServerBytesWriter {
                        IsGeography = true
                    };
                    var bytes = geometryWriter.Write(geometry);

                    return(new System.Data.SqlTypes.SqlBytes(bytes));

                    //return SqlGeography.Point((double)obj.lat, (double)obj.lng, srid);
                }

                return(value);
            }

            default:
            {
                var typeName = RoutineParameterV2.GetCSharpDataTypeFromSqlDbType(sqlType.ToString().ToLower());
                var type     = Type.GetType(typeName);

                return(Convert.ChangeType(value, type));
            }
            }
        }
Exemple #32
0
        private void map1_MouseDown(object sender, MouseEventArgs e)
        {
            Stopwatch timer = new Stopwatch();

            timer.Start();

            Coordinate mousept = map1.PixelToProj(e.Location);

            NetTopologySuite.Geometries.Point xp = new NetTopologySuite.Geometries.Point(mousept.X, mousept.Y);
            Console.WriteLine(xp.ToString());

            MapPolygonLayer polylayer = (MapPolygonLayer)map1.Layers[0];
            MapPolygonLayer gridlayer = (MapPolygonLayer)map1.Layers[1];

            //Iterate through NLDAS grid and determine if it intersects a polygon at selected region
            gridlayer.UnSelectAll();
            double interArea = 0.0;

            foreach (GeoAPI.Geometries.IGeometry s in overlap)
            {
                if (s.Intersects(xp))
                {
                    squareArea = s.Area;
                    foreach (GeoAPI.Geometries.IGeometry p in polys)
                    {
                        if (p.Intersects(s))
                        {
                            GeoAPI.Geometries.IGeometry intersection = p.Intersection(s);
                            interArea += intersection.Area;
                            break;
                        }
                    }
                    break;
                }
            }

            /**
             * /// slightly slower implementation, but provides visual selection.
             * int iShape = 0;
             * foreach (GeoAPI.Geometries.IGeometry s in squares)
             * {
             *  if (s.Intersects(xp))
             *  {
             *      squareArea = s.Area;
             *      gridlayer.Select(iShape);
             *      foreach (GeoAPI.Geometries.IGeometry p in polys)
             *      {
             *          if (p.Intersects(s))
             *          {
             *              GeoAPI.Geometries.IGeometry intersection = p.Intersection(s);
             *              interArea += intersection.Area;
             *              break;
             *          }
             *      }
             *      break;
             *  }
             *  iShape++;
             * }**/

            double percent = (interArea / squareArea) * 100;

            label2.Text = "Area of square: " + squareArea.ToString() + "\r\nArea of polygon in selected square: " + interArea.ToString() + "\r\nPortion of polygon covers " + percent.ToString() + "% of this square.";

            timer.Stop();
            TimeSpan ts          = timer.Elapsed;
            string   elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);

            Console.WriteLine("RunTime " + elapsedTime);

            switch (shapeType)
            {
            case "Point":
                if (e.Button == MouseButtons.Left)
                {
                    if ((pointmouseClick))
                    {
                        //This method is used to convert the screen cordinate to map coordinate
                        //e.location is the mouse click point on the map control
                        Coordinate coord = map1.PixelToProj(e.Location);

                        //Create a new point
                        //Input parameter is clicked point coordinate
                        DotSpatial.Topology.Point point = new DotSpatial.Topology.Point(coord);

                        //Add the point into the Point Feature
                        //assigning the point feature to IFeature because via it only we can set the attributes.
                        IFeature currentFeature = pointF.AddFeature(point);

                        //increase the point id
                        pointID = pointID + 1;

                        //set the ID attribute
                        //currentFeature.DataRow["PointID"] = pointID;

                        //refresh the map
                        map1.ResetBuffer();
                    }
                }

                else
                {
                    //mouse right click
                    map1.Cursor     = Cursors.Default;
                    pointmouseClick = false;
                }
                break;

            case "line":
                if (e.Button == MouseButtons.Left)
                {
                    //left click - fill array of coordinates
                    //coordinate of clicked point
                    Coordinate coord = map1.PixelToProj(e.Location);
                    if (linemouseClick)
                    {
                        //first time left click - create empty line feature
                        if (firstClick)
                        {
                            //Create a new List called lineArray.
                            //This list will store the Coordinates
                            //We are going to store the mouse click coordinates into this array.
                            List <Coordinate> lineArray = new List <Coordinate>();

                            //Create an instance for LineString class.
                            //We need to pass collection of list coordinates
                            LineString lineGeometry = new LineString(lineArray);

                            //Add the linegeometry to line feature
                            IFeature lineFeature = lineF.AddFeature(lineGeometry);

                            //add first coordinate to the line feature
                            lineFeature.Coordinates.Add(coord);
                            //set the line feature attribute
                            lineID = lineID + 1;
                            lineFeature.DataRow["LineID"] = lineID;
                            firstClick = false;
                        }
                        else
                        {
                            //second or more clicks - add points to the existing feature
                            IFeature existingFeature = lineF.Features[lineF.Features.Count - 1];
                            existingFeature.Coordinates.Add(coord);

                            //refresh the map if line has 2 or more points
                            if (existingFeature.Coordinates.Count >= 2)
                            {
                                lineF.InitializeVertices();
                                map1.ResetBuffer();
                            }
                        }
                    }
                }
                else
                {
                    //right click - reset first mouse click
                    firstClick = true;
                    map1.ResetBuffer();
                }
                break;

            case "polygon":

                if (e.Button == MouseButtons.Left)
                {
                    //left click - fill array of coordinates
                    Coordinate coord = map1.PixelToProj(e.Location);

                    if (polygonmouseClick)
                    {
                        //first time left click - create empty line feature
                        if (firstClick)
                        {
                            //Create a new List called polygonArray.

                            //this list will store the Coordinates
                            //We are going to store the mouse click coordinates into this array.

                            List <Coordinate> polygonArray = new List <Coordinate>();

                            //Create an instance for LinearRing class.
                            //We pass the polygon List to the constructor of this class
                            LinearRing polygonGeometry = new LinearRing(polygonArray);

                            //Add the polygonGeometry instance to PolygonFeature
                            IFeature polygonFeature = polygonF.AddFeature(polygonGeometry);

                            //add first coordinate to the polygon feature
                            polygonFeature.Coordinates.Add(coord);

                            //set the polygon feature attribute
                            polygonID = polygonID + 1;
                            polygonFeature.DataRow["PolygonID"] = polygonID;
                            firstClick = false;
                        }
                        else
                        {
                            //second or more clicks - add points to the existing feature
                            IFeature existingFeature = (IFeature)polygonF.Features[polygonF.Features.Count - 1];

                            existingFeature.Coordinates.Add(coord);

                            //refresh the map if line has 2 or more points
                            if (existingFeature.Coordinates.Count >= 3)
                            {
                                //refresh the map
                                polygonF.InitializeVertices();
                                map1.ResetBuffer();
                            }
                        }
                    }
                }
                else
                {
                    //right click - reset first mouse click
                    firstClick = true;
                }
                break;
            }
        }
Exemple #33
0
 private IQueryable <NearbyLocationModel> ProjectToNearbyLocationModel(IQueryable <Location> locations, NetTopologySuite.Geometries.Point targetPoint)
 {
     return(locations.Select(x => new NearbyLocationModel
     {
         Location = x,
         // not sure about the conversion
         DistanceInMeters = (int)x.Coordinates.Distance(targetPoint)
     }));
 }