// TODO: Implement the more sophisticated method
        // TODO: Move coordinates class and add accuracy field?
        private PatternMiningCoordinates FindBestCoordinates(Dictionary <string, int> geohashCounts, int ruleTotalCount)
        {
            string bestGeohash     = null;
            double highestFraction = -1;

            foreach (var entry in geohashCounts)
            {
                var geohash = entry.Key;
                var count   = entry.Value;

                var occFraction = count / (1.0d * ruleTotalCount);

                if (occFraction > highestFraction)
                {
                    bestGeohash     = geohash;
                    highestFraction = occFraction;
                }
            }

            var result = GeoHash.Decode(bestGeohash);

            return(new PatternMiningCoordinates()
            {
                Latitude = result.Coordinates.Lat,
                Longitude = result.Coordinates.Lon,
                Confidence = highestFraction
            });
        }
Пример #2
0
        public void Decode_WhenHashStringHasDefaultLength_ReturnsCoordinatesWithinStandardPrecision()
        {
            var geoHashDecodeResult = GeoHash.Decode(HashString);

            Assert.True(Math.Abs(Latitude - geoHashDecodeResult.Coordinates.Lat) < 0.0001, "(37.8324 - " + geoHashDecodeResult.Coordinates.Lat + " was >= 0.0001");
            Assert.True(Math.Abs(Longitude - geoHashDecodeResult.Coordinates.Lon) < 0.0001, "(112.5584 - " + geoHashDecodeResult.Coordinates.Lon + " was >= 0.0001");
        }
Пример #3
0
        public void DecodeFromCoords()
        {
            double lat_actual5 = 25.787, long_actual5 = -4.3291;
            var    calculated8 = GeoHash.Decode("eusftqx9");

            Assert.Equal(calculated8.Latitude.ToString().Substring(0, 6), lat_actual5.ToString());
            Assert.Equal(calculated8.Longitude.ToString().Substring(0, 7), long_actual5.ToString());
        }
Пример #4
0
        public async Task <IEnumerable <GeoClusterLocation> > GetGeoLocationClustersAsync(
            GetGeoLocationClustersRequest request,
            CancellationToken cancellationToken)
        {
            IEnumerable <MediaGeoLocation> medias = await _mediaStore.FindMediaInGeoBoxAsync(
                request.Box,
                100000,
                cancellationToken);

            var clusters = new List <GeoClusterLocation>();

            if (medias.Count() < 500 && request.Precision > 10)
            {
                //Add every item as cluster
                foreach (MediaGeoLocation media in medias)
                {
                    clusters.Add(new GeoClusterLocation()
                    {
                        Hash = GeoHash.Encode(
                            media.Coordinates.Latitude,
                            media.Coordinates.Longitude),

                        Coordinates = media.Coordinates,
                        Id          = media.Id,
                        Count       = 1
                    });
                }
            }
            else
            {
                medias.ToList().ForEach(x => x.GeoHash = x.GeoHash.Substring(0, request.Precision));
                IEnumerable <IGrouping <string, MediaGeoLocation> > grouped = medias
                                                                              .GroupBy(x => x.GeoHash);

                foreach (IGrouping <string, MediaGeoLocation>?group in grouped)
                {
                    GeohashDecodeResult decoded = GeoHash.Decode(group.Key);
                    var cluster = new GeoClusterLocation
                    {
                        Hash        = group.Key,
                        Count       = group.Count(),
                        Coordinates = new GeoCoordinate
                        {
                            Latitude  = decoded.Coordinates.Lat,
                            Longitude = decoded.Coordinates.Lon
                        }
                    };
                    if (group.Count() == 1)
                    {
                        cluster.Id = group.First().Id;
                    }
                    clusters.Add(cluster);
                }
            }

            return(clusters);
        }
Пример #5
0
        public static void BoundingCircleTest()
        {
            Coordinates c = new Coordinates {
                Lat = mLat, Lon = mLon
            };

            Console.WriteLine("point latitude " + c.Lat + ", longitude " + c.Lon);
            var encoded = GeoHash.Encode(c.Lat, c.Lon, mLevel);

            Console.WriteLine("encoded = " + encoded);

            var decoded   = GeoHash.Decode(encoded);
            var latitude  = decoded.Coordinates.Lat;
            var longitude = decoded.Coordinates.Lon;

            Console.WriteLine("decoded box latitude " + latitude + ", longitude " + longitude);

            BoundingBox box    = GeoHash.DecodeBbox(encoded);
            var         maxLat = box.Maximum.Lat;
            var         minLat = box.Minimum.Lat;
            var         maxLon = box.Maximum.Lon;
            var         minLon = box.Minimum.Lon;

            // Measure the box size in meters
            var oneSide     = DataBase.Measure(maxLat, minLon, minLat, minLon);
            var anotherSide = DataBase.Measure(maxLat, maxLon, maxLat, minLon);

            // Bounding circle
            var watch = System.Diagnostics.Stopwatch.StartNew();

            string[] hashList = DataBase.Bcircle(c.Lat, c.Lon, mRadius, mLevel);
            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

            //foreach (var h in hashList)
            //{
            //    Console.WriteLine(h);
            //}

            Console.WriteLine("box size: " + oneSide + " meters * " + anotherSide + " meters");
            Console.WriteLine("bounding circle radius " + mRadius + " meters, level " + mLevel);
            Console.WriteLine("Get bounding circle, time elapsed: " + elapsedMs + " ms | " + hashList.Length + " results get");
            string filename = "bounding circle" + c.Lat.ToString() + "-" + c.Lon.ToString() + "-" + mRadius.ToString() + "-" + mLevel.ToString();

            KMLGenerator.GenerateKMLBoundingCircle(hashList, c.Lat, c.Lon, mRadius, filename);
            Console.WriteLine("save as file name " + filename);
        }
