Esempio n. 1
0
        public void GetDistanceFromSegmentToPoint_ShouldReturnDistanceToTheEnd_WhenPlacedOnDiagonal()
        {
            var point   = new Point(0, 0);
            var segment = new Segment(new Point(1, 2), new Point(3, 2));

            var distance = DistanceUtils.GetDistanceFromSegmentToPoint(point, segment);

            distance.Should().BeApproximately(Math.Sqrt(5), Precision);
        }
Esempio n. 2
0
        public void GetDistanceFromPointToPoint_ShouldReturnDistance_WhenPointsOnOneLine()
        {
            var firstPoint  = new Point(1, 2);
            var secondPoint = new Point(3, 2);

            var distance = DistanceUtils.GetDistanceFromPointToPoint(firstPoint, secondPoint);

            distance.Should().BeApproximately(2, Precision);
        }
Esempio n. 3
0
        public void GetDistanceFromSegmentToPoint_ShouldReturnDistanceFromTheCenter_WhenRightUnderThePoint()
        {
            var point   = new Point(0, 0);
            var segment = new Segment(new Point(-1, 1), new Point(1, 1));

            var distance = DistanceUtils.GetDistanceFromSegmentToPoint(point, segment);

            distance.Should().BeApproximately(1, Precision);
        }
Esempio n. 4
0
        public virtual void TestOneMeterPrecision()
        {
            init(GeohashPrefixTree.MaxLevelsPossible);
            GeohashPrefixTree grid = (GeohashPrefixTree)((RecursivePrefixTreeStrategy)strategy).Grid;
            //DWS: I know this to be true.  11 is needed for one meter
            double degrees = DistanceUtils.Dist2Degrees(0.001, DistanceUtils.EarthMeanRadiusKilometers);

            assertEquals(11, grid.GetLevelForDistance(degrees));
        }
Esempio n. 5
0
        public double Calculate(SpatialContext ctx, Document document, Point origin, bool round = false)
        {
            var point      = document.GetPoint(ctx);
            var calc       = ctx.GetDistCalc();
            var distance   = calc.Distance(origin, point);
            var distanceKm = DistanceUtils.Degrees2Dist(distance, DistanceUtils.EARTH_EQUATORIAL_RADIUS_KM);

            return(round ? Math.Round(distanceKm * 1000d, 2, MidpointRounding.AwayFromZero) : distanceKm);
        }
        public void testOneMeterPrecision()
        {
            init(GeohashPrefixTree.GetMaxLevelsPossible());
            GeohashPrefixTree grid = (GeohashPrefixTree)((RecursivePrefixTreeStrategy)strategy).GetGrid();
            //DWS: I know this to be true.  11 is needed for one meter
            double degrees = DistanceUtils.Dist2Degrees(0.001, DistanceUtils.EARTH_MEAN_RADIUS_KM);

            assertEquals(11, grid.GetLevelForDistance(degrees));
        }
Esempio n. 7
0
        //Failing test from http://groups.google.com/group/ravendb/browse_thread/thread/7a93f37036297d48/
        public void CanSuccessfullyDoSpatialQueryOfNearbyLocations()
        {
            // These items is in a radius of 4 miles (approx 6,5 km)
            var areaOneDocOne   = new DummyGeoDoc(55.6880508001, 13.5717346673);
            var areaOneDocTwo   = new DummyGeoDoc(55.6821978456, 13.6076183965);
            var areaOneDocThree = new DummyGeoDoc(55.673251569, 13.5946697607);

            // This item is 12 miles (approx 19 km) from the closests in areaOne
            var closeButOutsideAreaOne = new DummyGeoDoc(55.8634157297, 13.5497731987);

            // This item is about 3900 miles from areaOne
            var newYork = new DummyGeoDoc(40.7137578228, -74.0126901936);

            var documentStore = new EmbeddableDocumentStore {
                RunInMemory = true
            };

            documentStore.Initialize();
            var session = documentStore.OpenSession();

            session.Store(areaOneDocOne);
            session.Store(areaOneDocTwo);
            session.Store(areaOneDocThree);
            session.Store(closeButOutsideAreaOne);
            session.Store(newYork);
            session.SaveChanges();

            var indexDefinition = new IndexDefinition
            {
                Map = "from doc in docs select new { _ = SpatialIndex.Generate(doc.Latitude, doc.Longitude) }"
            };

            documentStore.DatabaseCommands.PutIndex("FindByLatLng", indexDefinition);

            // Wait until the index is built
            session.Advanced.LuceneQuery <DummyGeoDoc>("FindByLatLng")
            .WaitForNonStaleResults()
            .ToArray();

            const double lat = 55.6836422426, lng = 13.5871808352;             // in the middle of AreaOne
            const double radius = 5.0;

            // Expcted is that 5.0 will return 3 results
            var nearbyDocs = session.Advanced.LuceneQuery <DummyGeoDoc>("FindByLatLng")
                             .WithinRadiusOf(radius, lat, lng)
                             .WaitForNonStaleResults()
                             .ToArray();

            Assert.NotEqual(null, nearbyDocs);
            Assert.Equal(3, nearbyDocs.Length);
            var dist = DistanceUtils.GetInstance();

            Assert.Equal(true, nearbyDocs.All(x => dist.GetDistanceMi(x.Latitude, x.Longitude, lat, lng) < radius));

            session.Dispose();
        }
