// GET: api/FindNearByProperties - iOS APP P4U public IEnumerable <NearByAddresses> GetFindNearByProperties(double longitude, double latitude) { DbGeography searchLocation = DbGeography.FromText(String.Format("POINT({0} {1})", longitude, latitude)); return ((from location in db.Addresses where longitude != null && latitude != null select new NearByAddresses { ID = location.ID, Name = location.Name, Number = location.Number, Floor = location.Floor, AreaName = location.AreaName, Block = location.Block, Street = location.Street, City = location.City, State = location.State, Country = location.Country, PostalCode = location.PostalCode, ZipCode = location.ZipCode, Latitude = location.Latitude, Longitude = location.Longitude, Distance = searchLocation.Distance( DbGeography.FromText("POINT(" + location.Longitude + " " + location.Latitude + ")")) }) .OrderBy(location => location.Distance).ToList()); }
public static DbGeography PerformMovement(DbGeography current, DateTime lastMovement, Orders orders, int speed) { DbGeography newLoc = null; double newLat = 0; double newLon = 0; var diffInSeconds = (DateTime.Now - lastMovement).TotalSeconds; var distance = (double)speed * diffInSeconds; var axisDistance = Math.Sqrt(Math.Pow(distance, 2) / 2); var totalAxisDistance = Math.Sqrt(Math.Pow(current.Distance(orders.location).Value, 2) / 2); if (totalAxisDistance < axisDistance) { axisDistance = totalAxisDistance; } double toMove = (double)((decimal)axisDistance / (1852m * 60m)); double checkDiff = (double)(2m / (1852m * 60m)); if (Math.Abs(orders.location.Latitude.Value - current.Latitude.Value) < checkDiff) { newLat = current.Latitude.Value; } else { if (orders.location.Latitude.Value > current.Latitude.Value) { newLat = current.Latitude.Value + toMove; } else { newLat = current.Latitude.Value - toMove; } } if (Math.Abs(orders.location.Longitude.Value - current.Longitude.Value) < checkDiff) { newLon = current.Longitude.Value; } else { if (orders.location.Longitude.Value > current.Longitude.Value) { newLon = current.Longitude.Value + toMove; } else { newLon = current.Longitude.Value - toMove; } } var point = string.Format("POINT({1} {0})", newLat, newLon); newLoc = DbGeography.FromText(point); return(newLoc); }
/// <summary> /// поиск филиалов по географическим координатам /// </summary> /// <param name="location"></param> /// <returns></returns> public List <FuzzySearchResult> SearchOfficeByGeocode(DbGeography location) { var result = new List <FuzzySearchResult>(); foreach (var item in mfcDataOfBot.Offices.Where(x => x.Geo != null)) { var dist = location.Distance(item.Geo); if (dist < 500) { result.Add(new FuzzySearchResult(item.DisplayName, item.AisMFCID, (double)dist, 0.5F, FuzzySearchResultDataType.Customer)); } } return(result); }
public List <FuzzySearchResult> SearchCustomerByGeocode(DbGeography location, List <DBasesCustomersHolder> customers) { var res = new List <FuzzySearchResult>(); foreach (var db in customers) { foreach (var item in db.Customers) { var dist = location.Distance(item.Location); if (dist < 500) { res.Add(new FuzzySearchResult(item.Name, item.CustomerID, db.DBaseID + item.CustomerID.ToString(), item.LocaleCity, (double)dist, 0.5F, FuzzySearchResultDataType.Customer, "")); } } } return(res); }
public async Task <List <ArmedTrapResult> > ListArmedTraps(float latitude, float longitude, string userId) { List <ArmedTrapResult> response = new List <ArmedTrapResult>(); DbGeography searchLocation = DbGeography.FromText(string.Format("POINT({0} {1})", longitude.ToString(CultureInfo.InvariantCulture), latitude.ToString(CultureInfo.InvariantCulture))); var armedTraps = await (from armedTrap in AppRepository.EntitiesContext.ArmedTraps where !armedTrap.Disarmed && armedTrap.User.Id != new Guid(userId) select new { Id = armedTrap.Id, Date = armedTrap.Date, UserId = armedTrap.User.Id, Latitude = armedTrap.Latitude, Longitude = armedTrap.Longitude, NameKey = armedTrap.NameKey, Distance = searchLocation.Distance( DbGeography.FromText("POINT(" + armedTrap.Longitude + " " + armedTrap.Latitude + ")")) }) .OrderBy(a => a.Distance) .Where(a => a.Distance < 500) .ToListAsync(); if (armedTraps != null) { foreach (var armedTrap in armedTraps) { ArmedTrapResult armedTrapResponse = new ArmedTrapResult(); armedTrapResponse.Date = armedTrap.Date; armedTrapResponse.Id = armedTrap.Id.ToString(); armedTrapResponse.Latitude = armedTrap.Latitude; armedTrapResponse.Longitude = armedTrap.Longitude; armedTrapResponse.NameKey = armedTrap.NameKey; armedTrapResponse.UserId = armedTrap.UserId.ToString(); response.Add(armedTrapResponse); } } return(response); }
public static double CalculateDistance(DbGeography pointOne, DbGeography pointTwo) { return(pointOne.Distance(pointTwo).GetValueOrDefault()); }
private static DateTime UnixEpoch = new DateTime(1969, 12, 31, 17, 0, 0); // Jan 1, 1970 UTC in local time public ActionResult NodeCheckinData(string id) { if (!System.Text.RegularExpressions.Regex.IsMatch(id, "^[a-zA-Z\\-0-9]+$")) { return(new ContentResult { ContentType = "text/plain", Content = "Bad id" }); } if (Request.Files.Count == 0) { return new ContentResult { Content = "no file", ContentType = "text/plain" } } ; var hpf = Request.Files[0] as System.Web.HttpPostedFileBase; XDocument doc = XDocument.Load(hpf.InputStream, LoadOptions.PreserveWhitespace); using (var mnc = new MeshNodeEntities()) { var locElement = doc.Element("MeshReport").Element("Location").Element("Last"); string[] loc = locElement.Attribute("Position").Value.Split(','); var status = new MeshNodeStatus { Location = (loc.Length > 1) ? DbGeography.PointFromText(string.Format("POINT({0} {1})", loc[1], loc[0]), GeographyServices.SRID) : null, Time = DateTime.Parse(doc.Element("MeshReport").Attribute("time").Value), Name = id, IPAddr = doc.ElementOrDefault("Modem").ElementOrDefault("IP").SafeValue() }; try { float uptime; if (float.TryParse(doc.ElementOrDefault("Uptime").SafeValue(), out uptime)) { status.Uptime = uptime; } var volts = doc.ElementOrDefault("Voltages").SafeValue(); if (!string.IsNullOrWhiteSpace(volts)) { var voltParts = volts.Split(' '); status.BatteryVolts = float.Parse(voltParts[0]); status.HouseVolts = float.Parse(voltParts[1]); status.AlternatorVolts = float.Parse(voltParts[2]); } } catch (Exception) { // eat } foreach (var existing in mnc.Checkins.Where(f => f.Name == id)) { mnc.Checkins.Remove(existing); } mnc.Checkins.Add(status); mnc.SaveChanges(); string track = doc.ElementOrDefault("Location").ElementOrDefault("History").SafeValue(); if (!string.IsNullOrWhiteSpace(track)) { string[] trackParts = track.Trim().Split('\n'); DateTime start = UnixEpoch.AddSeconds(int.Parse(trackParts[0].Split(',')[0])); DateTime stop = UnixEpoch.AddSeconds(int.Parse(trackParts[trackParts.Length - 1].Split(',')[0])); MeshNodeLocation before = mnc.Locations.Where(f => f.Name == id && f.Time < start).OrderByDescending(f => f.Time).FirstOrDefault(); MeshNodeLocation after = mnc.Locations.Where(f => f.Name == id && f.Time > stop).OrderBy(f => f.Time).FirstOrDefault(); foreach (var existing in mnc.Locations.Where(f => f.Name == id && f.Time >= start && f.Time <= stop)) { mnc.Locations.Remove(existing); } foreach (var report in trackParts) { string[] parts = report.Split(','); DateTime time = UnixEpoch.AddSeconds(int.Parse(parts[0])); if (string.IsNullOrWhiteSpace(parts[1]) || string.IsNullOrWhiteSpace(parts[2])) { continue; } DbGeography location = DbGeography.PointFromText(string.Format("POINT({0} {1})", parts[2], parts[1]), GeographyServices.SRID); if ((before == null || location.Distance(before.Location) > 20) && (after == null || location.Distance(after.Location) > 10)) // meters { MeshNodeLocation newLoc = new MeshNodeLocation { Name = id, Time = time, Location = location }; mnc.Locations.Add(newLoc); before = newLoc; } } mnc.SaveChanges(); } } return(new ContentResult { Content = "Thanks", ContentType = "text/plain" }); }
public double Distance(Point point) { return(_Geography.Distance(point._Geography).Value); }
// GET: MyProfile public async Task <ActionResult> Index() { //String UserIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; //if (string.IsNullOrEmpty(UserIP)) //{ // UserIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; //} var response = new WebClient().DownloadString("http://checkip.dyndns.org/"); int index = response.IndexOf(':'); int index2 = response.IndexOf('<', index); string UserIP = response.Substring(index + 2, index2 - (index + 2)); // string url = "http://freegeoip.net/json/" + UserIP; //string url = "https://ipinfo.io/" + UserIP + "/geo"; string url = "https://ipinfo.io/json"; WebClient client = new WebClient(); string jsonstring = client.DownloadString(url); dynamic dynObj = JsonConvert.DeserializeObject(jsonstring); System.Web.HttpContext.Current.Session["UserCountryCode"] = dynObj.country_code; const string point1text = "POINT(6.3692109 53.1459672)"; const string point2text = "POINT(6.3924875 53.1625221)"; DbGeography point1 = DbGeography.FromText(point1text); DbGeography point2 = DbGeography.FromText(point2text); var distance = point1.Distance(point2); string id = User.Identity.GetUserId(); if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } var user = await UserManager.FindByIdAsync(id); if (user == null) { return(HttpNotFound()); } string emailAddress = user.Email; Customers cust = new Customers(); cust = db.Customers.Where(x => x.Email == emailAddress).FirstOrDefault(); /* Temporary code to add the already registered users to the customer table * , after that every user will be added automatically when registering */ if (cust == null) { cust = new Customers { FullName = user.UserName, UserName = user.UserName, Email = user.Email, PhoneNum = user.PhoneNumber }; db.Customers.Add(cust); cust.Locations = new List <Locations>(); cust.Tags = new List <Tags>(); cust.Preferences = new List <Preferences>(); db.SaveChanges(); } Session["Customer"] = cust; List <Tags> tags = new List <Tags>(); tags = cust.Tags.ToList(); List <string> tagsNames = new List <string>(); foreach (var item in tags) { tagsNames.Add(item.Name); } ViewBag.tags = tagsNames; var TagsList = db.Tags.ToList().Select(x => new SelectListItem() { Selected = tagsNames.Contains(x.Name), Text = x.Name, Value = x.Name }); List <string> countries = new List <string>(); countries.Add("Select"); List <string> cities = new List <string>(); cities.Add("Select"); List <string> taggs = new List <string>(); taggs.Add("Select"); foreach (var item in db.Locations.ToList()) { string country = item.Country; countries.Add(country); string city = item.City; cities.Add(city); } foreach (var item in db.Tags.ToList()) { string tt = item.Name; taggs.Add(tt); } countries = countries.Distinct().ToList(); cities = cities.Distinct().ToList(); SelectList mycountries = new SelectList(countries); SelectList mycities = new SelectList(cities); SelectList mytags = new SelectList(taggs); ViewBag.listCountry = mycountries; Session["mycountries"] = mycountries; ViewBag.listCity = mycities; Session["mycities"] = mycities; ViewBag.taggs = mytags; Session["mytags"] = mytags; List <Preferences> list = new List <Preferences>(); foreach (var item in cust.Preferences.ToList()) { list.Add(item); } ViewBag.prefs = list; // ViewBag.tagsList = TagsList; return(View(new editCustomer { FullName = cust.FullName, Email = cust.Email, PhoneNum = cust.PhoneNum, Id = cust.Id, UserName = cust.UserName, tags = TagsList, })); }
/// <summary> /// Encodes the polygon for Google maps /// </summary> /// <returns></returns> public virtual string EncodeGooglePolygon(double minimumDistanceBetweenPointsInMeters) { var str = new StringBuilder(); if (this.GeoFence != null) { var encodeDiff = (Action <int>)(diff => { int shifted = diff << 1; if (diff < 0) { shifted = ~shifted; } int rem = shifted; while (rem >= 0x20) { str.Append((char)((0x20 | (rem & 0x1f)) + 63)); rem >>= 5; } str.Append((char)(rem + 63)); }); int lastLat = 0; int lastLng = 0; // AsText() returns coordinates as Well-Known-Text format (WKT). Strip leading and closing text string coordinates = this.GeoFence.AsText().Replace("POLYGON ((", "").Replace("))", ""); string[] longSpaceLat = coordinates.Split(','); DbGeography pointLast = null; DbGeography pointThis = null; for (int i = 0; i < longSpaceLat.Length; i++) { string[] longLat = longSpaceLat[i].Trim().Split(' '); double latDbl = double.Parse(longLat[1]); double lngDbl = double.Parse(longLat[0]); int latRnd = (int)Math.Round(latDbl * 1E5); int lngRnd = (int)Math.Round(lngDbl * 1E5); bool addPoint = true; if (minimumDistanceBetweenPointsInMeters > 0) { pointThis = DbGeography.FromText(string.Format("POINT({1} {0})", latDbl, lngDbl)); if (pointLast != null && pointThis.Distance(pointLast) < minimumDistanceBetweenPointsInMeters) { addPoint = false; } } if (addPoint) { encodeDiff(latRnd - lastLat); encodeDiff(lngRnd - lastLng); lastLat = latRnd; lastLng = lngRnd; pointLast = pointThis; } } } return(str.ToString()); }
/// <summary> /// The GetRestaurantWithoutFoodPreferences method. /// Gets a restaurant from the database that meets a specified criteria. /// <para> /// @author: Jennifer Nguyen /// @updated: 04/09/2018 /// </para> /// </summary> /// <param name="city"></param> /// <param name="state"></param> /// <param name="foodType"></param> /// <param name="distanceInMeters"></param> /// <param name="avgFoodPrice"></param> /// <param name="currentUtcTimeOfDay"></param> /// <param name="currentLocalDayOfWeek"></param> /// <param name="location"></param> /// <returns></returns> public ResponseDto <SelectedRestaurantDto> GetRestaurantWithoutFoodPreferences(string city, string state, string foodType, double distanceInMeters, int avgFoodPrice, TimeSpan currentUtcTimeOfDay, string currentLocalDayOfWeek, DbGeography location) { try { // Get the businessHours from the restaurants that meet the criteria var businessHours = (from userProfile in context.UserProfiles join restaurantProfile in context.RestaurantProfiles on userProfile.Id equals restaurantProfile.Id join businessHour in context.BusinessHours on restaurantProfile.Id equals businessHour.RestaurantId where restaurantProfile.Address.City == city && state == restaurantProfile.Address.State && foodType == restaurantProfile.Details.FoodType && avgFoodPrice == restaurantProfile.Details.AvgFoodPrice && distanceInMeters >= location.Distance(restaurantProfile.Location) && currentLocalDayOfWeek == businessHour.Day select businessHour).ToList(); // Select one restaurant profile id from a randomized list of qualified restaurants where the restaurants' business hours are open now var selectedRestaurantProfileId = businessHours.Where(businessHour // If open time is less than or equal to close time, then that means that the times are on the same day => businessHour.OpenTime.TimeOfDay <= businessHour.CloseTime.TimeOfDay ? (currentUtcTimeOfDay >= businessHour.OpenTime.TimeOfDay) && (currentUtcTimeOfDay <= businessHour.CloseTime.TimeOfDay) : (currentUtcTimeOfDay >= businessHour.OpenTime.TimeOfDay) || (currentUtcTimeOfDay <= businessHour.CloseTime.TimeOfDay)) .Select(businessHour => businessHour.RestaurantId).OrderBy(businessHour => Guid.NewGuid()).FirstOrDefault(); // Extract the restaurant information and contain the info in a SelectedRestaurantDto var selectedRestaurant = (from userProfile in context.UserProfiles join restaurantProfile in context.RestaurantProfiles on userProfile.Id equals restaurantProfile.Id where restaurantProfile.Id == selectedRestaurantProfileId select new SelectedRestaurantDto() { RestaurantId = restaurantProfile.Id, DisplayName = userProfile.DisplayName, ClientCity = city, ClientState = state, Address = restaurantProfile.Address, PhoneNumber = restaurantProfile.PhoneNumber, BusinessHourDtos = (from businessHour in context.BusinessHours where businessHour.RestaurantId == restaurantProfile.Id select new BusinessHourDto() { Day = businessHour.Day, OpenDateTime = businessHour.OpenTime, CloseDateTime = businessHour.CloseTime }).ToList() }).FirstOrDefault(); // Return the SelectedRestaurantDto return(new ResponseDto <SelectedRestaurantDto>() { Data = selectedRestaurant }); } catch (Exception) { // When exception is caught, then return a ResponseDto with null data with a general error message set return(new ResponseDto <SelectedRestaurantDto>() { Data = null, Error = GeneralErrorMessages.GENERAL_ERROR }); } }