public List <string> GetListOfZipCodes(ProfileListFilterModel filter) { var result = new List <string>(); //var filterDefinition = Builders<LocationLookup>.Filter.Ne(p=>p.Supervisor, null); if (!string.IsNullOrEmpty(filter.mfz)) { var location = GetLongLat(filter.mfz); var point = new GeoJson2DGeographicCoordinates(location.lg, location.lt); var pnt = new GeoJsonPoint <GeoJson2DGeographicCoordinates>(point); //Expression<Func<Profile,Profile>> fieldExpression = p => p.Supervisor.Addresses.Where(_ => _.Type.Equals("Primary")); FieldDefinition <LocationLookup, string> field = "LocationLookup.Location"; //_context.Locations.Collection.Indexes.CreateOne(Builders<LocationLookup>.IndexKeys.Geo2DSphere(field)); //var filterDefinition = Builders<LocationLookup>.Filter.NearSphere(p => p.Location, pnt, filter.mfd*10); var filterDefinition = Builders <LocationLookup> .Filter.NearSphere(field, pnt, filter.mfd *500); var foo = _context.Locations.Collection.Find(filterDefinition); //var s = ""; } return(result); }
private void SetPosition(double lon, double lat) { Latitude = lat; Longitude = lon; Location = new GeoJsonPoint <GeoJson2DGeographicCoordinates>( new GeoJson2DGeographicCoordinates(lon, lat)); }
public static double DegreeBearing(GeoJsonPoint <GeoJson2DGeographicCoordinates> p1, GeoJsonPoint <GeoJson2DGeographicCoordinates> p2) { var dLon = ToRad(p2.Coordinates.Longitude - p1.Coordinates.Longitude); var dPhi = Math.Log(Math.Tan(ToRad(p2.Coordinates.Latitude) / 2.0d + Math.PI / 4.0d) / Math.Tan(ToRad(p1.Coordinates.Latitude) / 2.0d + Math.PI / 4.0d)); if (Math.Abs(dLon) > Math.PI) { dLon = dLon > 0 ? -(2.0d * Math.PI - dLon) : (2.0d * Math.PI + dLon); } return(ToBearing(Math.Atan2(dLon, dPhi))); double ToRad(double degrees) { return(degrees * (Math.PI / 180.0d)); } double ToDegrees(double radians) { return(radians * 180.0d / Math.PI); } double ToBearing(double radians) { return((ToDegrees(radians) + 360.0d) % 360.0d); } }
public async Task <UserDto> CreateUser(string name, GeoJsonPoint <GeoJson2DGeographicCoordinates> location) { var userId = (int)await this._currentLocations.CountDocumentsAsync(FilterDefinition <UserDto> .Empty) + 1; var user = new UserDto { UserId = userId, Name = name, LastKnownLocation = location }; await this._currentLocations.InsertOneAsync(user); await this._historicalLocations.InsertOneAsync(new UserHistoryDto { UserId = userId, Name = name, LocationHistory = new GeoJsonMultiPoint <GeoJson2DGeographicCoordinates>( new GeoJsonMultiPointCoordinates <GeoJson2DGeographicCoordinates>( new List <GeoJson2DGeographicCoordinates> { location.Coordinates })) }); return(user); }
public static double DistanceTo(this GeoJsonPoint <GeoJson2DGeographicCoordinates> startPoint, GeoJsonPoint <GeoJson2DGeographicCoordinates> destination) { if (startPoint?.Coordinates is null || destination?.Coordinates is null) { return(double.NaN); } double startLatitude = startPoint.Coordinates.Latitude; double startLongitude = startPoint.Coordinates.Longitude; double destinationLatitude = destination.Coordinates.Latitude; double destinationLongitude = destination.Coordinates.Longitude; double fromPointRadianLatitude = ConvertToRadians(startLatitude);; double toPointRadianLatitude = ConvertToRadians(destinationLatitude); double df = ConvertToRadians(startLatitude - destinationLatitude); double dl = ConvertToRadians(startLongitude - destinationLongitude); double a = Math.Sin(df / 2) * Math.Sin(df / 2) + Math.Cos(fromPointRadianLatitude) * Math.Cos(toPointRadianLatitude) * Math.Sin(dl / 2) * Math.Sin(dl / 2); double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a)); return(R * c); }
public double[] GetWeights( double minArea, double maxArea, double minPricePerYear, double maxPricePerYear, double minDistanceTowardsMetroEntrance, double maxDistanceTowardsMetroEntrance, double minDistanceTowardsStation, double maxDistanceTowardsStation, double minDistanceTowardsCenter, double maxDistanceTowardsCenter, double minDegreeBearingTowardsCenter, double maxDegreeBearingTowardsCenter, GeoJsonPoint <GeoJson2DGeographicCoordinates> moscowCenter) { var weights = new List <double> { (Area - minArea) / (maxArea - minArea), (PricePerYear - minPricePerYear) / (maxPricePerYear - minPricePerYear), (DistanceTowardsMetroEntrance - minDistanceTowardsMetroEntrance) / (maxDistanceTowardsMetroEntrance - minDistanceTowardsMetroEntrance), (DistanceTowardsStation - minDistanceTowardsStation) / (maxDistanceTowardsStation - minDistanceTowardsStation), (GeoHelpers.CalcDistance(GeoPoint, moscowCenter) - minDistanceTowardsCenter) / (maxDistanceTowardsCenter - minDistanceTowardsCenter), (GeoHelpers.DegreeBearing(GeoPoint, moscowCenter) - minDegreeBearingTowardsCenter) / (maxDegreeBearingTowardsCenter - minDegreeBearingTowardsCenter) }; return(weights.ToArray()); }
public async Task <Response <List <GasStation> > > GetGasStationsByLocationAsync(GetLocationDto location) { var response = Response <List <GasStation> > .Create(); if (location is null) { response.WithBusinessError("Coordinates are invalid"); } var maxDistance = Settings.GeocoddingSettings.BaseRadius; var customerLocation = new GeoJsonPoint <GeoJson2DGeographicCoordinates>(new GeoJson2DGeographicCoordinates(location.Longitude, location.Latitude)); var gasStations = new List <GasStation>(); while (!gasStations.Any() && maxDistance <= 15000) { var filter = Builders <GasStation> .Filter.Near(x => x.Address.Location, customerLocation, maxDistance) & Builders <GasStation> .Filter.Eq(x => x.DeletedAt, null); gasStations = await Collection.FindAsync(filter) .GetAwaiter() .GetResult() .ToListAsync(); maxDistance += 5000; } return(gasStations); }
static async Task MainAsync(string[] args) { var conexaoAeroporto = new conectandoMongoDBGeo(); var listaAeroportos = await conexaoAeroporto.Airports.Find(new BsonDocument()).ToListAsync(); Console.WriteLine("Listando todos os aeroportos"); foreach (var doc in listaAeroportos) { Console.WriteLine(doc.name); } Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine(""); var ponto = new GeoJson2DGeographicCoordinates(-118.325258, 34.103212); var localizacao = new GeoJsonPoint <GeoJson2DGeographicCoordinates>(ponto); var construtor = Builders <Aeroporto> .Filter; var filtro_builder = construtor.NearSphere(x => x.loc, localizacao, 100000); listaAeroportos = await conexaoAeroporto.Airports.Find(filtro_builder).ToListAsync(); Console.WriteLine("Listando todos os aeroportos proximo de mim"); foreach (var doc in listaAeroportos) { Console.WriteLine(doc.name); } Console.WriteLine(""); }
private static FilterDefinition <TResponse> GetFilters <TResponse>(DateTime fromDate, DateTime toDate, double userLat, double userLng, double maxDistanceKm, string locationName, string freeText) { var filter = Builders <TResponse> .Filter.Ne("Type", "Övrigt") & Builders <TResponse> .Filter.Gte("UtcDateTime", new BsonDateTime(fromDate.Date)) & Builders <TResponse> .Filter.Lt("UtcDateTime", new BsonDateTime(toDate.Date.AddDays(1))); if (locationName != null && locationName.Length > 2) { filter &= Builders <TResponse> .Filter.Regex("Location.Name", new BsonRegularExpression(".*" + locationName + ".*", "i")); } if (freeText != null && freeText.Length > 2) { filter &= Builders <TResponse> .Filter.Regex("Summary", new BsonRegularExpression(".*" + freeText + ".*", "i")); } if (userLat > 0 && userLng > 0) { var gp = new GeoJsonPoint <GeoJson2DGeographicCoordinates>(new GeoJson2DGeographicCoordinates(userLat, userLng)); filter &= Builders <TResponse> .Filter.Near("Geo", gp, maxDistanceKm * 1000); } return(filter); }
/// <summary> /// Updates store location /// </summary> /// <param name="id">The document id of store to update</param> /// <param name="location">The location to update</param> /// <exception cref="ArgumentException">Throws when id is empty</exception> /// <exception cref="ArgumentNullException">Throws when location is null</exception> /// <returns>Result of update</returns> public async Task <UpdateResult> UpdateStoreLocation(string id, GeoJsonPoint <GeoJson2DGeographicCoordinates> location) { #region Validations if (string.IsNullOrWhiteSpace(id)) { throw new ArgumentException("MongoDB id is empty", nameof(id)); } if (location is null) { throw new ArgumentNullException(nameof(location)); } #endregion // Create filter FilterDefinition <Store> filter = Builders <Store> .Filter.Eq(store => store.ID, id); // Create update query UpdateDefinition <Store> update = Builders <Store> .Update.Set(store => store.Location, location); return(await _stores.UpdateOneAsync(filter, update)); }
public void ToJson1() { GeoJsonPoint point = new GeoJsonPoint(9.536067, 55.708116, 1.125); string json = point.ToJson(Formatting.None); Assert.AreEqual(Json1, json); }
public static CoordinateModel ToCoordinateModel(this GeoJsonPoint <GeoJson2DGeographicCoordinates> point) { return(new CoordinateModel { Latitude = point.Coordinates.Latitude, Longitude = point.Coordinates.Longitude }); }
public async Task UpdateorAddUserLocationAsync(int userId, GeoJsonPoint <GeoJson2DGeographicCoordinates> location) { await this._currentLocations.FindOneAndUpdateAsync(u => u.UserId == userId, Builders <UserDto> .Update.Set("location", location)); await this._historicalLocations.FindOneAndUpdateAsync(u => u.UserId == userId, Builders <UserHistoryDto> .Update.Push("location.coordinates", location.Coordinates)); }
public City(string cityName, string lng, string lat) { CityName = cityName; Long = lng; Lat = lat; Location = new GeoJsonPoint <GeoJson2DGeographicCoordinates>( new GeoJson2DGeographicCoordinates(double.Parse(Lat.Replace(",", "."), CultureInfo.InvariantCulture), double.Parse(Long.Replace(",", "."), CultureInfo.InvariantCulture))); }
public PotatoFeed(FeedDto other) { Name = other.Name; FeedId = other.FeedId; Location = new GeoJsonPoint <GeoJson2DGeographicCoordinates>( new GeoJson2DGeographicCoordinates(other.Location.Longitude, other.Location.Latitude)); }
public PotatoFeed(FeedDto other) { Name = other.Name; Id = other.Id; Location = new GeoJsonPoint<GeoJson2DGeographicCoordinates>( new GeoJson2DGeographicCoordinates(other.Location.Longitude, other.Location.Latitude)); }
public Potato(KnockDto other) { Id = other.Id; FeedId = other.FeedId; Content = other.Content; Message = other.Message; Location = other.Location; PotatoLoc = new GeoJsonPoint<GeoJson2DGeographicCoordinates>(new GeoJson2DGeographicCoordinates(other.Location.Longitude, other.Location.Latitude)); }
private void AssertCoordinates(ContactModel contactModel, GeoJsonPoint <GeoJson2DGeographicCoordinates> location) { if (contactModel == null) { return; } Assert.AreEqual(contactModel.Coordinates, location.Coordinates.Latitude.ToString(CultureInfo.InvariantCulture) + CoordSeparator + location.Coordinates.Longitude.ToString(CultureInfo.InvariantCulture)); }
private List<Police> GetPolice(double longitude, double latitude) { double radius = 8046; var policeCollection = GetDatabase().GetCollection<Police>("Police"); var centerPoint = new GeoJsonPoint<GeoJson2DGeographicCoordinates>(new GeoJson2DGeographicCoordinates(longitude, latitude)); var query = Query.Near("Location", centerPoint, radius, true); var queryResolved = policeCollection.Find(query); return queryResolved.ToList<Police>(); }
public async Task WebAPI_StoreRepository_UpdateStoreLocation_Should_Update_For_Each_Store() { #region Arrange IEnumerable <Store> allStores = await _storeRepository.GetStoresAsync(); ILocationService locationService = new LocationService(); #endregion #region Act // Validate stores exists if (allStores.IsNullOrEmpty()) { throw new Exception("Stores are empty"); } foreach (Store store in allStores) { // Continue when store already has location if (store.Location != null) { continue; } // Continue when city or address are empty if (string.IsNullOrWhiteSpace(store.City) || string.IsNullOrWhiteSpace(store.Address)) { continue; } // Fetch location for store ForwardGeocodingResponse locationResponse = await locationService.GetLocationByAddress(store.City, store.Address); // Continue when results are empty if (locationResponse.Results.IsNullOrEmpty()) { continue; } ForwardGeocodingResult result = locationResponse.Results.First(); var geoPointToUpdate = new GeoJsonPoint <GeoJson2DGeographicCoordinates>( new GeoJson2DGeographicCoordinates( longitude: result.Geometry.Lng, latitude: result.Geometry.Lat)); await _storeRepository.UpdateStoreLocation(store.ID, geoPointToUpdate); } #endregion // No assert }
public async Task <IList <T> > GetIntersects(Point point, string collectionName, Expression <Func <T, object> > field) { var repository = new MongoRepository <T>(_dbSettings, collectionName); var geometry = new GeoJsonPoint <GeoJson2DGeographicCoordinates>(new GeoJson2DGeographicCoordinates(point.coordinates[0], point.coordinates[1])); var filter = Builders <T> .Filter.GeoIntersects(field, geometry); return(await repository.GetCollection().Find(filter).ToListAsync()); }
public void Parse1() { GeoJsonPoint point = GeoJsonPoint.Parse(Json1); Assert.AreEqual(GeoJsonType.Point, point.Type); Assert.AreEqual(9.536067, point.X); Assert.AreEqual(55.708116, point.Y); Assert.AreEqual(1.125, point.Altitude); }
public void Deserialize1() { GeoJsonPoint point = JsonConvert.DeserializeObject <GeoJsonPoint>(Json1); Assert.AreEqual(GeoJsonType.Point, point.Type); Assert.AreEqual(9.536067, point.X); Assert.AreEqual(55.708116, point.Y); Assert.AreEqual(1.125, point.Altitude); }
public PotatoKnock(KnockDto other) { this._id = other.Id; FeedId = other.FeedId; Content = other.Content; Message = other.Message; Location = new GeoJsonPoint <GeoJson2DGeographicCoordinates>( new GeoJson2DGeographicCoordinates(other.Location?.Longitude ?? 0.0, other.Location?.Latitude ?? 0.0)); }
public static FilterDefinition <VenueLocation> CreateGeoJsonFilter(this double searchRadiusMiles, double latitude, double longitude) { GeoJsonPoint <GeoJson2DGeographicCoordinates> geoPoint = new GeoJsonPoint <GeoJson2DGeographicCoordinates>(new GeoJson2DGeographicCoordinates(longitude, latitude)); double searchRadiusInMeters = searchRadiusMiles * 1609.344; //1609.344 Meters = 1 Mile FilterDefinition <VenueLocation> filter = Builders <VenueLocation> .Filter.Near("location", geoPoint, maxDistance : searchRadiusInMeters); return(filter); }
private List <FireStation> GetFireStations(double longitude, double latitude) { double radius = 8046; var fireCollection = GetDatabase().GetCollection <FireStation>("FireStations"); var centerPoint = new GeoJsonPoint <GeoJson2DGeographicCoordinates>(new GeoJson2DGeographicCoordinates(longitude, latitude)); var query = Query.Near("Location", centerPoint, radius, true); var queryResolved = fireCollection.Find(query); return(queryResolved.ToList <FireStation>()); }
public void Constructor1() { GeoJsonPoint point = new GeoJsonPoint(); Assert.AreEqual(GeoJsonType.Point, point.Type); Assert.AreEqual(0, point.X); Assert.AreEqual(0, point.Y); Assert.AreEqual(0, point.Altitude); }
private void TestRoundTrip <TCoordinates>(string expected, GeoJsonPoint <TCoordinates> point) where TCoordinates : GeoJsonCoordinates { var json = point.ToJson(); Assert.AreEqual(expected, json); var rehydrated = BsonSerializer.Deserialize <GeoJsonPoint <TCoordinates> >(json); Assert.AreEqual(expected, rehydrated.ToJson()); }
public void Constructor3() { GeoJsonPoint point = new GeoJsonPoint(9.536067, 55.708116, 1.125); Assert.AreEqual(GeoJsonType.Point, point.Type); Assert.AreEqual(9.536067, point.X); Assert.AreEqual(55.708116, point.Y); Assert.AreEqual(1.125, point.Altitude); }
/// <summary> /// Parses the specified <paramref name="json"/> object into an instance deriving from <see cref="GeoJsonObject"/>. /// /// As the GeoJSON format specified the type of a /// </summary> /// <param name="json">The JSON object.</param> /// <returns>An instance that derives from <see cref="GeoJsonObject"/>.</returns> private static GeoJsonObject Parse(JObject json) { if (json == null) { return(null); } // Get the value of the "type" property string type = json.GetString("type"); if (string.IsNullOrWhiteSpace(type)) { throw new GeoJsonParseException("The JSON object doesn't specify a type", json); } // Parse the type into an enum if (EnumUtils.TryParseEnum(type, out GeoJsonType result) == false) { throw new GeoJsonParseException($"Unknown type {type}", json); } switch (result) { case GeoJsonType.Feature: return(GeoJsonFeature.Parse(json)); case GeoJsonType.FeatureCollection: return(GeoJsonFeatureCollection.Parse(json)); case GeoJsonType.Point: return(GeoJsonPoint.Parse(json)); case GeoJsonType.LineString: return(GeoJsonLineString.Parse(json)); case GeoJsonType.Polygon: return(GeoJsonPolygon.Parse(json)); case GeoJsonType.MultiPoint: return(GeoJsonMultiPoint.Parse(json)); //case GeoJsonType.MultiLineString: // return GeoJsonMultiLineString.Parse(obj); case GeoJsonType.MultiPolygon: return(GeoJsonMultiPolygon.Parse(json)); case GeoJsonType.GeometryCollection: return(GeoJsonGeometryCollection.Parse(json)); default: throw new GeoJsonParseException($"Unknown type {type}", json); } }
public static double DistanceBetween(GeoJsonPoint <GeoJson3DGeographicCoordinates> position1, GeoJsonPoint <GeoJson3DGeographicCoordinates> position2) { if (position1 == null || position2 == null) { return(double.NegativeInfinity); } var location1 = new GeoCoordinate(position1.Coordinates.Latitude, position1.Coordinates.Longitude); var location2 = new GeoCoordinate(position2.Coordinates.Latitude, position2.Coordinates.Longitude); return(location1.GetDistanceTo(location2)); }
private static void WriteGeoJsonPoint(GeoJsonPoint <GeoJson2DGeographicCoordinates> point, JsonWriter writer) { writer.WriteStartObject(); writer.WritePropertyName("type"); writer.WriteValue("Point"); writer.WritePropertyName("coordinates"); writer.WriteStartArray(); writer.WriteValue(point.Coordinates.Longitude); writer.WriteValue(point.Coordinates.Latitude); writer.WriteEndArray(); writer.WriteEndObject(); }
private static void AddPoint(SqlGeometryBuilder builder, GeoJsonPoint point, bool isLongitudeFirst) { builder.BeginGeometry(OpenGisGeometryType.Point); var temporaryPoint = IRI.Msh.Common.Primitives.Point.Parse(point.Coordinates, isLongitudeFirst); builder.BeginFigure(temporaryPoint.X, temporaryPoint.Y); builder.EndFigure(); builder.EndGeometry(); }
internal static IMongoQuery GetGeoIntersect(string coords) { const double MetersToEarthDegrees = 111.12e3; if (String.IsNullOrEmpty(coords)) { return Query.Null; } string[] points = coords.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (points.Length == 0) { return Query.Null; } GeoJsonGeometry<GeoJson2DGeographicCoordinates> geometry = null; if (points.Length == 1) { #region Point string[] xyr = coords.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); // Point with radius if (xyr.Length == 3) { double latitude = Double.Parse(xyr[0], NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign | NumberStyles.Number, CultureInfo.InvariantCulture); double longitude = Double.Parse(xyr[1], NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign | NumberStyles.Number, CultureInfo.InvariantCulture); double radius = Double.Parse(xyr[2], NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign | NumberStyles.Number, CultureInfo.InvariantCulture); if (radius <= 0) radius = 1; var polyPoints = GetPolygon(longitude, latitude, radius / MetersToEarthDegrees); var linearRing = GeoJson.LinearRingCoordinates(polyPoints.ToArray()); geometry = new GeoJsonPolygon<GeoJson2DGeographicCoordinates>(new GeoJsonPolygonCoordinates<GeoJson2DGeographicCoordinates>(linearRing)); } else if (xyr.Length == 2) { double latitude = Double.Parse(xyr[0], NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign | NumberStyles.Number, CultureInfo.InvariantCulture); double longitude = Double.Parse(xyr[1], NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign | NumberStyles.Number, CultureInfo.InvariantCulture); geometry = new GeoJsonPoint<GeoJson2DGeographicCoordinates>(new GeoJson2DGeographicCoordinates(longitude, latitude)); } #endregion } else { #region Polygon double[,] p = new double[points.Length, 2]; List<GeoJson2DGeographicCoordinates> polyPoints = new List<GeoJson2DGeographicCoordinates>(); //polygon for (int k = 0; k < points.Length; k++) { string[] xy = points[k].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); var lat = Double.Parse(xy[0], NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign | NumberStyles.Number, CultureInfo.InvariantCulture); var lon = Double.Parse(xy[1], NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign | NumberStyles.Number, CultureInfo.InvariantCulture); polyPoints.Add(new GeoJson2DGeographicCoordinates(lon, lat)); } if (polyPoints.First().Latitude != polyPoints.Last().Latitude || polyPoints.First().Longitude != polyPoints.Last().Longitude) polyPoints.Add(polyPoints.First()); var linearRing = GeoJson.LinearRingCoordinates(polyPoints.ToArray()); geometry = new GeoJsonPolygon<GeoJson2DGeographicCoordinates>(new GeoJsonPolygonCoordinates<GeoJson2DGeographicCoordinates>(linearRing)); #endregion } if (geometry != null) return Query.GeoIntersects("location.GeoJson", geometry); else return Query.Null; }