Esempio n. 8
0
        public void GetDistanceFromPointToPoint_ShouldReturnDistance_WhenPointsOnDiagonal(
            int x, int y, double expectedResult)
        {
            var firstPoint  = new Point(0, 0);
            var secondPoint = new Point(x, y);

            var distance = DistanceUtils.GetDistanceFromPointToPoint(firstPoint, secondPoint);

            distance.Should().BeApproximately(expectedResult, Precision);
        }
Esempio n. 9
0
        public Point GetCenter()
        {
            double y = GetHeight() / 2 + minY;
            double x = GetWidth() / 2 + minX;

            if (minX > maxX)                     //WGS84
            {
                x = DistanceUtils.NormLonDEG(x); //in case falls outside the standard range
            }
            return(new PointImpl(x, y, ctx));
        }
        public Filter ToFilter(SpatialContext spatialContext, SpatialPrefixTree tree)
        {
            var strategy = new RecursivePrefixTreeStrategy(tree, GeoFieldName);

            var spatialArgs = new SpatialArgs(SpatialOperation.Intersects,
                                              spatialContext.MakeBufferedLineString(
                                                  this.Points.Select(p => (IPoint) new Point(p[0], p[1], spatialContext)).ToList(),
                                                  DistanceUtils.Dist2Degrees(this.Distance, DistanceUtils.EARTH_MEAN_RADIUS_KM)));

            return(strategy.MakeFilter(spatialArgs));
        }
Esempio n. 11
0
        public static TopDocs DistanceQueryAndSort_PointVectorStrategy(Searcher searcher, PointVectorStrategy strategy, Point myLocation)
        {
            var ctx = strategy.GetSpatialContext();

            var q = strategy.MakeQuery(new SpatialArgs(
                                           SpatialOperation.IsWithin,
                                           ctx.MakeCircle(myLocation, DistanceUtils.Dist2Degrees(20000, DistanceUtils.EARTH_MEAN_RADIUS_KM))));

            TopDocs hits = searcher.Search(q, null, 100, new Sort(new SortField("pointvector", new PointVectorDistanceFieldComparatorSource(myLocation, strategy))));

            return(hits);
        }
Esempio n. 12
0
 /// <summary>
 /// Calculates the distance in meters between two GPS locations.
 /// </summary>
 /// <param name="loc1">The first location.</param>
 /// <param name="loc2">The second location.</param>
 /// <returns>The distance in meters between the two locations.</returns>
 public static double GetDistance(IPoint loc1, IPoint loc2)
 {
     if (loc1 == null)
     {
         throw new ArgumentNullException(nameof(loc1));
     }
     if (loc2 == null)
     {
         throw new ArgumentNullException(nameof(loc2));
     }
     return(DistanceUtils.GetDistance(loc1.Latitude, loc1.Longitude, loc2.Latitude, loc2.Longitude));
 }
