private static async Task <string> AddIntervention( InterventionDto intervention, CloudTable interventionsTable, Address convertedGeoAddress ) { int nextId = await InterventionCounter.GetNextId(interventionsTable); InterventionEntity interventionEntity = new InterventionEntity() { PartitionKey = GeoHash.Encode(convertedGeoAddress.Latitude, convertedGeoAddress.Lognitude, Config.GeoHashPrecision), RowKey = nextId.ToString(), Email = intervention.Email, City = intervention.City, Street = intervention.Street, StreetNumber = intervention.StreetNumber, CreationDate = DateTime.UtcNow, ModificationDate = DateTime.UtcNow, Description = intervention.Description, FullName = intervention.FullName, PhoneNumber = intervention.PhoneNumber, Status = (int)intervention.Status, GeoLat = convertedGeoAddress.Latitude, GeoLng = convertedGeoAddress.Lognitude, }; TableOperation insertNewIntervention = TableOperation.Insert(interventionEntity); await interventionsTable.ExecuteAsync(insertNewIntervention); return(interventionEntity.RowKey); }
public async Task <Place> CreatePlace(Place place, string user) { if (!place.Owners.Any()) { place.Owners.Add(new Entities.Application.ListableUser { Id = user }); } if (place.MainPlaylist != null && place.MainPlaylist.Id != null && string.IsNullOrEmpty(place.MainPlaylist.Name)) { var dbUser = await this.userService.GetUser(user); var play = await this.playlistService.GetPlaylistFromSpotify(place.MainPlaylist.Id, dbUser.CurrentToken); if (play != null) { place.MainPlaylist = play; } } place.Geohash = GeoHash.Encode(place.Location.Latitude, place.Location.Longitude); var converted = _mapper.ToDbEntity(place); var dbResult = await _dao.CreatePlace(converted); if (place.MainPlaylist != null) { await this.playlistService.CreatePlaylist(dbResult.Reference.Id, place.MainPlaylist); } return(_mapper.ToApplicationEntity(dbResult)); }
/// <summary> /// Add coordinates to database(in use) /// </summary> /// <param name="coordinate"></param> public void Add(Coordinates coordinate) { double latitude = coordinate.Lat; double longitude = coordinate.Lon; for (int numberOfChars = 1; numberOfChars <= _MaxNumberOfChar; numberOfChars++) { // Get the key string key = GeoHash.Encode(latitude, longitude, numberOfChars); // The value is coordinate // First entry if (!_Dict.ContainsKey(key)) { List <Coordinates> value = new List <Coordinates> { coordinate }; _Dict.Add(key, value); //Console.WriteLine("Add new key " + key); } // Second entry else if (_Dict.ContainsKey(key) && _Dict[key].Count < _MaxCoordinatesInValue) { _Dict[key].Add(coordinate); //Console.WriteLine("Add existent key " + key + ", " + Dict[key].Count); } // The deepest level else if (numberOfChars == _MaxCoordinatesInValue) { _Dict[key].Add(coordinate); //Console.WriteLine("Add existent key " + key + ", " + Dict[key].Count); } } }
public ClosestCityFinder( string citiesPath, string alternateNamesPath, string admin1Path, string admin2Path, string countriesPath, string clliPath, string unlocodePath) { var alternateNamesDict = GeonamesAlternateNamesParser.ParseToDict(alternateNamesPath); var admin1Dict = GeonamesAdminParser.ParseToDict(admin1Path); var admin2Dict = GeonamesAdminParser.ParseToDict(admin2Path); var countryEntities = GeonamesCountriesParser.ParseToList(countriesPath); var countryCodesDict = GeonamesCountriesParser.ListToISOCodeDict(countryEntities); var geonamesIdsToCLLICodes = CLLICodesParser.ParseToDict(clliPath); var geonamesIdsToUNLOCODECodes = UNLOCODECodesParser.ParseToDict(unlocodePath); this.GeohashesToCities = new Dictionary <string, List <GeonamesCityEntity> >(); foreach (var entity in GeonamesCitiesParser.Parse(citiesPath, alternateNamesDict, admin1Dict, admin2Dict, countryCodesDict, geonamesIdsToCLLICodes, geonamesIdsToUNLOCODECodes)) { var geohash = GeoHash.Encode(entity.Latitude, entity.Longitude, numberOfChars: 3); // 3 = ±78km List <GeonamesCityEntity> citiesInGeohash; if (!this.GeohashesToCities.TryGetValue(geohash, out citiesInGeohash)) { citiesInGeohash = new List <GeonamesCityEntity>(); this.GeohashesToCities[geohash] = citiesInGeohash; } citiesInGeohash.Add(entity); } }
public JObject BpolygonSearchProcess(Coordinates select, Coordinates[] polygon, int level) { string hash = GeoHash.Encode(select.Lat, select.Lon, level); // get all other points(out of range) in box Coordinates[] allCoordinates = GetCoordinates(hash); List <Coordinates> coordinatesInRange = new List <Coordinates>(); List <Coordinates> coordinatesOutOfRange = new List <Coordinates>(); foreach (Coordinates c in allCoordinates) { if (PointInPolygon(c, polygon)) { coordinatesInRange.Add(c); } else { coordinatesOutOfRange.Add(c); } } JObject json = JObject.FromObject( new { Boxhash = hash, CoordinatesInRange = coordinatesInRange, CoordinatesOutOfRange = coordinatesOutOfRange } ); return(json); }
public JObject BoundingCircleSearchProcess(double selectLatitude, double selectLongitude, double searchLatitude, double searchLongitude, double radius, int level = 9) { string hash = GeoHash.Encode(selectLatitude, selectLongitude, level); // get all other points(out of range) in box Coordinates[] allCoordinates = GetCoordinates(hash); List <Coordinates> coordinatesInRange = new List <Coordinates>(); List <Coordinates> coordinatesOutOfRange = new List <Coordinates>(); foreach (Coordinates c in allCoordinates) { if (Measure(c.Lat, c.Lon, searchLatitude, searchLongitude) <= radius) { coordinatesInRange.Add(c); } else { coordinatesOutOfRange.Add(c); } } JObject json = JObject.FromObject( new { Boxhash = hash, CoordinatesInRange = coordinatesInRange, CoordinatesOutOfRange = coordinatesOutOfRange } ); return(json); }
// geohash.org public string GetPathAsGeoHash() { // var locations = locationService.Get(); //var path = locationService.Get().Select(l => GeoHash.Encode(l.Latitude, l.Longitude)); return string.Join(",", locationService.Get().Select(l => GeoHash.Encode(l.Latitude, l.Longitude))); }
public static string GetGeoHash(string latitude, string longitude) { var latitudeParsed = double.Parse(latitude, CultureInfo.InvariantCulture); var longitudeParsed = double.Parse(longitude, CultureInfo.InvariantCulture); var geoHash = GeoHash.Encode(latitudeParsed, longitudeParsed, Config.GeoHashPrecision); return(geoHash); }
public void Encode() { // 鸟巢 Assert.Equal("wx4g8c9vn", GeoHash.Encode(116.402843, 39.999375)); // 水立方 Assert.Equal("wx4g89tkz", GeoHash.Encode(116.3967, 39.99932)); // 故宫 Assert.Equal("wx4g0ffev", GeoHash.Encode(116.40382, 39.918118)); }
public void Encode_WhenTheNumberOfCharsIsProvided_ReturnsHashStringWithTheProvidedNumberOfChars() { const int hashStringNumberOfChars = 3; var actualHashString = GeoHash.Encode(32, 117, hashStringNumberOfChars); Assert.Equal(hashStringNumberOfChars, actualHashString.Length); Assert.Equal("wte", actualHashString); }
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); }
public void Encode_WhenTheNumberOfCharsIsNotProvided_ReturnsHashStringWithTheDefaultNumberOfChars() { const int defaultHashStringNumberOfChars = 9; var actualHashString = GeoHash.Encode(Latitude, Longitude); Assert.Equal(defaultHashStringNumberOfChars, actualHashString.Length); Assert.Equal(HashString, actualHashString); }
static void Main(string[] args) { var dataReader = new DataFileReader <GeoInfoModel>(); var dir = Path.Combine(Directory.GetCurrentDirectory(), "../../../../../data/001/"); var imgDir = Path.Combine(Directory.GetCurrentDirectory(), "img"); var pltFiles = FileTools.GetAllFile(dir, "*.plt"); var tracks = dataReader.GetTrajectories(pltFiles); Parallel.ForEach(tracks, t => { t.GeoCodes = t.GeoPoints.Select(tt => GeoHash.Encode(tt.Latitude, tt.Longitude, 7)) .Distinct() .ToList(); }); Console.WriteLine(tracks.Count()); var cluster = new CommonSubsequenceCluster(); var sh = new Stopwatch(); sh.Start(); var tree = cluster.BuildClusterTree(tracks.ToArray(), 0.7f, 0.4f); Console.WriteLine($"BuildClusterTree, count:{tracks.Count()}, time:{sh.Elapsed}"); if (Directory.Exists(imgDir)) { Directory.GetFiles(imgDir, "*.png") .ToList() .ForEach(File.Delete); } else { Directory.CreateDirectory(imgDir); } cluster.ForeachTree(tree, node => { var draw = new DrawBase(256, 256) .OpenAutoFit(node.MinLon, node.MinLat, node.MaxLon, node.MaxLat) .Draw(node, Color.Red, 3); draw.Image.Save($"{imgDir}/{node.LevelTag}.png"); draw.Image.Dispose(); // Console.WriteLine(node.LevelTag); foreach (var sib in node.Siblings) { var drawSib = new DrawBase(256, 256) .OpenAutoFit(sib.MinLon, sib.MinLat, sib.MaxLon, sib.MaxLat) .Draw(sib, Color.Red, 3); drawSib.Image.Save($"{imgDir}/{sib.LevelTag}.png"); drawSib.Image.Dispose(); // Console.WriteLine(sib.LevelTag); } }); }
public void EncodeFromCoords() { string actual8 = "eusftqx9"; string calculated8 = GeoHash.Encode(25.78792, -4.32913, 8); Assert.Equal(actual8, calculated8); Assert.Equal("efkbt6rx", GeoHash.Encode(new GeoPoint(12.7578, -4.32913), 8)); Assert.Equal("fbukqnpp", GeoHash.Encode(new GeoPoint(50, -50), 8)); }
public async Task <string> GetGeoHashedLocation() { Geoposition position = await GetLocation(); if (position != null) { return(GeoHash.Encode(position.Coordinate.Latitude, position.Coordinate.Longitude, HashLength)); } return(null); }
/// <summary> /// Add coordinates to database(not in use) /// </summary> /// <param name="latitude"></param> /// <param name="longitude"></param> /// <param name="numberOfChars"></param> public void Add2(double latitude, double longitude, int numberOfChars = 1) { // Get the key string key = GeoHash.Encode(latitude, longitude, numberOfChars); // Get the value Coordinates coordinate = new Coordinates { Lat = latitude, Lon = longitude }; if (!_Dict.ContainsKey(key)) { List <Coordinates> value = new List <Coordinates> { coordinate }; _Dict.Add(key, value); //Console.WriteLine("Add new key " + key); return; } if (_Dict.ContainsKey(key) && _Dict[key].Count < _MaxCoordinatesInValue) { _Dict[key].Add(coordinate); //Console.WriteLine("Add existent key " + key + ", " + Dict[key].Count); return; } if (numberOfChars >= _MaxNumberOfChar) { _Dict[key].Add(coordinate); //Console.WriteLine("Add existent key " + key + ", " + Dict[key].Count); return; } // Check how many coordinates under this key // If more than maxCoordinatesInValue, encode one more level // Also calculate all upper level again, move to a deeper level if (_Dict.ContainsKey(key) && _Dict[key].Count >= _MaxCoordinatesInValue) { if (!_FullList.Contains(key)) { // Mark current level as full _FullList.Add(key); //Console.WriteLine("Add " + key + " to full list"); // Move current level to the deeper level foreach (var coor in _Dict[key]) { Add2(coor.Lat, coor.Lon, numberOfChars + 1); } } // Calculate one more level Add2(latitude, longitude, numberOfChars + 1); } }
public async Task <ActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "interventions")] [RequestBodyType(typeof(InterventionDto), "InterventionDto")] InterventionDto intervention, [Table(Config.InterventionsTableName, Connection = Config.StorageConnectionName)] IAsyncCollector <InterventionEntity> interventions, ILogger log) { var results = new List <ValidationResult>(); if (!Validator.TryValidateObject(intervention, new ValidationContext(intervention, null, null), results)) { var errorList = new List <string>(); foreach (var error in results) { errorList.Add(error.ErrorMessage); } string json = JsonConvert.SerializeObject(errorList); return(new BadRequestObjectResult(json)); } Address convertedGeoAddress = new Address(); try { // retry should be added convertedGeoAddress = await _addressConverter.ConvertToGeoAddress(intervention.Address); } catch (Exception e) { log.LogError(e, "error"); return(new StatusCodeResult(StatusCodes.Status500InternalServerError)); } InterventionEntity interventionEntity = new InterventionEntity() { Email = intervention.Email, City = intervention.City, Street = intervention.Street, StreetNumber = intervention.StreetNumber, CreationDate = DateTime.UtcNow, ModificationDate = DateTime.UtcNow, Description = intervention.Description, FullName = intervention.FullName, PhoneNumber = intervention.PhoneNumber, Status = (int)intervention.Status, GeoLat = convertedGeoAddress.Latitude, GeoLng = convertedGeoAddress.Lognitude, PartitionKey = GeoHash.Encode(convertedGeoAddress.Latitude, convertedGeoAddress.Lognitude, Config.GeoHashPrecision) }; await interventions.AddAsync(interventionEntity); await interventions.FlushAsync(); return(new JsonResult(new { id = interventionEntity.RowKey })); }
// geohash.org public string GetPathAsGeoHash() { TrackingContext context = new TrackingContext(); var locations = context.Trackings .Where(t => t.ValidGPS) .Select(t => t.Location) .ToList(); var path = locations.Select(l => GeoHash.Encode(l.Latitude, l.Longitude)); return(string.Join(",", path)); }
private async Task <GeoLocation?> GetGeoLocationDataAsync( ExifProfile exifProfile, CancellationToken cancellationToken) { IExifValue <Rational[]> lat = exifProfile.GetValue(ExifTag.GPSLatitude); IExifValue <Rational[]> lon = exifProfile.GetValue(ExifTag.GPSLongitude); IExifValue <string> latRef = exifProfile.GetValue(ExifTag.GPSLatitudeRef); IExifValue <string> lonRef = exifProfile.GetValue(ExifTag.GPSLongitudeRef); IExifValue <Rational> alt = exifProfile.GetValue(ExifTag.GPSAltitude); if (lat != null) { var gps = new GeoLocation() { Type = "gps", Point = new GeoPoint() }; var latValue = ConvertToLocation(lat.Value); var lonValue = ConvertToLocation(lon.Value); if (latRef.Value.ToString() == "S") { latValue = latValue * -1; } if (lonRef.Value.ToString() == "W") { lonValue = lonValue * -1; } gps.Point = GeoPoint.Create(latValue, lonValue); if (alt != null) { var dominator = (int)alt.Value.Denominator; if (dominator == 0) { dominator = 1; } gps.Altitude = (int)alt.Value.Numerator / dominator; } gps.GeoHash = GeoHash.Encode(gps.Point.Coordinates[1], gps.Point.Coordinates[0]); gps.Address = await _geoDecoderService.DecodeAsync( gps.Point.Coordinates[1], gps.Point.Coordinates[0], cancellationToken); return(gps); } return(null); }
public static List <Tuple <string, string> > GeohashQueries(Geolocation center, double radius) { GeopointService.ValidateGeopoint(center); var queryBits = Math.Max(1, BoundingBoxBits(center, radius)); var geohashPrecision = queryBits / BITS_PER_CHAR; var coordinates = BoundingBoxCoordinates(center, radius); var queries = coordinates.Select((coordinate) => { return(GeohashQuery(GeoHash.Encode(coordinate.Lat, coordinate.Lon, geohashPrecision), queryBits)); }); // remove duplicates return(queries.ToHashSet().ToList()); }
// geohash.org public string GetPathAsGeoHash() { IList <string> path = new List <string>(); using (var context = new TrackingContext()) { var locations = context.Trackings.Where(t => t.ValidGPS).Select(t => t.Location).ToList(); foreach (Location location in locations) { path.Add(GeoHash.Encode(location.Latitude, location.Longitude)); } return(string.Join(",", path)); } }
public static string GetGeoHash(ChannelData channelData) { if (channelData.Message != null && channelData.Message.Attachments != null) { foreach (var attachment in channelData.Message.Attachments) { if (attachment.Type == "location") { FacebookChannelData.Coordinates coordinates = attachment.Payload.Coordinates; string geoHash = GeoHash.Encode(coordinates.Lat, coordinates.Long); return(geoHash); } } } return(null); }
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); }
private async Task <GeoLocation?> GetGpsLocation(IReadOnlyList <MetadataEx.Directory> meta, CancellationToken cancellationToken) { var geo = GetMetadataValue(meta, "QuickTime Metadata Header/GPS Location"); if (geo != null) { var regex = new Regex(@"(\+|\-)(\d{2,}\.\d{2,})"); MatchCollection?matches = regex.Matches(geo); var coordintates = new List <double>(); foreach (string?value in matches.Select(x => x?.ToString())) { double coordValue; if (double.TryParse(value, out coordValue)) { coordintates.Add(coordValue); } } if (coordintates.Count == 2) { var gps = new GeoLocation() { Type = "gps", Point = GeoPoint.Create(coordintates[0], coordintates[1]) }; try { gps.GeoHash = GeoHash.Encode(gps.Point.Coordinates[1], gps.Point.Coordinates[0]); gps.Address = await _geoDecoderService.DecodeAsync( coordintates[0], coordintates[1], cancellationToken); return(gps); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } return(null); }
private async Task <MediaOperationCompletedMessage> UpdateMetadataAsync( Guid id, DateTimeOffset?dateTaken, UpdateMedataGeoLocation?geoLocation, CancellationToken cancellationToken) { MediaOperationCompletedMessage msg = new MediaOperationCompletedMessage { Type = MediaOperationType.UpdateMetadata, MediaId = id, }; try { if (dateTaken.HasValue) { await _mediaService.UpdateDateTakenAsync(id, dateTaken, cancellationToken); } if (geoLocation is { } geo&& geo.Latitude.HasValue && geo.Longitude.HasValue) { Media media = await _mediaStore.GetByIdAsync(id, cancellationToken); media.GeoLocation = new GeoLocation { Point = GeoPoint.Create(geo.Latitude.Value, geo.Longitude.Value), Type = "User", GeoHash = GeoHash.Encode(geo.Latitude.Value, geo.Longitude.Value), Address = GetAddress(geoLocation) }; await _mediaStore.UpdateAsync(media, cancellationToken); } msg.IsSuccess = true; } catch (Exception ex) { msg.IsSuccess = false; msg.Message = ex.Message; } return(msg); }
public void HandleLocationEvent(GameEventData data) { var locationEvent = JsonConvert.DeserializeObject <LocationEvent>(data.Data); var geoHash = GeoHash.Encode(locationEvent.Latitude, locationEvent.Longitude); locationEvent.Geohash = geoHash; //TODO: Optimize this so we don't serialize back to JSON first and then to CSV data.Data = JsonConvert.SerializeObject( locationEvent, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); var serializedGameEvent = data.ToCsv("gameSessionId", "longitude", "latitude", "geohash"); _blobOutputManager.QueueAppendToBlob(data, serializedGameEvent); _eventHubOutputManager.SendToEventHub(data, serializedGameEvent); }
public async Task <Place> UpdatePlace(Place place, string user) { var old = await this.GetPlace(place.Id); if (!old.Owners.Select(o => o.Id).Contains(user)) { throw new GrooverAuthException("Current User has no permissions to update this place"); } var fullUser = await this.userService.GetUser(user); var playlistNeedsUpdate = false; var dbFormat = PlaylistService.ParseSpotifyPlaylist(place.MainPlaylist.Id); if (old.MainPlaylist?.Id != dbFormat || (!old.MainPlaylist?.Songs?.Any() ?? true)) { old.MainPlaylist = await this.playlistService.GetPlaylistFromSpotify(place.MainPlaylist.Id, fullUser.CurrentToken); playlistNeedsUpdate = true; } old.DisplayName = place.DisplayName; old.Location = place.Location; old.Address = place.Address; old.PendingReview = !old.Approved; old.Phone = place.Phone; old.Timetables = place.Timetables; old.Geohash = GeoHash.Encode(old.Location.Latitude, old.Location.Longitude); var converted = _mapper.ToDbEntity(old); var dbResult = await _dao.UpdatePlace(converted); if (playlistNeedsUpdate) { await playlistService.SetPlaylist(old.Id, old.MainPlaylist, true); } return(_mapper.ToApplicationEntity(dbResult)); }
public GeonamesCityEntity FindClosestCityForCoordinates(double latitude, double longitude) { var coordinatesGeohash = GeoHash.Encode(latitude, longitude, numberOfChars: 3); // 3 = ±78km var neighborGeohashes = GeoHash.Neighbors(coordinatesGeohash); var targetGeohashes = new HashSet <string>(neighborGeohashes); targetGeohashes.Add(coordinatesGeohash); var targetCities = new List <GeonamesCityEntity>(); foreach (var targetGeohash in targetGeohashes) { List <GeonamesCityEntity> citiesInTargetGeohash; if (this.GeohashesToCities.TryGetValue(targetGeohash, out citiesInTargetGeohash)) { targetCities.AddRange(citiesInTargetGeohash); } } GeonamesCityEntity closestCity = null; double closestCityDistance = double.MaxValue; foreach (var targetCity in targetCities) { var distance = DistanceHelper.Distance(targetCity.Latitude, targetCity.Longitude, latitude, longitude, DistanceUnit.Kilometer); if (distance <= 50 && distance < closestCityDistance) { closestCity = targetCity; closestCityDistance = distance; } } return(closestCity); }
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(); }
/// <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()); }