Пример #6
0
        public void Decode()
        {
            var gp1 = GeoHash.Decode("wx4g8c9vn");

            Assert.True(Math.Abs(116.402843 - gp1.Longitude) < 0.0001);
            Assert.True(Math.Abs(39.999375 - gp1.Latitude) < 0.0001);

            var gp2 = GeoHash.Decode("wx4g89tkz");

            Assert.True(Math.Abs(116.3967 - gp2.Longitude) < 0.0001);
            Assert.True(Math.Abs(39.99932 - gp2.Latitude) < 0.0001);

            var gp3 = GeoHash.Decode("wx4g0ffev");

            Assert.True(Math.Abs(116.40382 - gp3.Longitude) < 0.0001);
            Assert.True(Math.Abs(39.918118 - gp3.Latitude) < 0.0001);
        }
Пример #7
0
        static void Main(string[] args)
        {
            Stopwatch sp = new Stopwatch();

            #region Set
            //普通set
            sp.Start();
            for (int i = 0; i < 10000; i++)
            {
                RedisHelper.Item_SetString(conn, "test_" + i, "value_" + i);
            }
            sp.Stop();
            Console.WriteLine("time:" + sp.Elapsed.TotalMilliseconds);
            //批量set
            sp.Restart();
            Dictionary <string, string> temp = new Dictionary <string, string>();
            for (int i = 0; i < 10000; i++)
            {
                temp.Add("test_" + i, "value_" + i);
            }
            RedisHelper.Item_MSet(conn, temp);
            sp.Stop();
            Console.WriteLine("batch_time:" + sp.Elapsed.TotalMilliseconds);
            //管道set
            sp.Restart();
            Dictionary <string, string> temp2 = new Dictionary <string, string>();
            for (int i = 0; i < 10000; i++)
            {
                temp2.Add("test_" + i, "value_" + i);
            }
            RedisHelper.Item_SetAsync(conn, temp2);
            sp.Stop();
            Console.WriteLine("pipeline_time:" + sp.Elapsed.TotalMilliseconds);
            #endregion

            #region Get
            //普通get
            sp.Restart();
            List <string> list1 = new List <string>();
            for (int i = 0; i < 10000; i++)
            {
                list1.Add(RedisHelper.Item_GetString(conn, "test_" + i));
            }
            sp.Stop();
            Console.WriteLine("Get_Time:" + sp.Elapsed.TotalMilliseconds);
            //批量get
            sp.Restart();
            List <string> list2 = new List <string>();
            string[]      keys1 = new string[10000];
            for (int i = 0; i < 10000; i++)
            {
                keys1[i] = "test_" + i;
            }
            list2.AddRange(RedisHelper.Item_MGet(conn, keys1));
            sp.Stop();
            Console.WriteLine("batch_Time:" + sp.Elapsed.TotalMilliseconds);
            //管道get
            sp.Restart();
            List <string> list3 = new List <string>();
            string[]      keys2 = new string[10000];
            for (int i = 0; i < 10000; i++)
            {
                keys2[i] = "test_" + i;
            }
            list3.AddRange(RedisHelper.Item_MGet(conn, keys2));
            sp.Stop();
            Console.WriteLine("pipeline_Time:" + sp.Elapsed.TotalMilliseconds);
            #endregion

            double lng = 121.490546;
            double lat = 31.262235;

            #region GeoHash
            string geohash = GeoHash.Encode(lat, lng);
            var    ret     = GeoHash.Decode(geohash);
            #endregion

            #region RedisGeo
            RedisHelper.GeoHashAdd(conn, "TestGeo", lat, lng, "1234");
            RedisHelper.GeoHashAdd(conn, "TestGeo", lat + 1, lng + 1, "1235");
            RedisHelper.GeoHashAdd(conn, "TestGeo", lat + 23, lng + 45, "1236");
            RedisHelper.GeoHashAdd(conn, "TestGeo", lat + 8, lng + 37, "1237");
            RedisHelper.GeoHashAdd(conn, "TestGeo", lat + 15, lng - 23, "1238");

            string geoHash  = RedisHelper.GeoHash(conn, "TestGeo", "1234");
            var    distince = RedisHelper.GeoHashDistance(conn, "TestGeo", "1234", "1235");
            var    location = RedisHelper.GeoHashLocation(conn, "TestGeo", "1234");
            var    list     = RedisHelper.GeoHashRadius(conn, "TestGeo", lat, lng, 10000, -1, 0, 1);
            #endregion

            Console.ReadKey();
        }