Esempio n. 13
0
        protected virtual void TestRectangle(double minX, double width, double minY, double height)
        {
            double maxX = minX + width;
            double maxY = minY + height;

            minX = NormX(minX);
            maxX = NormX(maxX);

            IRectangle r = ctx.MakeRectangle(minX, maxX, minY, maxY);

            //test equals & hashcode of duplicate
            IRectangle r2 = ctx.MakeRectangle(minX, maxX, minY, maxY);

            Assert.Equal(r, r2);
            Assert.Equal(r.GetHashCode(), r2.GetHashCode());

            string msg = r.ToString();

            Assert.Equal(/*msg,*/ width != 0 && height != 0, r.HasArea);
            Assert.Equal(/*msg,*/ width != 0 && height != 0, r.GetArea(ctx) > 0);
            if (ctx.IsGeo && r.Width == 360 && r.Height == 180)
            {
                //whole globe
                double earthRadius = DistanceUtils.ToDegrees(1);
                CustomAssert.EqualWithDelta(4 * Math.PI * earthRadius * earthRadius, r.GetArea(ctx), 1.0);//1km err
            }

            AssertEqualsRatio(msg, height, r.Height);
            AssertEqualsRatio(msg, width, r.Width);
            IPoint center = r.Center;

            msg += " ctr:" + center;
            //System.out.println(msg);
            AssertRelation(msg, SpatialRelation.CONTAINS, r, center);

            IDistanceCalculator dc = ctx.DistCalc;
            double dUR             = dc.Distance(center, r.MaxX, r.MaxY);
            double dLR             = dc.Distance(center, r.MaxX, r.MinY);
            double dUL             = dc.Distance(center, r.MinX, r.MaxY);
            double dLL             = dc.Distance(center, r.MinX, r.MinY);

            Assert.Equal(/*msg,*/ width != 0 || height != 0, dUR != 0);
            if (dUR != 0)
            {
                Assert.True(dUR > 0 && dLL > 0);
            }
            AssertEqualsRatio(msg, dUR, dUL);
            AssertEqualsRatio(msg, dLR, dLL);
            if (!ctx.IsGeo || center.Y == 0)
            {
                AssertEqualsRatio(msg, dUR, dLL);
            }
        }
Esempio n. 14
0
        private void Search()
        {
            IndexReader   indexReader   = DirectoryReader.Open(directory);
            IndexSearcher indexSearcher = new IndexSearcher(indexReader);
            Sort          idSort        = new Sort(new SortField("id", SortFieldType.INT32));

            //--Filter by circle (<= distance from a point)
            {
                //Search with circle
                //note: SpatialArgs can be parsed from a string
                SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects,
                                                   ctx.MakeCircle(-80.0, 33.0, DistanceUtils.Dist2Degrees(200, DistanceUtils.EARTH_MEAN_RADIUS_KM)));
                Filter  filter = strategy.MakeFilter(args);
                TopDocs docs   = indexSearcher.Search(new MatchAllDocsQuery(), filter, 10, idSort);
                AssertDocMatchedIds(indexSearcher, docs, 2);
                //Now, lets get the distance for the 1st doc via computing from stored point value:
                // (this computation is usually not redundant)
                Document doc1    = indexSearcher.Doc(docs.ScoreDocs[0].Doc);
                String   doc1Str = doc1.GetField(strategy.FieldName).GetStringValue();
                //assume doc1Str is "x y" as written in newSampleDocument()
                int    spaceIdx    = doc1Str.IndexOf(' ');
                double x           = double.Parse(doc1Str.Substring(0, spaceIdx - 0), CultureInfo.InvariantCulture);
                double y           = double.Parse(doc1Str.Substring(spaceIdx + 1), CultureInfo.InvariantCulture);
                double doc1DistDEG = ctx.CalcDistance(args.Shape.Center, x, y);
                assertEquals(121.6d, DistanceUtils.Degrees2Dist(doc1DistDEG, DistanceUtils.EARTH_MEAN_RADIUS_KM), 0.1);
                //or more simply:
                assertEquals(121.6d, doc1DistDEG * DistanceUtils.DEG_TO_KM, 0.1);
            }
            //--Match all, order by distance ascending
            {
                IPoint      pt          = ctx.MakePoint(60, -50);
                ValueSource valueSource = strategy.MakeDistanceValueSource(pt, DistanceUtils.DEG_TO_KM);    //the distance (in km)
                Sort        distSort    = new Sort(valueSource.GetSortField(false)).Rewrite(indexSearcher); //false=asc dist
                TopDocs     docs        = indexSearcher.Search(new MatchAllDocsQuery(), 10, distSort);
                AssertDocMatchedIds(indexSearcher, docs, 4, 20, 2);
                //To get the distance, we could compute from stored values like earlier.
                // However in this example we sorted on it, and the distance will get
                // computed redundantly.  If the distance is only needed for the top-X
                // search results then that's not a big deal. Alternatively, try wrapping
                // the ValueSource with CachingDoubleValueSource then retrieve the value
                // from the ValueSource now. See LUCENE-4541 for an example.
            }
            //demo arg parsing
            {
                SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects,
                                                   ctx.MakeCircle(-80.0, 33.0, 1));
                SpatialArgs args2 = new SpatialArgsParser().Parse("Intersects(BUFFER(POINT(-80 33),1))", ctx);
                assertEquals(args.toString(), args2.toString());
            }

            indexReader.Dispose();
        }
Esempio n. 15
0
 private void Init()
 {
     if (radiusDEG > 90)
     {
         //--spans more than half the globe
         Debug.Assert(enclosingBox.GetWidth() == 360);
         double backDistDEG = 180 - radiusDEG;
         if (backDistDEG > 0)
         {
             double backRadius = 180 - radiusDEG;
             double backX      = DistanceUtils.NormLonDEG(GetCenter().GetX() + 180);
             double backY      = DistanceUtils.NormLatDEG(GetCenter().GetY() + 180);
             //Shrink inverseCircle as small as possible to avoid accidental overlap.
             // Note that this is tricky business to come up with a value small enough
             // but not too small or else numerical conditioning issues become a problem.
             backRadius -= Math.Max(Ulp(Math.Abs(backY) + backRadius), Ulp(Math.Abs(backX) + backRadius));
             if (inverseCircle != null)
             {
                 inverseCircle.Reset(backX, backY, backRadius);
             }
             else
             {
                 inverseCircle = new GeoCircle(ctx.MakePoint(backX, backY), backRadius, ctx);
             }
         }
         else
         {
             inverseCircle = null;        //whole globe
         }
         horizAxisY = GetCenter().GetY(); //although probably not used
     }
     else
     {
         inverseCircle = null;
         double _horizAxisY = ctx.GetDistCalc().CalcBoxByDistFromPt_yHorizAxisDEG(GetCenter(), radiusDEG, ctx);
         //some rare numeric conditioning cases can cause this to be barely beyond the box
         if (_horizAxisY > enclosingBox.GetMaxY())
         {
             horizAxisY = enclosingBox.GetMaxY();
         }
         else if (_horizAxisY < enclosingBox.GetMinY())
         {
             horizAxisY = enclosingBox.GetMinY();
         }
         else
         {
             horizAxisY = _horizAxisY;
         }
         //Debug.Assert(enclosingBox.Relate_yRange(horizAxis, horizAxis, ctx).Intersects());
     }
 }
Esempio n. 16
0
            public override float CustomScore(int doc, float subQueryScore, float valSrcScore)
            {
                var dist = CalculateDistance(doc);

                var distanceInHundredsOfMeters = (float)DistanceUtils.Degrees2Dist(dist, DistanceUtils.EARTH_EQUATORIAL_RADIUS_KM) * 10;

                if (distanceInHundredsOfMeters < 1)
                {
                    distanceInHundredsOfMeters = 1;
                }

                // Perhaps another distance boost algorithm?
                return(subQueryScore + 1 / distanceInHundredsOfMeters);
            }
Esempio n. 17
0
        public void GetClosestToThePointRectangle_ShouldReturnClosestRectangle_WhenThreeRectangles()
        {
            var point           = new Point(0, 0);
            var firstRectangle  = new Rectangle(new Point(2, 1), new Size(3, 2));
            var secondRectangle = new Rectangle(new Point(-5, 0), new Size(4, 2));
            var thirdRectangle  = new Rectangle(new Point(-1, 3), new Size(2, 3));

            var result = DistanceUtils.GetClosestToThePointRectangle(
                point, new List <Rectangle> {
                firstRectangle, secondRectangle, thirdRectangle
            });

            result.Should().Be(secondRectangle);
        }