Пример #8
0
        /// <summary>
        /// Bounding Circle
        /// Get all the hashString covered by the circle in numberOfChars
        /// </summary>
        /// <param name="latitude">latitude of center point</param>
        /// <param name="longitude">longitude of center point</param>
        /// <param name="radius">radius in meters</param>
        /// <param name="numberOfChars">number of characters of hash string</param>
        /// <returns>hash string array</returns>
        public static string[] Bcircle(double latitude, double longitude, double radius, int numberOfChars = 9)
        {
            var    hashList   = new List <string>();
            string hashCenter = GeoHash.Encode(latitude, longitude, numberOfChars);

            hashList.Add(hashCenter);

            GeohashDecodeResult latLon = GeoHash.Decode(hashCenter);

            // Find left and right end
            // Find west(left) end
            Coordinates leftCoor = DistanceToPoint(latitude, longitude, radius, 270);
            string      hashLeft = GeoHash.Encode(leftCoor.Lat, leftCoor.Lon, numberOfChars);

            NGeoHash.BoundingBox boxLeft = GeoHash.DecodeBbox(hashLeft);

            // Find east(right) end
            Coordinates rightCoor = DistanceToPoint(latitude, longitude, radius, 90);
            string      hashRight = GeoHash.Encode(rightCoor.Lat, rightCoor.Lon, numberOfChars);

            NGeoHash.BoundingBox boxRight = GeoHash.DecodeBbox(hashRight);

            // Find steps(from left to right)
            double perLon  = latLon.Error.Lon * 2; // box size(in degree) on west-east direction
            var    lonStep = Math.Round((boxRight.Minimum.Lon - boxLeft.Minimum.Lon) / perLon);

            double perLat = latLon.Error.Lat * 2; // box size(in dgree) on north–south direction

            for (var lon = 0; lon <= lonStep; lon++)
            {
                // Find current box
                string currentBoxHash           = GeoHash.Neighbor(hashLeft, new[] { 0, lon });
                NGeoHash.BoundingBox currentBox = GeoHash.DecodeBbox(currentBoxHash);

                // Find north(upper) end
                // Find up neighbor
                // Check if in range
                int i = 0;
                NGeoHash.BoundingBox upBox = currentBox;
                string upBoxHash           = currentBoxHash;
                while (BoxInCircleRange(upBox, latitude, longitude, radius))
                {
                    if (!hashList.Contains(upBoxHash))
                    {
                        hashList.Add(upBoxHash);
                    }
                    //Console.WriteLine("Add+ " + upBoxHash);
                    i++;
                    upBoxHash = GeoHash.Neighbor(currentBoxHash, new[] { i, 0 });
                    upBox     = GeoHash.DecodeBbox(upBoxHash);
                }

                // Find south(down) end
                // Find steps(north to south)
                int j = 0;
                NGeoHash.BoundingBox downBox = currentBox;
                string downBoxHash           = currentBoxHash;
                while (BoxInCircleRange(downBox, latitude, longitude, radius))
                {
                    if (!hashList.Contains(downBoxHash))
                    {
                        hashList.Add(downBoxHash);
                    }
                    //Console.WriteLine("Add- " + downBoxHash);
                    j--;
                    downBoxHash = GeoHash.Neighbor(currentBoxHash, new[] { j, 0 });
                    downBox     = GeoHash.DecodeBbox(downBoxHash);
                }
            }

            // Check each point on the circle, see if covers more box
            // Find step length of radius
            double stepOfRadius = FindMinSideLength(hashCenter) * 0.9;
            // Find step of cricle, devide 360 degree to how many parts
            double stepOfCircle = 360 / (Math.PI * 2 * radius / stepOfRadius);

            for (double degree = 0; degree <= 360; degree += stepOfCircle)
            {
                Coordinates coor = DistanceToPoint(latitude, longitude, radius, degree);
                string      hash = GeoHash.Encode(coor.Lat, coor.Lon, numberOfChars);
                if (!hashList.Contains(hash))
                {
                    hashList.Add(hash);
                }
            }


            return(hashList.ToArray());
        }
Пример #9
0
 public void DecodeInvalid()
 {
     Assert.ThrowsAny <System.Collections.Generic.KeyNotFoundException>(() => GeoHash.Decode(@"happy times"));
 }