Esempio n. 18
0
        public static TopDocs DistanceFilter_PointVectorStrategy(Searcher searcher, PointVectorStrategy strategy, Point myLocation)
        {
            var ctx = strategy.GetSpatialContext();

            var q      = new MatchAllDocsQuery();
            var filter = strategy.MakeFilter(new SpatialArgs(SpatialOperation.IsWithin,
                                                             ctx.MakeCircle(myLocation,
                                                                            DistanceUtils.Dist2Degrees(2000,
                                                                                                       DistanceUtils
                                                                                                       .EARTH_MEAN_RADIUS_KM))));
            TopDocs hits = searcher.Search(q, filter, 100);

            return(hits);
        }
Esempio n. 19
0
        /// <summary>
        /// Calls <see cref="DistanceUtils.CalcLonDegreesAtLat(double, double)"/> given pA or pB's latitude;
        /// whichever is farthest. It's useful to expand a buffer of a line segment when used in
        /// a geospatial context to cover the desired area.
        /// </summary>
        public static double ExpandBufForLongitudeSkew(IPoint pA, IPoint pB,
                                                       double buf)
        {
            double absA   = Math.Abs(pA.Y);
            double absB   = Math.Abs(pB.Y);
            double maxLat = Math.Max(absA, absB);
            double newBuf = DistanceUtils.CalcLonDegreesAtLat(maxLat, buf);

            //    if (newBuf + maxLat >= 90) {
            //      //TODO substitute spherical cap ?
            //    }
            Debug.Assert(newBuf >= buf);
            return(newBuf);
        }
Esempio n. 20
0
            public override float CustomScore(int doc, float subQueryScore, float valSrcScore)
            {
                var dist = CalculateDistance(doc);

                var distanceInHundredsOfMeters = (float)DistanceUtils.Degrees2Dist(dist, DistanceUtils.EARTH_EQUATORIAL_RADIUS_KM) * 10;

                if (distanceInHundredsOfMeters < 1)
                {
                    distanceInHundredsOfMeters = 1;
                }

                Console.WriteLine("docid {0} - dist = {1}, subscore = {3},  score = {2}", doc, dist, subQueryScore + 1 / distanceInHundredsOfMeters, subQueryScore);

                // Perhaps another distance boost algorithm?
                return(subQueryScore + 1 / distanceInHundredsOfMeters);
            }
Esempio n. 21
0
 protected Rectangle makeNormRect(double minX, double maxX, double minY, double maxY)
 {
     if (ctx.IsGeo())
     {
         if (Math.Abs(maxX - minX) >= 360)
         {
             minX = -180;
             maxX = 180;
         }
         else
         {
             minX = DistanceUtils.NormLonDEG(minX);
             maxX = DistanceUtils.NormLonDEG(maxX);
         }
     }
     return(ctx.MakeRectangle(minX, maxX, minY, maxY));
 }
Esempio n. 22
0
        private void TestDistCalcPointOnBearing(double distKm, double EPS)
        {
            for (int angDEG = 0; angDEG < 360; angDEG += random.Next(1, 20))
            {
                Point c = ctx.MakePoint(
                    DistanceUtils.NormLonDEG(random.Next(359)),
                    random.Next(-90, 90));

                //0 distance means same point
                Point p2 = dc().PointOnBearing(c, 0, angDEG, ctx, null);
                Assert.Equal(c, p2);

                p2 = dc().PointOnBearing(c, distKm * DistanceUtils.KM_TO_DEG, angDEG, ctx, null);
                double calcDistKm = dc().Distance(c, p2) * DistanceUtils.DEG_TO_KM;
                AssertEqualsRatio(distKm, calcDistKm, EPS);
            }
        }
Esempio n. 23
0
        public void PutNextRectangle_ShouldPlaceRectanglesCloseToCircle_WhenManyRectanglesWithSameSize(
            int rectanglesCount)
        {
            var size = new Size(2, 1);

            rectangles = Enumerable.Range(0, rectanglesCount)
                         .Select(n => layouter.PutNextRectangle(size)).ToList();

            var expectedMaxDelta = rectangles.Select(RectangleUtils.GetRectangleDiagonal).Max();

            var convexHullPoints = GeometryUtils.BuildConvexHull(rectangles);
            var distances        = convexHullPoints.Select(p => DistanceUtils.GetDistanceFromPointToPoint(p, config.Center))
                                   .ToList();
            var actualDelta = distances.Max() - distances.Min();

            (expectedMaxDelta - actualDelta).Should().BeGreaterOrEqualTo(0);
        }
Esempio n. 24
0
        private void assertDistanceConversion(double dist)
        {
            double radius = DistanceUtils.EARTH_MEAN_RADIUS_KM;
            //test back & forth conversion for both
            double distRAD = DistanceUtils.Dist2Radians(dist, radius);

            CustomAssert.EqualWithDelta(dist, DistanceUtils.Radians2Dist(distRAD, radius), EPS);
            double distDEG = DistanceUtils.Dist2Degrees(dist, radius);

            CustomAssert.EqualWithDelta(dist, DistanceUtils.Degrees2Dist(distDEG, radius), EPS);
            //test across rad & deg
            CustomAssert.EqualWithDelta(distDEG, DistanceUtils.ToDegrees(distRAD), EPS);
            //test point on bearing
            CustomAssert.EqualWithDelta(
                DistanceUtils.PointOnBearingRAD(0, 0, DistanceUtils.Dist2Radians(dist, radius),
                                                DistanceUtils.DEG_90_AS_RADS, ctx, new PointImpl(0, 0, ctx)).GetX(),
                distRAD, 10e-5);
        }
Esempio n. 25
0
        public static TopDocs DistanceFilter_RecursivePrefixTreeStrategy(Searcher searcher, RecursivePrefixTreeStrategy strategy, Point myLocation)
        {
            var ctx = strategy.GetSpatialContext();

            var q      = new MatchAllDocsQuery();
            var filter = strategy.MakeFilter(new SpatialArgs(SpatialOperation.Intersects,
                                                             ctx.MakeCircle(myLocation,
                                                                            DistanceUtils.Dist2Degrees(2000,
                                                                                                       DistanceUtils
                                                                                                       .EARTH_MEAN_RADIUS_KM))));

            // Reverse sorting...
            var sortField = new SortField(null, SortField.SCORE, true);

            TopDocs hits = searcher.Search(q, filter, 100, new Sort(sortField));

            return(hits);
        }
Esempio n. 26
0
        private static Filter CreateGeoDistanceFilter(GeoDistanceFilter geoDistanceFilter)
        {
            Filter result = null;

            if (geoDistanceFilter?.FieldName != null && geoDistanceFilter.Location != null)
            {
                var spatialContext = SpatialContext.GEO;
                var distance       = DistanceUtils.Dist2Degrees(geoDistanceFilter.Distance, DistanceUtils.EARTH_MEAN_RADIUS_KM);
                var searchArea     = spatialContext.MakeCircle(geoDistanceFilter.Location.Longitude, geoDistanceFilter.Location.Latitude, distance);
                var spatialArgs    = new SpatialArgs(SpatialOperation.Intersects, searchArea);

                var fieldName = LuceneSearchHelper.ToLuceneFieldName(geoDistanceFilter.FieldName);
                var strategy  = new PointVectorStrategy(spatialContext, fieldName);
                result = strategy.MakeFilter(spatialArgs);
            }

            return(result);
        }
Esempio n. 27
0
        private SpatialArgs GetArgs(int docId, int distanceInKms)
        {
            Document doc = base.indexSearcher.IndexReader.Document(docId, null);

            SpatialContext ctx = _spatialStrategy.GetSpatialContext();

            string[] parts = doc.Get(StrategyPrefix, null)
                             .Split(' ');

            Point pt = ctx.MakePoint(double.Parse(parts[0]),
                                     double.Parse(parts[1]));

            Circle circle = ctx.MakeCircle(pt, DistanceUtils.Dist2Degrees(distanceInKms, DistanceUtils.EARTH_MEAN_RADIUS_KM));

            var args = new SpatialArgs(SpatialOperation.Intersects, circle);

            return(args);
        }
Esempio n. 28
0
        public void CreateSpatialFilterAndWeight(PointRadiusCriterion geoFilter, Filter currentFilter, Weight currentWeight)
        {
            var spatialContext = SpatialContext.GEO;
            var geohashTree    = new GeohashPrefixTree(spatialContext, 10);
            var strategy       = new RecursivePrefixTreeStrategy(geohashTree, geoFilter.FieldName);
            var point          = spatialContext.MakePoint(geoFilter.Longitude, geoFilter.Latitude);

            var spatialArgs = new SpatialArgs(SpatialOperation.Intersects, spatialContext.MakeCircle(point,
                                                                                                     DistanceUtils.Dist2Degrees(geoFilter.RadiusKm, DistanceUtils.EARTH_MEAN_RADIUS_KM)));

            var circle = spatialContext.MakeCircle(point,
                                                   DistanceUtils.Dist2Degrees(geoFilter.RadiusKm, DistanceUtils.EARTH_MEAN_RADIUS_KM));
            var circleCells = strategy.GetGrid().GetWorldNode().GetSubCells(circle);

            var luceneFilters = new List <Filter>();

            if (currentFilter != null)
            {
                luceneFilters.Add(currentFilter);
            }

            var tempSpatial = strategy.MakeFilter(spatialArgs);

            luceneFilters.Add(tempSpatial);

            if (geoFilter.Sort != PointRadiusCriterion.SortOption.None)
            {
                var valueSource = strategy.MakeDistanceValueSource(point);
                var funcQ       = new FunctionQuery(valueSource);
                // this is a bit odd... but boosting the score negatively orders results
                if (geoFilter.Sort == PointRadiusCriterion.SortOption.Ascending)
                {
                    funcQ.Boost = -1;
                }
                spatialWeight = funcQ.CreateWeight(this);
                spatialWeight.GetSumOfSquaredWeights();

                luceneFilters.Add(new QueryWrapperFilter(currentWeight.Query));
            }

            spatialFilter = new ChainedFilter(luceneFilters.ToArray(), 1);
        }
Esempio n. 29
0
 public virtual IShape GetBuffered(double distance, SpatialContext ctx)
 {
     if (ctx.IsGeo)
     {
         //first check pole touching, triggering a world-wrap rect
         if (maxY + distance >= 90)
         {
             return(ctx.MakeRectangle(-180, 180, Math.Max(-90, minY - distance), 90));
         }
         else if (minY - distance <= -90)
         {
             return(ctx.MakeRectangle(-180, 180, -90, Math.Min(90, maxY + distance)));
         }
         else
         {
             //doesn't touch pole
             double latDistance    = distance;
             double closestToPoleY = (maxY - minY > 0) ? maxY : minY;
             double lonDistance    = DistanceUtils.CalcBoxByDistFromPt_deltaLonDEG(
                 closestToPoleY, minX, distance); //lat,lon order
                                                  //could still wrap the world though...
             if (lonDistance * 2 + Width >= 360)
             {
                 return(ctx.MakeRectangle(-180, 180, minY - latDistance, maxY + latDistance));
             }
             return(ctx.MakeRectangle(
                        DistanceUtils.NormLonDEG(minX - lonDistance),
                        DistanceUtils.NormLonDEG(maxX + lonDistance),
                        minY - latDistance, maxY + latDistance));
         }
     }
     else
     {
         IRectangle worldBounds = ctx.WorldBounds;
         double     newMinX     = Math.Max(worldBounds.MinX, minX - distance);
         double     newMaxX     = Math.Min(worldBounds.MaxX, maxX + distance);
         double     newMinY     = Math.Max(worldBounds.MinY, minY - distance);
         double     newMaxY     = Math.Min(worldBounds.MaxY, maxY + distance);
         return(ctx.MakeRectangle(newMinX, newMaxX, newMinY, newMaxY));
     }
 }
Esempio n. 30
0
        private Document CreateRandomDoc(int docId, Random rng, SpatialContext ctx)
        {
            Point shape = ctx.MakePoint(DistanceUtils.NormLonDEG(rng.NextDouble() * 360.0), DistanceUtils.NormLatDEG(rng.NextDouble() * 180.0));

            var doc = new Document();

            var idField = new NumericField("locationId", Field.Store.YES, true);

            idField.SetIntValue(docId);

            doc.Add(idField);

            foreach (AbstractField field in _spatialStrategy.CreateIndexableFields(shape))
            {
                doc.Add(field);
            }

            doc.Add(_spatialStrategy.CreateStoredField(shape));

            return(doc);
        }