/// <summary> /// The method for creating a trigger /// </summary> /// <param name="_trigger">The xml element containing the trigger description (Root node = Trigger)</param> /// <returns>The newly created trigger.</returns> public override Trigger CreateTrigger(XElement _trigger) { FindKeyTrigger t = null; String id = _trigger.Attribute("id").Value; string hint = _trigger.Elements().First().Element("Hint") != null ? _trigger.Elements().First().Element("Hint").Value : ""; string keyObject = _trigger.Elements().First().Element("KeyObject") != null ? _trigger.Elements().First().Element("KeyObject").Value : ""; float radius = float.Parse(_trigger.Elements().First().Element("Radius").Value); GeoCoordinate keyPosition = new GeoCoordinate(float.Parse(_trigger.Elements().First().Element("Latitude").Value), float.Parse(_trigger.Elements().First().Element("Longitude").Value), 0); t = new FindKeyTrigger(id, radius, keyPosition, hint, keyObject); t.preTriggerObjectIds = new List<string>(); t.postTriggerObjectIds = new List<string>(); if (_trigger.Element("PreTriggerObject") != null) foreach (XElement objectIdElement in _trigger.Element("PreTriggerObject").Elements()) { t.preTriggerObjectIds.Add(objectIdElement.Value); } if (_trigger.Element("PostTriggerObject") != null) foreach (XElement objectIdElement in _trigger.Element("PostTriggerObject").Elements()) { t.postTriggerObjectIds.Add(objectIdElement.Value); } return t; }
protected override async void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs Args) { _initialized = false; var location = await GetLastLocation(); if (location != null) { var geocoordinate = new GeoCoordinate(location.Latitude, location.Longitude); Map.SetView(geocoordinate, 18, MapAnimationKind.Linear); } _trackingTask = ScheduledActionService.Find(_TRACKING_TASK_NAME) as PeriodicTask; if (_trackingTask != null) { TrackingButton.DataContext = _trackingTask; TrackingEnabled = _trackingTask.IsEnabled; } else { TrackingEnabled = false; } _initialized = true; }
// from http://stackoverflow.com/questions/6366408/calculating-distance-between-two-latitude-and-longitude-geocoordinates public static double CalculateDistanceInMeters(double sourceLat, double sourceLng, double destLat, double destLng) { var sourceLocation = new GeoCoordinate(sourceLat, sourceLng); var targetLocation = new GeoCoordinate(destLat, destLng); return sourceLocation.GetDistanceTo(targetLocation); }
// Constructor public MainPage() { InitializeComponent(); bikePaths = new BikePaths(); trees = Tree.ParseCsv(); map = new Map(); map.CredentialsProvider = new ApplicationIdCredentialsProvider("Atvj6eBBbDS6-dL7shp9KmzY-0v0NL2ETYCFoHIDzQwK8_9bJ2ZdRgeMAj0sDs_F"); // Set the center coordinate and zoom level GeoCoordinate mapCenter = new GeoCoordinate(45.504693, -73.576494); int zoom = 14; // Create a pushpin to put at the center of the view Pushpin pin1 = new Pushpin(); pin1.Location = mapCenter; pin1.Content = "McGill University"; map.Children.Add(pin1); bikePaths.AddPathsToMap(map); // Set the map style to Aerial map.Mode = new Microsoft.Phone.Controls.Maps.AerialMode(); // Set the view and put the map on the page map.SetView(mapCenter, zoom); ContentPanel.Children.Add(map); }
//from http://stackoverflow.com/a/17545955 public static GeoCoordinate CreateWaypoint(GeoCoordinate sourceLocation, double distanceInMeters, double bearingDegrees, double altitude) { var distanceKm = distanceInMeters / 1000.0; var distanceRadians = distanceKm / 6371; //6371 = Earth's radius in km var bearingRadians = ToRad(bearingDegrees); var sourceLatitudeRadians = ToRad(sourceLocation.Latitude); var sourceLongitudeRadians = ToRad(sourceLocation.Longitude); var targetLatitudeRadians = Math.Asin(Math.Sin(sourceLatitudeRadians) * Math.Cos(distanceRadians) + Math.Cos(sourceLatitudeRadians) * Math.Sin(distanceRadians) * Math.Cos(bearingRadians)); var targetLongitudeRadians = sourceLongitudeRadians + Math.Atan2(Math.Sin(bearingRadians) * Math.Sin(distanceRadians) * Math.Cos(sourceLatitudeRadians), Math.Cos(distanceRadians) - Math.Sin(sourceLatitudeRadians) * Math.Sin(targetLatitudeRadians)); // adjust toLonRadians to be in the range -180 to +180... targetLongitudeRadians = (targetLongitudeRadians + 3 * Math.PI) % (2 * Math.PI) - Math.PI; return new GeoCoordinate(ToDegrees(targetLatitudeRadians), ToDegrees(targetLongitudeRadians), altitude); }
private async void GetMyMapLocationAsync() { Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracyInMeters = 50; try { Geoposition geoposition = await geolocator.GetGeopositionAsync( maximumAge: TimeSpan.FromMinutes(5), timeout: TimeSpan.FromSeconds(10) ); Map.Center = new GeoCoordinate(geoposition.Coordinate.Latitude, geoposition.Coordinate.Longitude); Map.ZoomLevel = ZoomLevel; myGeoCoordinate = geoposition.Coordinate.ToGeoCoordinate(); myMapOverlay.GeoCoordinate = myGeoCoordinate; myMapOverlay.Content = new Pushpin() {Content = "You"}; CalculateDistanceBetweenMeAndUser(); } catch (Exception ex) { if ((uint)ex.HResult == 0x80004004) { // the application does not have the right capability or the location master switch is off Debug.WriteLine("Geoposition not allowed or hadrware disabled"); } //else { // something else happened acquring the location Debug.WriteLine("Geoposition is not available. Failure."); } } }
public VehicleTracker(GeoCoordinate[] waypoints, double minSpeed, double maxSpeed, int lowSpeedDelayInSecs, int midSpeedDelayInSecs, int highSpeedDelayInSecs, double speedBetweenPosTolerance ) { if (waypoints.Length < 2) { throw new ArgumentException("Waypoints must be a GeoCoordinate array of at least 2"); } else if (minSpeed < 0 || minSpeed >= maxSpeed) { throw new ArgumentException("minSpeed must be positive and less than maxSpeed"); } else if (speedBetweenPosTolerance <= 0) { throw new ArgumentException("Speed tolerance must be greater than zero"); } else if (lowSpeedDelayInSecs <= 0 || midSpeedDelayInSecs <= 0 || highSpeedDelayInSecs <= 0) { throw new ArgumentException("Time delays must be positive"); } _waypoints = waypoints; _minSpeed = minSpeed; _maxSpeed = maxSpeed; _lowSpeedDelayInSeconds = lowSpeedDelayInSecs; _midSpeedDelayInSeconds = midSpeedDelayInSecs; _highSpeedDelayInSeconds = highSpeedDelayInSecs; _speedBetweenPosTolerance = speedBetweenPosTolerance; _random = new Random(); _speedInMph = _random.NextDouble(_minSpeed, _maxSpeed); }
public SelectDestination() { InitializeComponent(); street.Visibility = Visibility.Visible; (ApplicationBar.Buttons[1] as ApplicationBarIconButton).IsEnabled = true; GeoCoordinate geo = new GeoCoordinate(); geo = MainPage.bookingData.current_location; googlemap.Center = geo; googlemap.ZoomLevel = 16; zzoom.IsEnabled = true; positionLoaded = true; Microsoft.Phone.Controls.Maps.Pushpin new_pushpin = new Microsoft.Phone.Controls.Maps.Pushpin(); new_pushpin.Location = geo; pushPinCurrentLocation = new MapLayer(); new_pushpin.Content = "Current Location:\n "; new_pushpin.Content += MainPage.bookingData.current_location_address; new_pushpin.Visibility = Visibility.Visible; googlemap.Children.Add(pushPinCurrentLocation); pushPinCurrentLocation.AddChild(new_pushpin, geo, PositionOrigin.BottomLeft); if (MainPage.bookingData.isDesSet == true) { AddressMapping(); } }
private void AddPoint(Map controlMap, GeoCoordinate geo) { // With the new Map control: // Map -> MapLayer -> MapOverlay -> UIElements // - Add a MapLayer to the Map // - Add an MapOverlay to that layer // - We can add a single UIElement to that MapOverlay.Content MapLayer ml = new MapLayer(); MapOverlay mo = new MapOverlay(); // Add an Ellipse UI Ellipse r = new Ellipse(); r.Fill = new SolidColorBrush(Color.FromArgb(255, 240, 5, 5)); // the item is placed on the map at the top left corner so // in order to center it, we change the margin to a negative // margin equal to half the width and height r.Width = r.Height = 12; r.Margin = new Thickness(-6, -6, 0, 0); // Add the Ellipse to the Content mo.Content = r; // Set the GeoCoordinate of that content mo.GeoCoordinate = geo; // Add the MapOverlay to the MapLayer ml.Add(mo); // Add the MapLayer to the Map controlMap.Layers.Add(ml); }
/// <summary> /// Calculates the distance between 2 geo coordinates /// </summary> /// <param name="homeLat">Home latitude</param> /// <param name="homeLong">Home longitude</param> /// <param name="destLat">Destination latitude</param> /// <param name="destLong">Destination longitude</param> /// <returns>The distance in meters between</returns> public static double DistanceBetween(double homeLat, double homeLong, double destLat, double destLong) { var home = new GeoCoordinate(homeLat, homeLong); var dest = new GeoCoordinate(destLat, destLong); return DistanceBetween(home, dest); }
public ARunData ToARunData() { ARunData data = new ARunData(); for (int i = 0; i < longitude.Count(); i++) { GeoCoordinate geoCord = new GeoCoordinate(); geoCord.Longitude = longitude[i]; geoCord.Latitude = latitude[i]; data.geoCollection.Add(geoCord); } //data.datetime = JsonConvert.DeserializeObject<DateTime>(datetime, new JavaScriptDateTimeConverter()); try { data.datetime = TimeZoneInfo.ConvertTime(datetime, TimeZoneInfo.Local); } catch (Exception ex) { MessageBox.Show(ex.Message + "The time will be set to default"); data.datetime = DateTime.MinValue; } int dem = (int)IsolatedStorageSettings.ApplicationSettings["RunCount"]; dem++; IsolatedStorageSettings.ApplicationSettings.Save(); data.BurnedCalories = BurnedCalories; data.Duration = Duration; data.AvgSpeed = AvgSpeed; data.AvgPace = AvgPace; data.Distance = Distance; data.No = dem; data.IsSynced = true; return data; }
public ShotResult TakeShot(Player playerTakingShot, GeoCoordinate shotLocation) { if (playerTakingShot != NextPlayerToTakeShot) { return ShotResult.IllegalPlayer; } if (LastShotWasHit()) { return ShotResult.GameAlreadyOver; } var targetPlayer = NextPlayerToTakeShot == Player1 ? Player2 : Player1; if (targetPlayer.Location == null) { return ShotResult.TargetHasNoLocation; } if (ShotOutsideTargetZone(targetPlayer, shotLocation)) { return ShotResult.OutsideTargetZone; } //Take shot var shot = ShotOnTarget(targetPlayer, shotLocation) ? new Shot(playerTakingShot, shotLocation, ShotResult.Hit) : new Shot(playerTakingShot, shotLocation, ShotResult.Miss); //Push to stack shots.Push(shot); NextPlayerToTakeShot = targetPlayer; return shot.ShotResult; }
public JsonResult GetEnterprisesCloseToMyLocation(string latitude, string longitude) { var enterprises = Db.Enterprises.GetNearbyEnterprises(latitude, longitude); var searchViewModel = new MainSearchViewModel { Enterprises = new List<LightEnterprise>() }; foreach (var enterpriseViewModel in enterprises.Select(enterprise => new LightEnterprise { Key = EnterpriseHelper.GetKey(enterprise.Id), Name = enterprise.Name, LocationInfo = EnterpriseHelper.FormatDisplayStreet(enterprise), DistanceFromMyLocation = string.Empty, Categories = EnterpriseHelper.GetDisplayLabelsCategories(enterprise.Categories), Coordinates = enterprise.Coordinates, })) { searchViewModel.Enterprises.Add(enterpriseViewModel); } var myCoord = new GeoCoordinate(double.Parse(latitude, CultureInfo.InvariantCulture), double.Parse(longitude, CultureInfo.InvariantCulture)); foreach (var enterprise in searchViewModel.Enterprises) { var enterpriseCoord = new GeoCoordinate(enterprise.Coordinates.Lat, enterprise.Coordinates.Lng); var distance = myCoord.GetDistanceTo(enterpriseCoord); enterprise.DistanceFromMyLocation = string.Format("{0}km", Math.Round((distance / 1000), 1)); } return Json(searchViewModel); }
public void Guard(Route patrolRoute) { if (!flightTimer.Enabled) { // drone is not flying this.TakeOff(); } while (BatteryRemaining > Drone.BatteryLowLimit) { GeoCoordinate position = new GeoCoordinate(this.Position.Latitude, this.Position.Longitude); double distanceToPatrolEnd = position.GetDistanceTo(patrolRoute.RouteEnd); double distanceToPatrolStart = position.GetDistanceTo(patrolRoute.RouteStart); if (distanceToPatrolEnd < 20) { this.Destination = new WayPoint() {Latitude= patrolRoute.RouteStart.Latitude, Longitude = patrolRoute.RouteStart.Longitude, Altitude=0} ; } else if (distanceToPatrolStart < 20) { this.Destination = new WayPoint() { Latitude = patrolRoute.RouteEnd.Latitude, Longitude = patrolRoute.RouteEnd.Longitude, Altitude = 0 }; } this.Fly(); } // Battery limit is low, go back to base this.Destination = new WayPoint() { Latitude = patrolRoute.RouteStart.Latitude, Longitude = patrolRoute.RouteStart.Longitude, Altitude = 0 }; this.Land(); }
private async void GetCurrentLocation() { try { geolocator.DesiredAccuracyInMeters = 50; // If the cached location is over 30 minutes old, get a new one TimeSpan maximumAge = new TimeSpan(0, 30, 0); // If we're trying for more than 5 seconds, abandon the operation TimeSpan timeout = new TimeSpan(0, 0, 5); Geoposition myLocation = await geolocator.GetGeopositionAsync(maximumAge, timeout); GeoCoordinate geoCord = new GeoCoordinate(myLocation.Coordinate.Latitude, myLocation.Coordinate.Longitude); waypoints = new List<GeoCoordinate>(); waypoints.Add(geoCord); MyMapControl.Center = geoCord; MyMapControl.ZoomLevel = 12; AddPoint(MyMapControl, geoCord); geolocator.PositionChanged += newPosition; } catch (Exception exception) { //if this is an UnauthorizedAccessException: // 1) you haven’t included ID_CAP_LOCATION in your app manifest // or // 2) user has disabled location in the phone Settings // if this is a TimeoutExceeded exception: // the device couldn't get a location in the allotted time } }
private async void GetCoordinates() { Geolocator MyGeolocator = new Geolocator(); MyGeolocator.DesiredAccuracyInMeters = 5; Geoposition MyGeoPosition = null; try { MyGeoPosition = await MyGeolocator.GetGeopositionAsync(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10)); currentGeoCoordinate = ConvertGeocoordinate(MyGeoPosition.Coordinate); myMap.Center = currentGeoCoordinate; myMap.ZoomLevel = 15; if (!comeinGeoCoordinate.IsUnknown) { List<GeoCoordinate> geoCoordinates = new List<GeoCoordinate>(); geoCoordinates.Add(currentGeoCoordinate); geoCoordinates.Add(comeinGeoCoordinate); RouteQuery routeQuery = new RouteQuery(); routeQuery.Waypoints = geoCoordinates; routeQuery.QueryCompleted += routeQuery_QueryCompleted; routeQuery.QueryAsync(); } } catch (UnauthorizedAccessException) { MessageBox.Show("Location is disabled in phone settings"); } catch (Exception ex) { } }
/// <summary> /// Creates a new dot element. /// </summary> /// <param name="color"></param> public ElementText(int color, Font font, GeoCoordinate center, string text) { _color = color; _font = font; _center = center; _text = text; }
public static async void CheckForTargetLocation(int HitchBotID, int LocationID) { using (var db = new Models.Database()) { var location = db.Locations.First(l => l.ID == LocationID); var hitchbot = db.hitchBOTs.First(h => h.ID == HitchBotID); var TargetLocations = db.TwitterLocations.Where(l => l.HitchBot.ID == HitchBotID && l.Status == null).Include(l => l.TargetLocation); foreach (hitchbotAPI.Models.TwitterLocationTarget thisTargetLocation in TargetLocations) { var currentLocation = new GeoCoordinate(location.Latitude, location.Longitude); var targetLocation = new GeoCoordinate(thisTargetLocation.TargetLocation.Latitude, thisTargetLocation.TargetLocation.Longitude); if (currentLocation.GetDistanceTo(targetLocation) <= thisTargetLocation.RadiusKM * 1000) { int TweetID = await Helpers.TwitterHelper.PostTweetWithLocation(HitchBotID, LocationID, thisTargetLocation.TweetText); Task<int> WeatherTweet = TwitterHelper.PostTweetWithLocationAndWeather(HitchBotID, LocationID); LinkTargetLocationToTweet(TweetID, thisTargetLocation.ID); await WeatherTweet; break; } } } }
public StopsForLocationEventArgs(List<Stop> stops, GeoCoordinate searchLocation, bool limitExceeded, Exception error) : base(error) { this.stops = stops; this.location = searchLocation; this.limitExceeded = limitExceeded; }
private void Watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e) { var coord = new GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude); if (_line.Path.Count > 0) { var previousPoint = _line.Path.Last(); var distance = coord.GetDistanceTo(previousPoint); var millisPerKilometer = (1000.0 / distance) * (System.Environment.TickCount - _previousPositionChangeTick); _kilometres += distance / 1000.0; paceLabel.Text = TimeSpan.FromMilliseconds(millisPerKilometer).ToString(@"mm\:ss"); distanceLabel.Text = string.Format("{0:f2} km", _kilometres); caloriesLabel.Text = string.Format("{0:f0}", _kilometres * 65); // an average of 65 calories burned per kilometer PositionHandler handler = new PositionHandler(); var heading = handler.CalculateBearing(new Position(previousPoint), new Position(coord)); Map.SetView(coord, Map.ZoomLevel, heading, MapAnimationKind.Parabolic); ShellTile.ActiveTiles.First().Update(new IconicTileData() { Title = "WP8Runner", WideContent1 = string.Format("{0:f2} km", _kilometres), WideContent2 = string.Format("{0:f0} calories", _kilometres * 65), // an average of 65 calories burned per kilometer }); } else { Map.Center = coord; } _line.Path.Add(coord); _previousPositionChangeTick = System.Environment.TickCount; }
private void Button_gridbut_Click(object sender, RoutedEventArgs e) { if (sender == getGeoButton1) { (Application.Current as App).RouteOriginLocation = null; try { GeoCoordinate toGeo = new GeoCoordinate(); toGeo.Latitude = Double.Parse(LatitudeBox1.Text); toGeo.Longitude = Double.Parse(LongittudeBox1.Text); (Application.Current as App).RouteOriginLocation = toGeo; } catch { } NavigationService.Navigate(new Uri("/LocationSelectorPage.xaml?target=Origin", UriKind.Relative)); } else if (sender == getGeoButton2) { (Application.Current as App).SelectedLocation = null; try { GeoCoordinate toGeo = new GeoCoordinate(); toGeo.Latitude = Double.Parse(LatitudeBox2.Text); toGeo.Longitude = Double.Parse(LongittudeBox2.Text); (Application.Current as App).SelectedLocation = toGeo; } catch { } NavigationService.Navigate(new Uri("/LocationSelectorPage.xaml?target=Destination", UriKind.Relative)); } }
public void LocationForAddress(string addressString, GeoCoordinate searchNearLocation, object callerState) { GeocodeRequest request = new GeocodeRequest(); request.Credentials = new dev.virtualearth.net.webservices.v1.common.Credentials() { ApplicationId = bingMapsApiKey }; request.Query = addressString; request.UserProfile = new UserProfile() { CurrentLocation = new UserLocation() { Latitude = searchNearLocation.Latitude, Longitude = searchNearLocation.Longitude }, DistanceUnit = DistanceUnit.Mile, DeviceType = DeviceType.Mobile, ScreenSize = new SizeOfint() { Width = 480, Height = 700 } }; GeocodeState state = new GeocodeState() { Query = addressString, SearchNearLocation = searchNearLocation, CallerState = callerState }; geocodeService.GeocodeAsync(request, state); }
private void AddPinOnMap() { geo1 = new GeoCoordinate(Convert.ToDouble(ObjRootObjectJourney.data.latlong[0].latitude), Convert.ToDouble(ObjRootObjectJourney.data.latlong[0].longitude)); geo2 = new GeoCoordinate(Convert.ToDouble(ObjRootObjectJourney.data.latlong[ObjRootObjectJourney.data.latlong.Count - 1].latitude), Convert.ToDouble(ObjRootObjectJourney.data.latlong[ObjRootObjectJourney.data.latlong.Count - 1].longitude)); Image pinIMG = new Image(); pinIMG.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("/Images/map/pin_green.png", UriKind.Relative)); pinIMG.Width = 50; pinIMG.Height = 50; MapOverlay myLocationOverlay = new MapOverlay(); myLocationOverlay.Content = pinIMG; myLocationOverlay.PositionOrigin = new Point(0.5, 0.5); myLocationOverlay.GeoCoordinate = geo1; MapLayer myLocationLayer = new MapLayer(); myLocationLayer.Add(myLocationOverlay); mapJourney.Layers.Add(myLocationLayer); myLocationLayer = null; myLocationOverlay = null; pinIMG = null; pinIMG = new Image(); pinIMG.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("/Images/map/pin_red.png", UriKind.Relative)); pinIMG.Width = 50; pinIMG.Height = 50; myLocationOverlay = new MapOverlay(); myLocationOverlay.Content = pinIMG; myLocationOverlay.PositionOrigin = new Point(0.5, 0.5); myLocationOverlay.GeoCoordinate = geo2; myLocationLayer = new MapLayer(); myLocationLayer.Add(myLocationOverlay); mapJourney.Layers.Add(myLocationLayer); myLocationLayer = null; myLocationOverlay = null; pinIMG = null; mapJourney.ZoomLevel = ZoomLevel; mapJourney.Center = geo2; }
public void Init() { current = new GeoCoordinate(30.623665, -96.334171); destination = new GeoCoordinate(30.62505, -96.335362); navApp = new DroneControllerApp.AutoNavPage(); navApp.connectToDrone(); }
void Seanslar_getCompleted(seanslar sender) { loader.IsIndeterminate = false; PanoramaRoot.Title = sender.SalonBilgisi.name; pItem1.DataContext = sender.SalonBilgisi; listFilmler.ItemsSource = sender.SalonBilgisi.movies; if (sender.SalonBilgisi.latitude.ToString() != "false") { SalonCoordinate = new GeoCoordinate(double.Parse(sender.SalonBilgisi.latitude), double.Parse(sender.SalonBilgisi.longitude)); myMap.SetView(SalonCoordinate, 17); pinpoint_salon newPin = new pinpoint_salon(); MapOverlay newOverlay = new MapOverlay(); newOverlay.Content = newPin; newOverlay.GeoCoordinate = SalonCoordinate; newOverlay.PositionOrigin = new Point(0, 0); MapLayer MyLayer = new MapLayer(); MyLayer.Add(newOverlay); myMap.Layers.Add(MyLayer); } else { myMap.Visibility = Visibility.Collapsed; recMap.Visibility = System.Windows.Visibility.Collapsed; } }
public void CalculateDistances(GeoCoordinate clientCoordinate) { foreach (var server in Servers) { server.Distance = clientCoordinate.GetDistanceTo(server.GeoCoordinate); } }
public LocationForAddressEventArgs(List<LocationForQuery> locations, string query, GeoCoordinate searchNearLocation, Exception error, object state) : base(error, state) { this.query = query; this.locations = locations; this.searchNearLocation = searchNearLocation; }
public string GetInfo(string search, string latitud, string longitude, string distance) { var sCoord = new GeoCoordinate(double.Parse("30"),double.Parse("30")); var eCoord = new GeoCoordinate(double.Parse("30")+10, double.Parse("30")+10); return "[{\"idItem\": 1, \"idCategory\" : 1, \"name\":\"producto1\", \"category\":\"categoria 1\",\"description\":\"la description es indescriptible porque tenemos razones para inventar lo inventaro jaj que mamadas\", \"hasCost\": 1,\"cost\":16.5,\"active\":1, \"image\":\"http://192.168.1.110/finditout/images/image_1.jpg\"" + ",\"finditoutName\":\"dominio6\",\"distance\":" + sCoord.GetDistanceTo(eCoord) + ", \"latitude\":\"20.6827248\", \"longitude\":\"-103.3466798\", \"logo\":\"logo1\", \"allImages\":\"http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item1.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item2.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item3.jpg\"}" + ",{\"idItem\": 2, \"idCategory\" : 1, \"name\":\"producto2\", \"category\":\"categoria 1\",\"description\":\"la description es indescriptible porque tenemos razones para inventar lo inventaro jaj que mamadas\", \"hasCost\":1,\"cost\":20.5,\"active\":1, \"image\":\"http://192.168.1.110/finditout/images/image_1.jpg\"" + ",\"finditoutName\":\"dominio6\",\"distance\":" + sCoord.GetDistanceTo(eCoord) + ", \"latitude\":\"20.6827248\", \"longitude\":\"-103.4466798\", \"logo\":\"logo1\", \"allImages\":\"http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item1.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item2.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item3.jpg\"}" + //",{\"idItem\": 1, \"idCategory\" : 1, \"name\":\"producto1\", \"category\":\"categoria 1\",\"description\":\"la description es indescriptible porque tenemos razones para inventar lo inventaro jaj que mamadas\", \"hasCost\": 1,\"cost\":16.5,\"active\":1, \"image\":\"http://192.168.1.110/finditout/images/image_1.jpg\"" + ",\"finditoutName\":\"dominio6\",\"distance\":300.3, \"latitude\":\"20.6827248\", \"longitude\":\"-103.5466798\", \"logo\":\"logo1\", \"allImages\":\"http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item1.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item2.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item3.jpg\"}" + //",{\"idItem\": 2, \"idCategory\" : 1, \"name\":\"producto2\", \"category\":\"categoria 1\",\"description\":\"la description es indescriptible porque tenemos razones para inventar lo inventaro jaj que mamadas\", \"hasCost\":1,\"cost\":20.5,\"active\":1, \"image\":\"http://192.168.1.110/finditout/images/image_1.jpg\"" + ",\"finditoutName\":\"dominio6\",\"distance\":300.3, \"latitude\":\"20.6827248\", \"longitude\":\"-103.6466798\", \"logo\":\"logo1\", \"allImages\":\"http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item1.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item2.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item3.jpg\"}" + //",{\"idItem\": 1, \"idCategory\" : 1, \"name\":\"producto1\", \"category\":\"categoria 1\",\"description\":\"la description es indescriptible porque tenemos razones para inventar lo inventaro jaj que mamadas\", \"hasCost\": 1,\"cost\":16.5,\"active\":1, \"image\":\"http://192.168.1.110/finditout/images/image_1.jpg\"" + ",\"finditoutName\":\"dominio6\",\"distance\":300.3, \"latitude\":\"20.6827248\", \"longitude\":\"-103.7466798\", \"logo\":\"logo1\", \"allImages\":\"http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item1.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item2.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item3.jpg\"}" + //",{\"idItem\": 2, \"idCategory\" : 1, \"name\":\"producto2\", \"category\":\"categoria 1\",\"description\":\"la description es indescriptible porque tenemos razones para inventar lo inventaro jaj que mamadas\", \"hasCost\":1,\"cost\":20.5,\"active\":1, \"image\":\"http://192.168.1.110/finditout/images/image_1.jpg\"" + ",\"finditoutName\":\"dominio6\",\"distance\":300.3, \"latitude\":\"20.6827248\", \"longitude\":\"-103.8466798\", \"logo\":\"logo1\", \"allImages\":\"http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item1.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item2.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item3.jpg\"}" + //",{\"idItem\": 1, \"idCategory\" : 1, \"name\":\"producto1\", \"category\":\"categoria 1\",\"description\":\"la description es indescriptible porque tenemos razones para inventar lo inventaro jaj que mamadas\", \"hasCost\": 1,\"cost\":16.5,\"active\":1, \"image\":\"http://192.168.1.110/finditout/images/image_1.jpg\"" + ",\"finditoutName\":\"dominio6\",\"distance\":300.3, \"latitude\":\"20.6827248\", \"longitude\":\"-103.9466798\", \"logo\":\"logo1\", \"allImages\":\"http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item1.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item2.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item3.jpg\"}" + //",{\"idItem\": 2, \"idCategory\" : 1, \"name\":\"producto2\", \"category\":\"categoria 1\",\"description\":\"la description es indescriptible porque tenemos razones para inventar lo inventaro jaj que mamadas\", \"hasCost\":1,\"cost\":20.5,\"active\":1, \"image\":\"http://192.168.1.110/finditout/images/image_1.jpg\"" + ",\"finditoutName\":\"dominio6\",\"distance\":300.3, \"latitude\":\"20.6827248\", \"longitude\":\"-104.2466798\", \"logo\":\"logo1\", \"allImages\":\"http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item1.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item2.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item3.jpg\"}" + //",{\"idItem\": 1, \"idCategory\" : 1, \"name\":\"producto1\", \"category\":\"categoria 1\",\"description\":\"la description es indescriptible porque tenemos razones para inventar lo inventaro jaj que mamadas\", \"hasCost\": 1,\"cost\":16.5,\"active\":1, \"image\":\"http://192.168.1.110/finditout/images/image_1.jpg\"" + ",\"finditoutName\":\"dominio6\",\"distance\":300.3, \"latitude\":\"20.6827248\", \"longitude\":\"-104.3466798\", \"logo\":\"logo1\", \"allImages\":\"http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item1.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item2.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item3.jpg\"}" + //",{\"idItem\": 2, \"idCategory\" : 1, \"name\":\"producto2\", \"category\":\"categoria 1\",\"description\":\"la description es indescriptible porque tenemos razones para inventar lo inventaro jaj que mamadas\", \"hasCost\":1,\"cost\":20.5,\"active\":1, \"image\":\"http://192.168.1.110/finditout/images/image_1.jpg\"" + ",\"finditoutName\":\"dominio6\",\"distance\":300.3, \"latitude\":\"20.6827248\", \"longitude\":\"-104.4466798\", \"logo\":\"logo1\", \"allImages\":\"http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item1.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item2.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item3.jpg\"}" + //",{\"idItem\": 1, \"idCategory\" : 1, \"name\":\"producto1\", \"category\":\"categoria 1\",\"description\":\"la description es indescriptible porque tenemos razones para inventar lo inventaro jaj que mamadas\", \"hasCost\": 1,\"cost\":16.5,\"active\":1, \"image\":\"http://192.168.1.110/finditout/images/image_1.jpg\"" + ",\"finditoutName\":\"dominio6\",\"distance\":300.3, \"latitude\":\"20.6827248\", \"longitude\":\"-104.5466798\", \"logo\":\"logo1\", \"allImages\":\"http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item1.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item2.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item3.jpg\"}" + //",{\"idItem\": 2, \"idCategory\" : 1, \"name\":\"producto2\", \"category\":\"categoria 1\",\"description\":\"la description es indescriptible porque tenemos razones para inventar lo inventaro jaj que mamadas\", \"hasCost\":1,\"cost\":20.5,\"active\":1, \"image\":\"http://192.168.1.110/finditout/images/image_1.jpg\"" + ",\"finditoutName\":\"dominio6\",\"distance\":300.3, \"latitude\":\"20.6827248\", \"longitude\":\"-104.2466798\", \"logo\":\"logo1\", \"allImages\":\"http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item1.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item2.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item3.jpg\"}" + //",{\"idItem\": 1, \"idCategory\" : 1, \"name\":\"producto1\", \"category\":\"categoria 1\",\"description\":\"la description es indescriptible porque tenemos razones para inventar lo inventaro jaj que mamadas\", \"hasCost\": 1,\"cost\":16.5,\"active\":1, \"image\":\"http://192.168.1.110/finditout/images/image_1.jpg\"" + ",\"finditoutName\":\"dominio6\",\"distance\":300.3, \"latitude\":\"20.6827248\", \"longitude\":\"-104.3466798\", \"logo\":\"logo1\", \"allImages\":\"http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item1.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item2.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item3.jpg\"}" + //",{\"idItem\": 1, \"idCategory\" : 1, \"name\":\"producto1\", \"category\":\"categoria 1\",\"description\":\"la description es indescriptible porque tenemos razones para inventar lo inventaro jaj que mamadas\", \"hasCost\": 1,\"cost\":16.5,\"active\":1, \"image\":\"http://192.168.1.110/finditout/images/image_1.jpg\"" + ",\"finditoutName\":\"dominio6\",\"distance\":300.3, \"latitude\":\"20.6827248\", \"longitude\":\"-104.3466798\", \"logo\":\"logo1\", \"allImages\":\"http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item1.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item2.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item3.jpg\"}" + //",{\"idItem\": 1, \"idCategory\" : 1, \"name\":\"producto1\", \"category\":\"categoria 1\",\"description\":\"la description es indescriptible porque tenemos razones para inventar lo inventaro jaj que mamadas\", \"hasCost\": 1,\"cost\":16.5,\"active\":1, \"image\":\"http://192.168.1.110/finditout/images/image_1.jpg\"" + ",\"finditoutName\":\"dominio6\",\"distance\":300.3, \"latitude\":\"20.6827248\", \"longitude\":\"-104.3466798\", \"logo\":\"logo1\", \"allImages\":\"http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item1.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item2.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item3.jpg\"}" + //",{\"idItem\": 1, \"idCategory\" : 1, \"name\":\"producto1\", \"category\":\"categoria 1\",\"description\":\"la description es indescriptible porque tenemos razones para inventar lo inventaro jaj que mamadas\", \"hasCost\": 1,\"cost\":16.5,\"active\":1, \"image\":\"http://192.168.1.110/finditout/images/image_1.jpg\"" + ",\"finditoutName\":\"dominio6\",\"distance\":300.3, \"latitude\":\"20.6827248\", \"longitude\":\"-104.3466798\", \"logo\":\"logo1\", \"allImages\":\"http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item1.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item2.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item3.jpg\"}" + //",{\"idItem\": 1, \"idCategory\" : 1, \"name\":\"producto1\", \"category\":\"categoria 1\",\"description\":\"la description es indescriptible porque tenemos razones para inventar lo inventaro jaj que mamadas\", \"hasCost\": 1,\"cost\":16.5,\"active\":1, \"image\":\"http://192.168.1.110/finditout/images/image_1.jpg\"" + ",\"finditoutName\":\"dominio6\",\"distance\":300.3, \"latitude\":\"20.6827248\", \"longitude\":\"-104.3466798\", \"logo\":\"logo1\", \"allImages\":\"http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item1.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item2.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item3.jpg\"}" + //",{\"idItem\": 1, \"idCategory\" : 1, \"name\":\"producto1\", \"category\":\"categoria 1\",\"description\":\"la description es indescriptible porque tenemos razones para inventar lo inventaro jaj que mamadas\", \"hasCost\": 1,\"cost\":16.5,\"active\":1, \"image\":\"http://192.168.1.110/finditout/images/image_1.jpg\"" + ",\"finditoutName\":\"dominio6\",\"distance\":300.3, \"latitude\":\"20.6827248\", \"longitude\":\"-104.3466798\", \"logo\":\"logo1\", \"allImages\":\"http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item1.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item2.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item3.jpg\"}" + //",{\"idItem\": 1, \"idCategory\" : 1, \"name\":\"producto1\", \"category\":\"categoria 1\",\"description\":\"la description es indescriptible porque tenemos razones para inventar lo inventaro jaj que mamadas\", \"hasCost\": 1,\"cost\":16.5,\"active\":1, \"image\":\"http://192.168.1.110/finditout/images/image_1.jpg\"" + ",\"finditoutName\":\"dominio6\",\"distance\":300.3, \"latitude\":\"20.6827248\", \"longitude\":\"-104.3466798\", \"logo\":\"logo1\", \"allImages\":\"http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item1.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item2.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item3.jpg\"}" + //",{\"idItem\": 1, \"idCategory\" : 1, \"name\":\"producto1\", \"category\":\"categoria 1\",\"description\":\"la description es indescriptible porque tenemos razones para inventar lo inventaro jaj que mamadas\", \"hasCost\": 1,\"cost\":16.5,\"active\":1, \"image\":\"http://192.168.1.110/finditout/images/image_1.jpg\"" + ",\"finditoutName\":\"dominio6\",\"distance\":300.3, \"latitude\":\"20.6827248\", \"longitude\":\"-104.3466798\", \"logo\":\"logo1\", \"allImages\":\"http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item1.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item2.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item3.jpg\"}"+ //",{\"idItem\": 2, \"idCategory\" : 1, \"name\":\"producto2\", \"category\":\"categoria 1\",\"description\":\"la description es indescriptible porque tenemos razones para inventar lo inventaro jaj que mamadas\", \"hasCost\":1,\"cost\":20.5,\"active\":1, \"image\":\"http://192.168.1.110/finditout/images/image_1.jpg\"" + ",\"finditoutName\":\"dominio6\",\"distance\":300.3, \"latitude\":\"20.6827248\", \"longitude\":\"-104.6466798\", \"logo\":\"logo1\", \"allImages\":\"http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item1.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item2.jpg@@http://192.168.1.110/finditout/img/FindOut/FindItOutName/Item/item3.jpg\"}"+ "]"; }
/// <summary> /// Shows the Bing Maps application centered on the specified location. /// </summary> /// <param name="center">The location that will be used as the center point for the map.</param> /// <exception cref="InvalidOperationException">Center and SearchTerm cannot both be empty.</exception> public void Show(GeoCoordinate center) { new BingMapsTask() { Center = center, }.Show(); }
private const double WGS84_b = 6356752.3; // Minor semiaxis [m] #endregion Fields #region Methods public static QuadKey CreateQuadKey(GeoCoordinate coordinate, int levelOfDetail) { return new QuadKey( LonToTileX(Clip(coordinate.Longitude, -179.9999999, 179.9999999), levelOfDetail), LatToTileY(Clip(coordinate.Latitude, -85.05112877, 85.05112877), levelOfDetail), levelOfDetail); }
public Airport(string name, double x, double y) { this.Name = name; this.Coordinate = new GeoCoordinate(x, y); }
static void Main(string[] args) { logger.LogInfo("Log initialized"); // use File.ReadAllLines(path) to grab all the lines from your csv file // Log and error if you get 0 lines and a warning if you get 1 line var lines = File.ReadAllLines(csvPath); // Create a new instance of your TacoParser class var parser = new TacoParser(); // Grab an IEnumerable of locations using the Select command: var locations = lines.Select(parser.Parse); var locations = lines.Select(parser.Parse).ToArray(); // DON'T FORGET TO LOG YOUR STEPS // Now, here's the new code // Create two `ITrackable` variables with initial values of `null`. These will be used to store your two taco bells that are the furthest from each other. // Create a `double` variable to store the distance TacoBell tacoOne = null; TacoBell tacoTwo = null; double distance = 0; // Include the Geolocation toolbox, so you can compare locations: `using GeoCoordinatePortable;` // Do a loop for your locations to grab each location as the origin (perhaps: `locA`) // Create a new corA Coordinate with your locA's lat and long for (int i = 0; i < locations.Length; i++) { TacoBell locA = (TacoBell)locations[i]; GeoCoordinate corA = new GeoCoordinate(locA.latitude, locA.longitude); for (int j = i + 1; j < locations.Length; j++) { TacoBell locB = (TacoBell)locations[j]; GeoCoordinate corB = new GeoCoordinate(locB.latitude, locB.longitude); double temp = corA.GetDistanceTo(corB); if (temp > distance) { tacoOne = locA; tacoTwo = locB; distance = temp; } } } Console.WriteLine($"The furthest Taco Bells are {distance} away from each other"); Console.WriteLine($"Location A: {tacoOne.name}"); Console.WriteLine($"Location B: {tacoTwo.name}"); // Now, do another loop on the locations with the scope of your first loop, so you can grab the "destination" location (perhaps: `locB`) // Create a new Coordinate with your locB's lat and long // Now, compare the two using `.GetDistanceTo()`, which returns a double // If the distance is greater than the currently saved distance, update the distance and the two `ITrackable` variables you set above // Once you've looped through everything, you've found the two Taco Bells furthest away from each other. // TODO: Find the two Taco Bells in Alabama that are the furthest from one another. // HINT: You'll need two nested forloops TacoBell ala1 = null; TacoBell ala2 = null; double alaDistance = 0; double top = 34.991; double bottom = 31.018; double right = -84.977; double left = -88.477; for (int i = 0; i < locations.Length; i++) { TacoBell locA = (TacoBell)locations[i]; GeoCoordinate corA = new GeoCoordinate(locA.latitude, locA.longitude); if ((corA.Latitude < top && corA.Latitude > bottom) && (corA.Longitude < right && corA.Longitude > left)) { for (int j = i + 1; j < locations.Length; j++) { TacoBell locB = (TacoBell)locations[j]; GeoCoordinate corB = new GeoCoordinate(locB.latitude, locB.longitude); if ((corB.Latitude < top && corB.Latitude > bottom) && (corB.Longitude < right && corB.Longitude > left)) { double temp = corA.GetDistanceTo(corB); if (temp > alaDistance) { ala1 = locA; ala2 = locB; alaDistance = temp; } } } } } Console.WriteLine($"The furthest TacoBells in Alabama are {alaDistance} apart"); Console.WriteLine($"Ala Location A: {ala1.name}"); Console.WriteLine($"Ala Location B: {ala2.name}"); }
/// <summary> /// Calculates edge data. /// </summary> /// <param name="tagsIndex"></param> /// <param name="tags"></param> /// <param name="tagsForward"></param> /// <param name="from"></param> /// <param name="to"></param> /// <param name="edgeInterpreter"></param> /// <param name="intermediates"></param> /// <returns></returns> protected override Edge CalculateEdgeData(IEdgeInterpreter edgeInterpreter, ITagsIndex tagsIndex, TagsCollectionBase tags, bool tagsForward, GeoCoordinate from, GeoCoordinate to, List <GeoCoordinateSimple> intermediates) { if (edgeInterpreter == null) { throw new ArgumentNullException("edgeInterpreter"); } if (tagsIndex == null) { throw new ArgumentNullException("tagsIndex"); } if (tags == null) { throw new ArgumentNullException("tags"); } if (from == null) { throw new ArgumentNullException("from"); } if (to == null) { throw new ArgumentNullException("to"); } uint tagsId = tagsIndex.Add(tags); var shapeInBox = true; if (intermediates != null) { // verify shape-in-box. var box = new GeoCoordinateBox(from, to); for (int idx = 0; idx < intermediates.Count; idx++) { if (!box.Contains(intermediates[idx].Longitude, intermediates[idx].Latitude)) { // shape not in box. shapeInBox = false; break; } } } return(new Edge() { Forward = tagsForward, Tags = tagsId, Distance = (float)from.DistanceEstimate(to).Value, ShapeInBox = shapeInBox }); }
/// <inheritdoc /> public double GetElevation(ElevationDataType elevationDataType, QuadKey quadKey, GeoCoordinate coordinate) { return(getElevation(quadKey.TileX, quadKey.TileY, quadKey.LevelOfDetail, (int)elevationDataType, coordinate.Latitude, coordinate.Longitude)); }
public ActionResult CheckDirctFlightPost(string FlightNumber, string Date) { // testing Claim c = null; Guid g = new Guid("ecbc3e69-71c0-4fab-971d-3acc3bd98480"); using (AirHelpDBContext dc = new AirHelpDBContext()) { c = dc.Claims.Where(cl => cl.ClaimId == g).SingleOrDefault(); ViewBag.IsEu = c.AirPorts.Any(a => CommonHeppler.IsEuCountry(a.countryCode)); ViewBag.delayMessage = (c.issueDistance < 1500000 ? "Полета ви закъсня ли с повече от 2 часа?" : (c.issueDistance < 3500000 || ViewBag.IsEu ? "Полета ви закъсня ли с повече от 3 часа?" : "Полета ви закъсня ли с повече от 3 часа ?")); } return(View("ColectData", c)); var model = new VMDirectFlight() { date = Date, number = FlightNumber, numberError = "" }; var arr = Date.Split('.'); var day = int.Parse(arr[0]); var mont = int.Parse(arr[1]); var year = int.Parse(arr[2]); FlightStatus fligth = CommonHeppler.GetFlight(FlightNumber, Date); if (fligth.flightStatuses.Length == 0) { model.commonError = "Невалидна комбинция от номер и дата на полета"; return(View("DirectFlight", model)); } var AirLine = fligth.appendix.airlines.ToList().Find(a => a.iata == fligth.flightStatuses[0].primaryCarrierFsCode); Claim claim = new Claim { ClaimId = Guid.NewGuid(), FlightDate = Date, State = ClaimStatus.Accepted, UserId = User.Identity.IsAuthenticated ? User.Identity.Name : null, DateCreated = DateTime.Now, Type = ProblemType.Pending, FlightNumber = FlightNumber, AirCompany = AirLine.name, AirCompanyCountry = "" }; int number = 0; fligth.appendix.airports.ToList().ForEach(a => { double distance = 0; if (number > 0) { var sCoord = new GeoCoordinate(fligth.appendix.airports[number - 1].longitude, fligth.appendix.airports[number - 1].latitude); var eCoord = new GeoCoordinate(fligth.appendix.airports[number].longitude, fligth.appendix.airports[number].latitude); distance = sCoord.GetDistanceTo(eCoord); } AirPort airport = new AirPort { Id = Guid.NewGuid(), ap_name = a.name, city = a.city, cityCode = a.cityCode, country = a.countryName, countryCode = a.countryCode, elevation = a.elevationFeet, iata = a.iata, number = number, name = a.name, timezone = 0, icao = a.icao, type = "", x = a.latitude, y = a.longitude, distanceToNext = distance }; number++; claim.AirPorts.Add(airport); }); claim.allDistance = claim.AirPorts.Sum(a => a.distanceToNext); using (AirHelpDBContext dc = new AirHelpDBContext()) { dc.Claims.Add(claim); dc.SaveChanges(); } return(View("ColectData", claim)); }
public ActionResult ColectFlightDataFlightPost() { Guid newGuid = Guid.NewGuid(); var jsonString = Request.Form["jsonAirport"]; var jsonAirCompany = Request.Form["jsonAirComapany"]; var issueDepartureCode = Request.Form["Flight"]; var nubmer = Request.Form["FlightNumber"]; var nubmers = Request.Form["FlightNumbers"]; var date = Request.Form["Date"]; var dates = Request.Form["Dates"]; string[] flightNumbers = nubmers != null?nubmers.Split(',') : new string[] { nubmer, "" }; string[] flightDates = dates != null?dates.Split(',') : new string[] { date, "" }; var json = new JavaScriptSerializer(); Airport[] airports = json.Deserialize <Airport[]>(jsonString); Airline airCompany = json.Deserialize <Airline>(jsonAirCompany); Claim claim = new Claim { ClaimId = Guid.NewGuid(), State = ClaimStatus.Pending, UserId = null, DateCreated = DateTime.Now, Type = ProblemType.Pending, AirCompany = airCompany.name, AirCompanyCountry = airCompany.country, AirCompanyCode = airCompany.iata }; if (issueDepartureCode == null) { issueDepartureCode = airports[0].iata; } int number = 1; airports.ToList().ForEach(a => { AirPort airport = new AirPort { Id = Guid.NewGuid(), ap_name = a.ap_name, city = a.city, country = a.country, elevation = int.Parse(a.elevation), iata = a.iata, number = number, name = a.name, timezone = 0, icao = "", type = "", x = double.Parse(a.x), y = double.Parse(a.y), FlightNumber = airports.Length == number ? (nubmer != null ? nubmer : "") : flightNumbers[number - 1], FlightDate = airports.Length == number ? (date != null ? date : "") : flightDates[number - 1], startIssue = (number == 1 && airports.Length == 2) || (a.iata == issueDepartureCode) }; number++; claim.AirPorts.Add(airport); }); double allDistance = 0; double issuDistance = 0; bool flag = false; var claimAirPorts = claim.AirPorts.ToArray(); for (int i = 0; i < claimAirPorts.Length - 1; i++) { var sCoord = new GeoCoordinate(claimAirPorts[i].y, claimAirPorts[i].x); var eCoord = new GeoCoordinate(claimAirPorts[i + 1].y, claimAirPorts[i + 1].x); var d = sCoord.GetDistanceTo(eCoord); claimAirPorts[i].distanceToNext = d; allDistance += d; flag = flag || (claimAirPorts[i].iata == issueDepartureCode); if (flag) { issuDistance += d; } } claim.issueDistance = issuDistance; claim.allDistance = allDistance; // Check EU flagth IsEUFlight isEUFlight = IsEUFlight.NonEU; if (claim.AirPorts.All(a => CommonHeppler.IsEuCountryByName(a.country))) { isEUFlight = IsEUFlight.EU; } else if (claim.AirPorts.Any(a => CommonHeppler.IsEuCountryByName(a.country))) { isEUFlight = IsEUFlight.EUMixed; } double distance = (claim.Type == ProblemType.Delay) ? claim.allDistance : claim.issueDistance; FlightType flightType = FlightType.NotSupported; if (isEUFlight == IsEUFlight.NonEU) { flightType = FlightType.NotSupported; } else if (distance <= 1500000) { flightType = FlightType.F1500; } else if (distance <= 3500000 || isEUFlight == IsEUFlight.EU) { flightType = FlightType.FTo3500; } else { flightType = FlightType.FmoreThen3500; } claim.IsEUFlight = isEUFlight; claim.FlightType = flightType; using (AirHelpDBContext dc = new AirHelpDBContext()) { dc.Claims.Add(claim); dc.SaveChanges(); } return(View("ColectData", claim)); }
public async Task <PlayerUpdateResponse> HumanLikeWalking(GeoCoordinate targetLocation, double walkingSpeedInKilometersPerHour, Func <Task> functionExecutedWhileWalking, bool fromgoogle = false) { var randomFactor = 0.5f; var randomMin = (int)(walkingSpeedInKilometersPerHour * (1 - randomFactor)); var randomMax = (int)(walkingSpeedInKilometersPerHour * (1 + randomFactor)); var RandomWalkSpeed = RandomDevice.Next(randomMin, randomMax); walkingSpeedInKilometersPerHour = RandomWalkSpeed; var speedInMetersPerSecond = walkingSpeedInKilometersPerHour / 3.6; var sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var distanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); Logger.ColoredConsoleWrite(ConsoleColor.DarkCyan, $"Distance to target location: {distanceToTarget:0.##} meters. Will take {distanceToTarget / speedInMetersPerSecond:0.##} seconds!"); var nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, targetLocation); var nextWaypointDistance = speedInMetersPerSecond; var waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing); //Initial walking var requestSendDateTime = DateTime.Now; var result = await _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude, waypoint.Altitude); if (functionExecutedWhileWalking != null) { await functionExecutedWhileWalking(); } var locatePokemonWhileWalkingDateTime = DateTime.Now; do { var millisecondsUntilGetUpdatePlayerLocationResponse = (DateTime.Now - requestSendDateTime).TotalMilliseconds; sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var currentDistanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); if (currentDistanceToTarget < 40) { if (speedInMetersPerSecond > SpeedDownTo) { Logger.ColoredConsoleWrite(ConsoleColor.DarkCyan, $"We are within 40 meters of the target. Slowing down to ~10 km/h to not pass the target."); speedInMetersPerSecond = SpeedDownTo; } } nextWaypointDistance = Math.Min(currentDistanceToTarget, millisecondsUntilGetUpdatePlayerLocationResponse / 1000 * speedInMetersPerSecond); nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, targetLocation); waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing); requestSendDateTime = DateTime.Now; result = await _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude, waypoint.Altitude); if (functionExecutedWhileWalking != null) { await functionExecutedWhileWalking();// look for pokemon } await RandomHelper.RandomDelay(500, 600); }while ((LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation) >= 30 && !fromgoogle) || LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation) >= 2); return(result); }
private void Listening(IGbfsApi client) { Receive <RefreshManifest>(refresh => { _stationInformationRefresh?.Cancel(); _stationStatusRefresh?.Cancel(); client.GetManifest().PipeTo(Self); }); Receive <Manifest>(manifest => { var delay = TimeSpan.FromSeconds(manifest.TimeToLive); Context.System.Scheduler.ScheduleTellOnce(delay, Self, new RefreshManifest(), Self); var language = manifest.Data.ContainsKey("en") ? "en" : manifest.Data.Keys.First(); Self.Tell(new RefreshStationInformation { Manifest = manifest, Language = language, }); Self.Tell(new RefreshStationStatus { Manifest = manifest, Language = language, }); }); Receive <RefreshStationInformation>(refresh => { refresh.Manifest.GetStationInformation(client, refresh.Language) .ContinueWith(informationTask => { return(Refresh: refresh, StationInformation: informationTask.Result); }, TaskContinuationOptions.ExecuteSynchronously) .PipeTo(Self); }); Receive <RefreshStationStatus>(refresh => { refresh.Manifest.GetStationStatus(client, refresh.Language) .ContinueWith(statusTask => { return(Refresh: refresh, StationStatus: statusTask.Result); }, TaskContinuationOptions.ExecuteSynchronously) .PipeTo(Self); }); Receive <(RefreshStationInformation Refresh, StationInformation StationInformation)>(tuple => { var delay = TimeSpan.FromSeconds(tuple.StationInformation.TimeToLive); _stationInformationRefresh = Context.System.Scheduler.ScheduleTellOnceCancelable(delay, Self, tuple.Refresh, Self); _stationInformation = tuple.StationInformation.Data; }); Receive <(RefreshStationStatus Refresh, StationStatus StationStatus)>(tuple => { var delay = TimeSpan.FromSeconds(tuple.StationStatus.TimeToLive); _stationStatusRefresh = Context.System.Scheduler.ScheduleTellOnceCancelable(delay, Self, tuple.Refresh, Self); _stationStatus = tuple.StationStatus.Data; }); Receive <RequestChallenge>(request => { var stationStatuses = _stationStatus.Stations .Where(x => x.IsRenting && x.IsReturning && x.IsInstalled); var areaOfInterest = new GeoCoordinate(request.AreaOfInterest.Center.Latitude, request.AreaOfInterest.Center.Longitude); var all = _stationInformation.Stations .Select(si => new { Coordinate = new GeoCoordinate(si.Lat, si.Lon), Information = si, }) .Where(x => x.Coordinate.GetDistanceTo(areaOfInterest) <= request.AreaOfInterest.Radius * 1000) .Join(stationStatuses, x => x.Information.StationId, ss => ss.StationId, (x, status) => ( Coordinate: x.Coordinate, Information: x.Information, Status: status )) .ToList() .AsEnumerable(); var fromStation = GetCoordinate(all, request.From, x => x.NumBikesAvailable); var toStation = GetCoordinate(all, request.To, x => x.NumDocksAvailable, fromStation.Information); Sender.Tell(new Challenge { FromShortName = ShortenStationName(fromStation.Information.Name), From = fromStation.Information, ToShortName = ShortenStationName(toStation.Information.Name), To = toStation.Information, }); }); Receive <RequestStatus>(request => { var stationStatuses = _stationStatus.Stations .Where(x => x.IsRenting && x.IsReturning && x.IsInstalled); var areaOfInterest = new GeoCoordinate(request.AreaOfInterest.Center.Latitude, request.AreaOfInterest.Center.Longitude); var all = _stationInformation.Stations .Select(si => new { Coordinate = new GeoCoordinate(si.Lat, si.Lon), Information = si, }) .Where(x => x.Coordinate.GetDistanceTo(areaOfInterest) <= request.AreaOfInterest.Radius * 1000) .Join(stationStatuses, x => x.Information.StationId, ss => ss.StationId, (x, status) => new { x.Coordinate, x.Information, Status = status, }) .ToList(); Sender.Tell(new Status { Bikes = all.Sum(x => x.Status.NumBikesAvailable), Docks = all.Sum(x => x.Status.NumDocksAvailable), Stations = all.Count, }); }); Self.Tell(new RefreshManifest()); }
public IEnumerable <Orcamento> RetornarOrcamentosComDistanciaCalculada(string prestadorLatitude, string prestadorLongitude, string raio, string usuarioId) { var orcamentos = _orcamentoService.RetornaOrcamentosAbertos().ToList(); var orcamentosPagos = GetOrcamentoPagosPeloPrestador(usuarioId).ToList(); var orcamentosView = new List <Orcamento>(); foreach (var orcamento in orcamentos) { var expirou = _orcamentoService.PegarQuantidadeOrcamentosPorPrestador(orcamento.orc_Id); if (!expirou) { continue; } if (orcamentosPagos.All(s => s.orc_Id != orcamento.orc_Id)) { var coord_orcamento = new GeoCoordinate(); coord_orcamento.Latitude = double.Parse(orcamento.orc_latitude.Replace(",", "."), CultureInfo.InvariantCulture); coord_orcamento.Longitude = double.Parse(orcamento.orc_longitude.Replace(",", "."), CultureInfo.InvariantCulture); var coordenada_prestador = new GeoCoordinate(); coordenada_prestador.Latitude = double.Parse(prestadorLatitude.Replace(",", "."), CultureInfo.InvariantCulture); coordenada_prestador.Longitude = double.Parse(prestadorLongitude.Replace(",", "."), CultureInfo.InvariantCulture); var distancia = (coordenada_prestador.GetDistanceTo(coord_orcamento) / 1000); var endereco = orcamento.orc_endereco; var cidade = ""; var estado = new EnumAppEstados(); var partes = endereco.Split(','); foreach (var parte in partes.Where(s => s.Contains("-"))) { var separar = parte.Split('-'); var ufs = " AC, AL, AP, AM, BA, CE, DF, ES, GO, MA, MT, MS, MG, PA,PB, PR, PE, PI, RJ, RN, RS, RO, RR, SC, SP, SE, TO"; if (ufs.Contains(separar[1])) { estado = (EnumAppEstados)Enum.Parse(typeof(EnumAppEstados), separar[1]); cidade = separar[0]; } else { continue; } } orcamento.Distancia = Math.Round(distancia, 2).ToString() + " Km do seu negócio em " + cidade.ToString().Trim() + " - " + estado.ToString().Trim() + " "; if (distancia <= double.Parse(raio)) { orcamentosView.Add(orcamento); } } } return(orcamentosView); }
/// <inheritdoc cref="GetAreas(IGeoTiff, ITile)"/> /// <param name="imageMinCoordinate">Minimal <see cref="GeoCoordinate"/> /// of <see cref="IGeoTiff"/></param> /// <param name="imageMaxCoordinate">Maximal <see cref="GeoCoordinate"/> /// of <see cref="IGeoTiff"/></param> /// <param name="imageSize"><see cref="Images.Size"/> of <see cref="IGeoTiff"/></param> /// <param name="tileMinCoordinate">Minimal <see cref="GeoCoordinate"/> /// of <see cref="ITile"/></param> /// <param name="tileMaxCoordinate">Maximal <see cref="GeoCoordinate"/> /// of <see cref="ITile"/></param> /// <param name="tileSize"><see cref="Images.Size"/> of <see cref="ITile"/></param> /// <returns></returns> /// <exception cref="ArgumentNullException"/> /// <exception cref="ArgumentException"/> public static (Area readArea, Area writeArea) GetAreas(GeoCoordinate imageMinCoordinate, GeoCoordinate imageMaxCoordinate, Size imageSize, GeoCoordinate tileMinCoordinate, GeoCoordinate tileMaxCoordinate, Size tileSize) { #region Preconditions checks if (imageMinCoordinate == null) { throw new ArgumentNullException(nameof(imageMinCoordinate)); } if (imageMaxCoordinate == null) { throw new ArgumentNullException(nameof(imageMaxCoordinate)); } string err = string.Format(Strings.Culture, Strings.Equal, nameof(imageMinCoordinate), nameof(imageMaxCoordinate)); // This is to prevent unclear DivideByZeroException exception if (imageMinCoordinate == imageMaxCoordinate) { throw new ArgumentException(err); } if (imageSize == null) { throw new ArgumentNullException(nameof(imageSize)); } if (tileMinCoordinate == null) { throw new ArgumentNullException(nameof(tileMinCoordinate)); } if (tileMaxCoordinate == null) { throw new ArgumentNullException(nameof(tileMaxCoordinate)); } err = string.Format(Strings.Culture, Strings.Equal, nameof(tileMinCoordinate), nameof(tileMaxCoordinate)); // This is to prevent unclear DivideByZeroException exception if (tileMinCoordinate == tileMaxCoordinate) { throw new ArgumentException(err); } if (tileSize == null) { throw new ArgumentNullException(nameof(tileSize)); } #endregion // Read from input geotiff in pixels double readPosMinX = imageSize.Width * (tileMinCoordinate.X - imageMinCoordinate.X) / (imageMaxCoordinate.X - imageMinCoordinate.X); double readPosMaxX = imageSize.Width * (tileMaxCoordinate.X - imageMinCoordinate.X) / (imageMaxCoordinate.X - imageMinCoordinate.X); double readPosMinY = imageSize.Height - imageSize.Height * (tileMaxCoordinate.Y - imageMinCoordinate.Y) / (imageMaxCoordinate.Y - imageMinCoordinate.Y); double readPosMaxY = imageSize.Height - imageSize.Height * (tileMinCoordinate.Y - imageMinCoordinate.Y) / (imageMaxCoordinate.Y - imageMinCoordinate.Y); // If outside of tiff -- set to 0.0/Max readPosMinX = readPosMinX <0.0 ? 0.0 : readPosMinX> imageSize.Width ? imageSize.Width : readPosMinX; readPosMaxX = readPosMaxX <0.0 ? 0.0 : readPosMaxX> imageSize.Width ? imageSize.Width : readPosMaxX; readPosMinY = readPosMinY <0.0 ? 0.0 : readPosMinY> imageSize.Height ? imageSize.Height : readPosMinY; readPosMaxY = readPosMaxY <0.0 ? 0.0 : readPosMaxY> imageSize.Height ? imageSize.Height : readPosMaxY; // Output tile's borders in pixels double tilePixMinX = readPosMinX.Equals(0.0) ? imageMinCoordinate.X : readPosMinX.Equals(imageSize.Width) ? imageMaxCoordinate.X : tileMinCoordinate.X; double tilePixMaxX = readPosMaxX.Equals(0.0) ? imageMinCoordinate.X : readPosMaxX.Equals(imageSize.Width) ? imageMaxCoordinate.X : tileMaxCoordinate.X; double tilePixMinY = readPosMaxY.Equals(0.0) ? imageMaxCoordinate.Y : readPosMaxY.Equals(imageSize.Height) ? imageMinCoordinate.Y : tileMinCoordinate.Y; double tilePixMaxY = readPosMinY.Equals(0.0) ? imageMaxCoordinate.Y : readPosMinY.Equals(imageSize.Height) ? imageMinCoordinate.Y : tileMaxCoordinate.Y; // Positions of dataset to write in tile double writePosMinX = tileSize.Width - tileSize.Width * (tileMaxCoordinate.X - tilePixMinX) / (tileMaxCoordinate.X - tileMinCoordinate.X); double writePosMaxX = tileSize.Width - tileSize.Width * (tileMaxCoordinate.X - tilePixMaxX) / (tileMaxCoordinate.X - tileMinCoordinate.X); double writePosMinY = tileSize.Height * (tileMaxCoordinate.Y - tilePixMaxY) / (tileMaxCoordinate.Y - tileMinCoordinate.Y); double writePosMaxY = tileSize.Height * (tileMaxCoordinate.Y - tilePixMinY) / (tileMaxCoordinate.Y - tileMinCoordinate.Y); // Sizes to read and write double readXSize = readPosMaxX - readPosMinX; double writeXSize = writePosMaxX - writePosMinX; double readYSize = Math.Abs(readPosMaxY - readPosMinY); double writeYSize = Math.Abs(writePosMaxY - writePosMinY); // Shifts double readXShift = readPosMinX - (int)readPosMinX; readXSize += readXShift; double readYShift = readPosMinY - (int)readPosMinY; readYSize += readYShift; double writeXShift = writePosMinX - (int)writePosMinX; writeXSize += writeXShift; double writeYShift = writePosMinY - (int)writePosMinY; writeYSize += writeYShift; // If output image sides are lesser then 1 - make image 1x1 pixels to prevent division by 0 writeXSize = writeXSize > 1.0 ? writeXSize : 1.0; writeYSize = writeYSize > 1.0 ? writeYSize : 1.0; PixelCoordinate readOriginCoordinate = new(readPosMinX, readPosMinY); PixelCoordinate writeOriginCoordinate = new(writePosMinX, writePosMinY); Size readSize = new((int)readXSize, (int)readYSize); Size writeSize = new((int)writeXSize, (int)writeYSize); Area readArea = new(readOriginCoordinate, readSize); Area writeArea = new(writeOriginCoordinate, writeSize); return(readArea, writeArea); }
public async Task <PlayerUpdateResponse> HumanPathWalking(GpxReader.Trkpt trk, double walkingSpeedInKilometersPerHour, Func <Task <bool> > functionExecutedWhileWalking, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); //PlayerUpdateResponse result = null; var targetLocation = new GeoCoordinate(Convert.ToDouble(trk.Lat, CultureInfo.InvariantCulture), Convert.ToDouble(trk.Lon, CultureInfo.InvariantCulture)); var speedInMetersPerSecond = walkingSpeedInKilometersPerHour / 3.6; var sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); // Logger.Write($"Distance to target location: {distanceToTarget:0.##} meters. Will take {distanceToTarget/speedInMetersPerSecond:0.##} seconds!", LogLevel.Info); var nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, targetLocation); var nextWaypointDistance = speedInMetersPerSecond; var waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing, Convert.ToDouble(trk.Ele, CultureInfo.InvariantCulture)); //Initial walking var requestSendDateTime = DateTime.Now; var result = await _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude, waypoint.Altitude); UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude); do { cancellationToken.ThrowIfCancellationRequested(); var millisecondsUntilGetUpdatePlayerLocationResponse = (DateTime.Now - requestSendDateTime).TotalMilliseconds; sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var currentDistanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); //if (currentDistanceToTarget < 40) //{ // if (speedInMetersPerSecond > SpeedDownTo) // { // //Logger.Write("We are within 40 meters of the target. Speeding down to 10 km/h to not pass the target.", LogLevel.Info); // speedInMetersPerSecond = SpeedDownTo; // } //} nextWaypointDistance = Math.Min(currentDistanceToTarget, millisecondsUntilGetUpdatePlayerLocationResponse / 1000 * speedInMetersPerSecond); nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, targetLocation); waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing); requestSendDateTime = DateTime.Now; result = await _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude, waypoint.Altitude); UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude); if (functionExecutedWhileWalking != null) { await functionExecutedWhileWalking(); // look for pokemon & hit stops } } while (LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation) >= 30); return(result); }
/// <summary> /// Generates an arc and it's next point from the current aggregated point. /// </summary> /// <param name="previous"></param> /// <param name="current"></param> /// <param name="next"></param> /// <returns></returns> internal AggregatedArc CreateArcAndPoint(AggregatedRoutePoint previous, AggregatedRoutePoint current, AggregatedRoutePoint next) { // create the arc. AggregatedArc a = new AggregatedArc(); a.Name = current.Entry.Name; a.Names = current.Entry.Names.ConvertTo(); a.Tags = current.Entry.Tags.ConvertToTagsCollection(); if (previous != null) { GeoCoordinate previous_coordinate = new GeoCoordinate(previous.Entry.Latitude, previous.Entry.Longitude); GeoCoordinate currentCoordinate = new GeoCoordinate(current.Entry.Latitude, current.Entry.Longitude); Meter distance = previous_coordinate.DistanceReal(currentCoordinate); a.Distance = distance; } // create the point. AggregatedPoint p = new AggregatedPoint(); p.Location = new GeoCoordinate(current.Entry.Latitude, current.Entry.Longitude); p.Points = new List <PointPoi>(); p.EntryIdx = current.EntryIndex; if (previous != null && next != null && next.Entry != null) { GeoCoordinate previous_coordinate = new GeoCoordinate(previous.Entry.Latitude, previous.Entry.Longitude); GeoCoordinate next_coordinate = new GeoCoordinate(next.Entry.Latitude, next.Entry.Longitude); p.Angle = RelativeDirectionCalculator.Calculate(previous_coordinate, p.Location, next_coordinate); } if (current.Entry.SideStreets != null && current.Entry.SideStreets.Length > 0) { p.ArcsNotTaken = new List <KeyValuePair <RelativeDirection, AggregatedArc> >(); foreach (RouteSegmentBranch sideStreet in current.Entry.SideStreets) { AggregatedArc side = new AggregatedArc(); side.Name = sideStreet.Name; side.Names = sideStreet.Names.ConvertTo(); side.Tags = sideStreet.Tags.ConvertToTagsCollection(); RelativeDirection side_direction = null; if (previous != null) { GeoCoordinate previous_coordinate = new GeoCoordinate(previous.Entry.Latitude, previous.Entry.Longitude); GeoCoordinate next_coordinate = new GeoCoordinate(sideStreet.Latitude, sideStreet.Longitude); side_direction = RelativeDirectionCalculator.Calculate(previous_coordinate, p.Location, next_coordinate); } p.ArcsNotTaken.Add(new KeyValuePair <RelativeDirection, AggregatedArc>(side_direction, side)); } } if (current.Entry.Points != null) { foreach (RoutePoint route_point in current.Entry.Points) { PointPoi poi = new PointPoi(); poi.Name = route_point.Name; poi.Tags = route_point.Tags.ConvertTo(); poi.Location = new GeoCoordinate(route_point.Latitude, route_point.Longitude); GeoCoordinate previous_coordinate = new GeoCoordinate(previous.Entry.Latitude, previous.Entry.Longitude); GeoCoordinate current_coordinate = new GeoCoordinate(current.Entry.Latitude, current.Entry.Longitude); poi.Angle = RelativeDirectionCalculator.Calculate(previous_coordinate, current_coordinate, poi.Location); p.Points.Add(poi); } } // link the arc to the point. a.Next = p; return(a); }
/// <summary> /// Notifies this layer the mapview has changed. /// </summary> /// <param name="map"></param> /// <param name="zoomFactor"></param> /// <param name="center"></param> /// <param name="view"></param> /// <param name="extraView"></param> protected internal override void ViewChanged(Map map, float zoomFactor, GeoCoordinate center, View2D view, View2D extraView) { if (_suspended) { // do not accept trigger changes if suspended. return; } if (!this.IsVisible) { // if the map is not visible also do not accept changes. return; } try { // calculate the current zoom level. var zoomLevel = (int)System.Math.Round(map.Projection.ToZoomLevel(zoomFactor), 0); if (zoomLevel >= _minZoomLevel && zoomLevel <= _maxZoomLevel) { // build the bounding box. var viewBox = view.OuterBox; var box = new GeoCoordinateBox(map.Projection.ToGeoCoordinates(viewBox.Min[0], viewBox.Min[1]), map.Projection.ToGeoCoordinates(viewBox.Max[0], viewBox.Max[1])); // build the tile range. lock (_stack) { // make sure the tile range is not in use. _stack.Clear(); lock (_cache) { var tileRange = TileRange.CreateAroundBoundingBox(box, zoomLevel); _currentZoom = zoomLevel; foreach (var tile in tileRange.EnumerateInCenterFirst().Reverse()) { if (tile.IsValid) { // make sure all tiles are valid. Image2D temp; if (!_cache.TryPeek(tile, out temp) && !_loading.Contains(tile)) { // not cached and not loading. _stack.Push(tile); OsmSharp.Logging.Log.TraceEvent("LayerTile", Logging.TraceEventType.Information, "Queued tile: " + tile.ToString()); } } } _timer.Change(0, 250); } if (_stack.Count > 0) { // reset the attempts. lock (_attempts) { _attempts.Clear(); } } } } } catch (Exception ex) { // don't worry about exceptions here. OsmSharp.Logging.Log.TraceEvent("LayerTile", Logging.TraceEventType.Error, ex.Message); } }
public async Task <PlayerUpdateResponse> Move(GeoCoordinate targetLocation, double walkingSpeedInKilometersPerHour, Func <Task <bool> > functionExecutedWhileWalking, CancellationToken cancellationToken, bool disableHumanLikeWalking) { cancellationToken.ThrowIfCancellationRequested(); if (!disableHumanLikeWalking) { var speedInMetersPerSecond = walkingSpeedInKilometersPerHour / 3.6; var sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); // Logger.Write($"Distance to target location: {distanceToTarget:0.##} meters. Will take {distanceToTarget/speedInMetersPerSecond:0.##} seconds!", LogLevel.Info); var nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, targetLocation); var nextWaypointDistance = speedInMetersPerSecond; var waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing); //Initial walking var requestSendDateTime = DateTime.Now; var result = await _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude, _client.Settings.DefaultAltitude); UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude); do { cancellationToken.ThrowIfCancellationRequested(); var millisecondsUntilGetUpdatePlayerLocationResponse = (DateTime.Now - requestSendDateTime).TotalMilliseconds; sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var currentDistanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); if (currentDistanceToTarget < 40) { if (speedInMetersPerSecond > SpeedDownTo) { //Logger.Write("We are within 40 meters of the target. Speeding down to 10 km/h to not pass the target.", LogLevel.Info); speedInMetersPerSecond = SpeedDownTo; } } nextWaypointDistance = Math.Min(currentDistanceToTarget, millisecondsUntilGetUpdatePlayerLocationResponse / 1000 * speedInMetersPerSecond); nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, targetLocation); waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing); requestSendDateTime = DateTime.Now; result = await _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude, _client.Settings.DefaultAltitude); UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude); if (functionExecutedWhileWalking != null) { await functionExecutedWhileWalking(); // look for pokemon } } while (LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation) >= 30); return(result); } else { var result = await _client.Player.UpdatePlayerLocation(targetLocation.Latitude, targetLocation.Longitude, _client.Settings.DefaultAltitude); UpdatePositionEvent?.Invoke(targetLocation.Latitude, targetLocation.Longitude); return(result); } }
public static void updatePlayerLocation(Client client, GeoCoordinate loc, bool updateFile = true) { updatePlayerLocation(client, loc.Latitude, loc.Longitude, loc.Altitude, updateFile); }
public double getDistance(GeoCoordinate sCoord, GeoCoordinate eCoord) { return(sCoord.GetDistanceTo(eCoord)); }
/// <summary> /// Searches the data for a point on an edge closest to the given coordinate. /// </summary> /// <param name="graph"></param> /// <param name="vehicle"></param> /// <param name="coordinate"></param> /// <param name="delta"></param> /// <param name="matcher"></param> /// <param name="pointTags"></param> /// <param name="interpreter"></param> /// <param name="parameters"></param> public SearchClosestResult <TEdgeData> SearchClosest(IBasicRouterDataSource <TEdgeData> graph, IRoutingInterpreter interpreter, Vehicle vehicle, GeoCoordinate coordinate, float delta, IEdgeMatcher matcher, TagsCollectionBase pointTags, Dictionary <string, object> parameters) { return(this.SearchClosest(graph, interpreter, vehicle, coordinate, delta, matcher, pointTags, false, null)); }
public static double CalculateDistanceInMeters(GeoCoordinate sourceLocation, GeoCoordinate destinationLocation) { return(CalculateDistanceInMeters(sourceLocation.Latitude, sourceLocation.Longitude, destinationLocation.Latitude, destinationLocation.Longitude)); }
private async Task <BaseViewModel <PagingResult <StoreViewModel> > > GetAll(GetStoreWithGPSRequestViewmovel request, string defaultCondition = null) { var pageSize = request.PageSize; var pageIndex = request.PageIndex; var result = new BaseViewModel <PagingResult <StoreViewModel> >(); string filter = SearchHelper <Store> .GenerateStringExpression(request.Filter, defaultCondition); Expression <Func <Store, bool> > FilterExpression = await LinqHelper <Store> .StringToExpression(filter); var includeList = IncludeLinqHelper <Store> .StringToListInclude(request?.Include); QueryArgs <Store> queryArgs = new QueryArgs <Store> { Offset = pageSize * (pageIndex - 1), Limit = pageSize, Filter = FilterExpression, Sort = request.SortBy, Include = includeList }; var data = _repository.Get(queryArgs.Filter, queryArgs.Sort, queryArgs.Offset, queryArgs.Limit, queryArgs.Include).ToList(); //var sql = data.ToSql(); if (data == null || data.Count == 0) { result.Description = MessageHandler.CustomMessage(MessageConstants.NO_RECORD); result.Code = MessageConstants.NO_RECORD; } else { var pageSizeReturn = pageSize; if (data.Count < pageSize) { pageSizeReturn = data.Count; } result.Data = new PagingResult <StoreViewModel> { Results = _mapper.Map <IEnumerable <StoreViewModel> >(data), PageIndex = pageIndex, PageSize = pageSizeReturn, TotalRecords = _repository.Count(queryArgs.Filter) }; foreach (var item in result.Data.Results) { var listPromo = _promotionRepository.GetMany(_ => _.BrandId == item.BrandId && _.IsActive == true); item.Promotions = _mapper.Map <ICollection <PromotionViewModel> >(listPromo); } } if (request.Longitude != null && request.Latitude != null) { foreach (var item in result?.Data?.Results) { var sCoord = new GeoCoordinate(item.Latitude, item.Longitude); var eCoord = new GeoCoordinate(request.Latitude.Value, request.Longitude.Value); item.Distance = (sCoord.GetDistanceTo(eCoord) / 1000.0); } } return(result); }
/// <summary> /// Searches the data for a point on an edge closest to the given coordinate. /// </summary> /// <param name="graph"></param> /// <param name="vehicle"></param> /// <param name="coordinate"></param> /// <param name="delta"></param> /// <param name="matcher"></param> /// <param name="pointTags"></param> /// <param name="interpreter"></param> /// <param name="verticesOnly"></param> /// <param name="parameters"></param> public SearchClosestResult <TEdgeData> SearchClosest(IBasicRouterDataSource <TEdgeData> graph, IRoutingInterpreter interpreter, Vehicle vehicle, GeoCoordinate coordinate, float delta, IEdgeMatcher matcher, TagsCollectionBase pointTags, bool verticesOnly, Dictionary <string, object> parameters) { Meter distanceEpsilon = .1; // 10cm is the tolerance to distinguish points. var closestWithMatch = new SearchClosestResult <TEdgeData>(double.MaxValue, 0); var closestWithoutMatch = new SearchClosestResult <TEdgeData>(double.MaxValue, 0); double searchBoxSize = delta; // create the search box. var searchBox = new GeoCoordinateBox(new GeoCoordinate( coordinate.Latitude - searchBoxSize, coordinate.Longitude - searchBoxSize), new GeoCoordinate( coordinate.Latitude + searchBoxSize, coordinate.Longitude + searchBoxSize)); // get the arcs from the data source. var arcs = graph.GetEdges(searchBox); if (!verticesOnly) { // find both closest arcs and vertices. // loop over all. foreach (KeyValuePair <uint, KeyValuePair <uint, TEdgeData> > arc in arcs) { if (!graph.TagsIndex.Contains(arc.Value.Value.Tags)) { // skip this edge, no valid tags found. continue; } var arcTags = graph.TagsIndex.Get(arc.Value.Value.Tags); bool canBeTraversed = vehicle.CanTraverse(arcTags); if (canBeTraversed) { // the edge can be traversed. // test the two points. float fromLatitude, fromLongitude; float toLatitude, toLongitude; double distance; if (graph.GetVertex(arc.Key, out fromLatitude, out fromLongitude) && graph.GetVertex(arc.Value.Key, out toLatitude, out toLongitude)) { // return the vertex. var fromCoordinates = new GeoCoordinate(fromLatitude, fromLongitude); distance = coordinate.DistanceReal(fromCoordinates).Value; GeoCoordinateSimple[] coordinates; if (!graph.GetEdgeShape(arc.Key, arc.Value.Key, out coordinates)) { coordinates = null; } if (distance < distanceEpsilon.Value) { // the distance is smaller than the tolerance value. closestWithoutMatch = new SearchClosestResult <TEdgeData>( distance, arc.Key); if (matcher == null || (pointTags == null || pointTags.Count == 0) || matcher.MatchWithEdge(vehicle, pointTags, arcTags)) { closestWithMatch = new SearchClosestResult <TEdgeData>( distance, arc.Key); break; } } if (distance < closestWithoutMatch.Distance) { // the distance is smaller for the without match. closestWithoutMatch = new SearchClosestResult <TEdgeData>( distance, arc.Key); } if (distance < closestWithMatch.Distance) { // the distance is smaller for the with match. if (matcher == null || (pointTags == null || pointTags.Count == 0) || matcher.MatchWithEdge(vehicle, pointTags, graph.TagsIndex.Get(arc.Value.Value.Tags))) { closestWithMatch = new SearchClosestResult <TEdgeData>( distance, arc.Key); } } var toCoordinates = new GeoCoordinate(toLatitude, toLongitude); distance = coordinate.DistanceReal(toCoordinates).Value; if (distance < closestWithoutMatch.Distance) { // the distance is smaller for the without match. closestWithoutMatch = new SearchClosestResult <TEdgeData>( distance, arc.Value.Key); } if (distance < closestWithMatch.Distance) { // the distance is smaller for the with match. if (matcher == null || (pointTags == null || pointTags.Count == 0) || matcher.MatchWithEdge(vehicle, pointTags, arcTags)) { closestWithMatch = new SearchClosestResult <TEdgeData>( distance, arc.Value.Key); } } // search along the line. double distanceTotal = 0; var previous = fromCoordinates; GeoCoordinateSimple[] arcValueValueCoordinates; if (graph.GetEdgeShape(arc.Key, arc.Value.Key, out arcValueValueCoordinates) && arcValueValueCoordinates != null) { // calculate distance along all coordinates. for (int idx = 0; idx < arcValueValueCoordinates.Length; idx++) { var current = new GeoCoordinate(arcValueValueCoordinates[idx].Latitude, arcValueValueCoordinates[idx].Longitude); distanceTotal = distanceTotal + current.DistanceReal(previous).Value; previous = current; } } distanceTotal = distanceTotal + toCoordinates.DistanceReal(previous).Value; if (distanceTotal > 0) { // the from/to are not the same location. // loop over all edges that are represented by this arc (counting intermediate coordinates). previous = fromCoordinates; GeoCoordinateLine line; double distanceToSegment = 0; if (arcValueValueCoordinates != null) { for (int idx = 0; idx < arcValueValueCoordinates.Length; idx++) { var current = new GeoCoordinate( arcValueValueCoordinates[idx].Latitude, arcValueValueCoordinates[idx].Longitude); line = new GeoCoordinateLine(previous, current, true, true); distance = line.DistanceReal(coordinate).Value; if (distance < closestWithoutMatch.Distance) { // the distance is smaller. PointF2D projectedPoint = line.ProjectOn(coordinate); // calculate the position. if (projectedPoint != null) { // calculate the distance double distancePoint = previous.DistanceReal(new GeoCoordinate(projectedPoint)).Value + distanceToSegment; double position = distancePoint / distanceTotal; closestWithoutMatch = new SearchClosestResult <TEdgeData>( distance, arc.Key, arc.Value.Key, position, arc.Value.Value, coordinates); } } if (distance < closestWithMatch.Distance) { PointF2D projectedPoint = line.ProjectOn(coordinate); // calculate the position. if (projectedPoint != null) { // calculate the distance double distancePoint = previous.DistanceReal(new GeoCoordinate(projectedPoint)).Value + distanceToSegment; double position = distancePoint / distanceTotal; if (matcher == null || (pointTags == null || pointTags.Count == 0) || matcher.MatchWithEdge(vehicle, pointTags, arcTags)) { closestWithMatch = new SearchClosestResult <TEdgeData>( distance, arc.Key, arc.Value.Key, position, arc.Value.Value, coordinates); } } } // add current segment distance to distanceToSegment for the next segment. distanceToSegment = distanceToSegment + line.LengthReal.Value; // set previous. previous = current; } } // check the last segment. line = new GeoCoordinateLine(previous, toCoordinates, true, true); distance = line.DistanceReal(coordinate).Value; if (distance < closestWithoutMatch.Distance) { // the distance is smaller. PointF2D projectedPoint = line.ProjectOn(coordinate); // calculate the position. if (projectedPoint != null) { // calculate the distance double distancePoint = previous.DistanceReal(new GeoCoordinate(projectedPoint)).Value + distanceToSegment; double position = distancePoint / distanceTotal; closestWithoutMatch = new SearchClosestResult <TEdgeData>( distance, arc.Key, arc.Value.Key, position, arc.Value.Value, coordinates); } } if (distance < closestWithMatch.Distance) { PointF2D projectedPoint = line.ProjectOn(coordinate); // calculate the position. if (projectedPoint != null) { // calculate the distance double distancePoint = previous.DistanceReal(new GeoCoordinate(projectedPoint)).Value + distanceToSegment; double position = distancePoint / distanceTotal; if (matcher == null || (pointTags == null || pointTags.Count == 0) || matcher.MatchWithEdge(vehicle, pointTags, arcTags)) { closestWithMatch = new SearchClosestResult <TEdgeData>( distance, arc.Key, arc.Value.Key, position, arc.Value.Value, coordinates); } } } } } } } } else { // only find closest vertices. // loop over all. foreach (KeyValuePair <uint, KeyValuePair <uint, TEdgeData> > arc in arcs) { float fromLatitude, fromLongitude; float toLatitude, toLongitude; if (graph.GetVertex(arc.Key, out fromLatitude, out fromLongitude) && graph.GetVertex(arc.Value.Key, out toLatitude, out toLongitude)) { var vertexCoordinate = new GeoCoordinate(fromLatitude, fromLongitude); double distance = coordinate.DistanceReal(vertexCoordinate).Value; if (distance < closestWithoutMatch.Distance) { // the distance found is closer. closestWithoutMatch = new SearchClosestResult <TEdgeData>( distance, arc.Key); } vertexCoordinate = new GeoCoordinate(toLatitude, toLongitude); distance = coordinate.DistanceReal(vertexCoordinate).Value; if (distance < closestWithoutMatch.Distance) { // the distance found is closer. closestWithoutMatch = new SearchClosestResult <TEdgeData>( distance, arc.Value.Key); } GeoCoordinateSimple[] arcValueValueCoordinates; if (graph.GetEdgeShape(arc.Key, arc.Value.Key, out arcValueValueCoordinates)) { // search over intermediate points. for (int idx = 0; idx < arcValueValueCoordinates.Length; idx++) { vertexCoordinate = new GeoCoordinate( arcValueValueCoordinates[idx].Latitude, arcValueValueCoordinates[idx].Longitude); distance = coordinate.DistanceReal(vertexCoordinate).Value; if (distance < closestWithoutMatch.Distance) { // the distance found is closer. closestWithoutMatch = new SearchClosestResult <TEdgeData>( distance, arc.Key, arc.Value.Key, idx, arc.Value.Value, arcValueValueCoordinates); } } } } } } // return the best result. if (closestWithMatch.Distance < double.MaxValue) { return(closestWithMatch); } return(closestWithoutMatch); }
private String ResolveCity(GeoCoordinate coordinate, out String state) { state = null; const double SeattleSizeThreshold = 0.0500; if (IsDistanceWithin(coordinate, SeattleLocation, SeattleSizeThreshold)) { state = "Washington"; return("Seattle"); } const double BellevueSizeThreshold = 0.0500; if (IsDistanceWithin(coordinate, BellevueLocation, BellevueSizeThreshold)) { state = "Washington"; return("Bellevue"); } const double RedmondSizeThreshold = 0.0360; // 0.0360 should get most of the Microsoft main campus. But it's a tricky area. if (IsDistanceWithin(coordinate, RedmondLocation, RedmondSizeThreshold)) { state = "Washington"; return("Redmond"); } const double SnoqualmieSizeThreshold = 0.0250; if (IsDistanceWithin(coordinate, SnoqualmieLocation, SnoqualmieSizeThreshold)) { state = "Washington"; return("Snoqualmie"); } const double VegasSizeThreshold = 0.0700; if (IsDistanceWithin(coordinate, VegasLocation, VegasSizeThreshold)) { state = "Nevada"; return("Las Vegas"); } const double VegasDowntownSizeThreshold = 0.0050; if (IsDistanceWithin(coordinate, VegasFremontStreetLocation, VegasDowntownSizeThreshold)) { state = "Nevada"; return("Las Vegas - Fremont Street"); } const double RockfordIllinoisSizeThreshold = 0.1030; if (IsDistanceWithin(coordinate, RockfordIllinoisLocation, RockfordIllinoisSizeThreshold)) { state = "Illinois"; return("Rockford"); } const double RoscoeIllinoisSizeThreshold = 0.0200; if (IsDistanceWithin(coordinate, RoscoeIllinoisLocation, RoscoeIllinoisSizeThreshold)) { state = "Illinois"; return("Roscoe"); } return(null); }
/// <summary> /// Returns the weight between two points on an edge with the given tags for the vehicle. /// </summary> /// <param name="tags"></param> /// <param name="from"></param> /// <param name="to"></param> /// <returns></returns> public virtual double Weight(TagsCollection tags, GeoCoordinate from, GeoCoordinate to) { var distance = from.DistanceEstimate(to).Value; return(distance / (MaxSpeed(tags).Value) * 3.6); }
public CivicAddress ResolveAddress(GeoCoordinate coordinate) { Contract.Requires(coordinate != null); String addressLine1 = null, addressLine2 = null, building = null, city = null; String countryRegion = null; String state = null; city = ResolveCity(coordinate, out state); if (city == null) { city = "<unknown>"; } double errorThreshold = AllowWideRangeForErrors ? ErrorThresholdForSearching : VeryPreciseErrorThreshold; // @TODO: My data files are a little inconsistent. For Vegas, the building is usually the second option, like loc.Name. // For Microsoft main campus, the building is the point of interest, while the main campus is the name. IList <Location> locs = FindLocations(coordinate, errorThreshold); if (locs.Count > 0) { building = locs[0].Name; if (locs[0].PointOfInterestName != null) { addressLine1 = locs[0].PointOfInterestName; addressLine2 = locs[0].Name; building = locs[0].Name; } else { addressLine1 = building; } if (locs.Count > 1) { foreach (Location loc in locs) { if (loc.PointOfInterestName != null) { addressLine1 = loc.PointOfInterestName; addressLine2 = loc.Name; if (building == null) { building = loc.Name; } break; } } } } CivicAddress address = new CivicAddress(addressLine1, addressLine2, building, city, countryRegion, null, null, state); EventHandler <ResolveAddressCompletedEventArgs> handler = ResolveAddressCompleted; if (handler != null) { ResolveAddressCompletedEventArgs args = new ResolveAddressCompletedEventArgs(address, null, false, null); handler(this, args); } return(address); }
public static async Task Execute(ISession session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var pokestopsTuple = await GetPokeStops(session); pokestopList = pokestopsTuple.Item2; while (pokestopList.Any()) { cancellationToken.ThrowIfCancellationRequested(); await SnipeMSniperTask.CheckMSniperLocation(session, cancellationToken); pokestopList = pokestopList.OrderBy( i => session.Navigation.WalkStrategy.CalculateDistance( session.Client.CurrentLatitude, session.Client.CurrentLongitude, i.Latitude, i.Longitude, session)).ToList(); // randomize next pokestop between first and second by distance var pokestopListNum = 0; if (pokestopList.Count > 1) { pokestopListNum = rc.Next(0, 2); } var pokeStop = pokestopList[pokestopListNum]; pokestopList.RemoveAt(pokestopListNum); // this logic should only be called when we reach a pokestop either via GPX path or normal walking // as when walk-sniping, we want to get to the snipe ASAP rather than stop for lured pokemon upon // calling FarmPokestop; in that situation we are also always within 40m of the pokestop, so no // need to walk to it var fortInfo = await session.Client.Fort.GetFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); // we only move to the PokeStop, and send the associated FortTargetEvent, when not using GPX // also, GPX pathing uses its own EggWalker and calls the CatchPokemon tasks internally. if (!session.LogicSettings.UseGpxPathing) { // Will modify Lat,Lng and Name to fake position SetMoveToTargetTask.CheckSetMoveToTargetStatus(ref fortInfo, ref pokeStop); var eggWalker = new EggWalker(1000, session); var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, session.Client.CurrentLongitude, pokeStop.Latitude, pokeStop.Longitude); cancellationToken.ThrowIfCancellationRequested(); if (!session.LogicSettings.UseGoogleWalk && !session.LogicSettings.UseYoursWalk) { session.EventDispatcher.Send(new FortTargetEvent { Name = fortInfo.Name, Distance = distance, Route = "NecroBot2" }); } else { BaseWalkStrategy.FortInfo = fortInfo; } await session.Navigation.Move(new GeoCoordinate(pokeStop.Latitude, pokeStop.Longitude, LocationUtils.getElevation(session, pokeStop.Latitude, pokeStop.Longitude)), async() => { if (SetMoveToTargetTask.CheckStopforSetMoveToTarget()) { return(false); } // Catch normal map Pokemon await CatchNearbyPokemonsTask.Execute(session, cancellationToken); //Catch Incense Pokemon await CatchIncensePokemonsTask.Execute(session, cancellationToken); // Minor fix google route ignore pokestop await LookPokestops(session, pokeStop, cancellationToken); return(true); }, session, cancellationToken); // we have moved this distance, so apply it immediately to the egg walker. await eggWalker.ApplyDistance(distance, cancellationToken); } if (SetMoveToTargetTask.CheckReachTarget(session)) { return; } await FortAction(session, pokeStop, fortInfo, cancellationToken); if (session.LogicSettings.SnipeAtPokestops || session.LogicSettings.UseSnipeLocationServer) { await SnipePokemonTask.Execute(session, cancellationToken); } if (session.LogicSettings.EnableHumanWalkingSnipe) { //refactore to move this code inside the task later. await HumanWalkSnipeTask.Execute(session, cancellationToken, async (double lat, double lng) => { //idea of this function is to spin pokestop on way. maybe risky. var reachablePokestops = pokestopList.Where(i => LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, session.Client.CurrentLongitude, i.Latitude, i.Longitude) < 40 && i.CooldownCompleteTimestampMs == 0 ).ToList(); reachablePokestops = reachablePokestops.OrderBy(i => LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, session.Client.CurrentLongitude, i.Latitude, i.Longitude)).ToList(); foreach (var ps in reachablePokestops) { if (!session.LogicSettings.UseGpxPathing) { pokestopList.Remove(ps); } var fi = await session.Client.Fort.GetFort(ps.Id, ps.Latitude, ps.Longitude); await FarmPokestop(session, ps, fi, cancellationToken, true); await Task.Delay(2000); } }, async() => { // if using GPX we have to move back to the original pokestop, to resume the path. // we do not try to use pokest;ops on the way back, as we will have used them getting // here. if (session.LogicSettings.UseGpxPathing) { var eggWalker = new EggWalker(1000, session); var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, session.Client.CurrentLongitude, pokeStop.Latitude, pokeStop.Longitude); var geo = new GeoCoordinate(pokeStop.Latitude, pokeStop.Longitude); await session.Navigation.Move(geo, async() => { await CatchNearbyPokemonsTask.Execute(session, cancellationToken); //Catch Incense Pokemon await CatchIncensePokemonsTask.Execute(session, cancellationToken); return(true); }, session, cancellationToken); await eggWalker.ApplyDistance(distance, cancellationToken); return; } var nearestStop = pokestopList.OrderBy(i => LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, session.Client.CurrentLongitude, i.Latitude, i.Longitude)).FirstOrDefault(); var walkedDistance = LocationUtils.CalculateDistanceInMeters(nearestStop.Latitude, nearestStop.Longitude, session.Client.CurrentLatitude, session.Client.CurrentLongitude); if (walkedDistance > session.LogicSettings.HumanWalkingSnipeWalkbackDistanceLimit) { await Task.Delay(3000); var nearbyPokeStops = await UpdateFortsData(session); var notexists = nearbyPokeStops.Where(p => !pokestopList.Any(x => x.Id == p.Id)).ToList(); pokestopList.AddRange(notexists); session.EventDispatcher.Send(new PokeStopListEvent { Forts = pokestopList }); session.EventDispatcher.Send(new HumanWalkSnipeEvent() { Type = HumanWalkSnipeEventTypes.PokestopUpdated, Pokestops = notexists, NearestDistance = walkedDistance }); } }); } } }
public async void DoStuffAsync() { try { timerGetATC.Stop(); clients = await Context.FaStatusServer.GetAsync <Clients>("clients", false, "{\"clienttype\":\"ATC\"}"); } catch (Exception) { DoStuffAsync(); } finally { lstATC.Items.Clear(); if (clients.Count > 0) { foreach (var item in clients) { GeoCoordinate Location2 = new GeoCoordinate(Convert.ToDouble(item.location[1].Replace(".", ",")), Convert.ToDouble(item.location[0].Replace(".", ","))); string distance = (Convert.ToInt32(t.Location.GetDistanceTo(Location2)) * 0.000539956803).ToString("F0"); string[] split = item.callsign.ToString().Split('_'); foreach (string word in split) { switch (word) { case "FSS": if (Convert.ToInt32(distance) < 2000) { lstATC.Items.Add(new ListViewItem(new string[] { item.callsign.ToString(), item.frequency.ToString(), item.realname.ToString(), distance + " NM" })); lstATC.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); lstATC.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); } else { Console.WriteLine("FSS // Nothing on your Range"); } break; case "CTR": if (Convert.ToInt32(distance) < 500) { lstATC.Items.Add(new ListViewItem(new string[] { item.callsign.ToString(), item.frequency.ToString(), item.realname.ToString(), distance + " NM" })); lstATC.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); lstATC.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); } else { Console.WriteLine("CTR // Nothing on your Range"); } break; case "APP": if (Convert.ToInt32(distance) < 100) { lstATC.Items.Add(new ListViewItem(new string[] { item.callsign.ToString(), item.frequency.ToString(), item.realname.ToString(), distance + " NM" })); lstATC.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); lstATC.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); } else { Console.WriteLine("APP // Nothing on your Range"); } break; case "DEP": if (Convert.ToInt32(distance) < 100) { lstATC.Items.Add(new ListViewItem(new string[] { item.callsign.ToString(), item.frequency.ToString(), item.realname.ToString(), distance + " NM" })); lstATC.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); lstATC.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); } else { Console.WriteLine("DEP // Nothing on your Range"); } break; case "TWR": if (Convert.ToInt32(distance) < 30) { lstATC.Items.Add(new ListViewItem(new string[] { item.callsign.ToString(), item.frequency.ToString(), item.realname.ToString(), distance + " NM" })); lstATC.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); lstATC.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); } else { Console.WriteLine("TWR // Nothing on your Range"); } break; case "GND": if (Convert.ToInt32(distance) < 10) { lstATC.Items.Add(new ListViewItem(new string[] { item.callsign.ToString(), item.frequency.ToString(), item.realname.ToString(), distance + " NM" })); lstATC.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); lstATC.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); } else { Console.WriteLine("GND // Nothing on your Range"); } break; case "DEL": if (Convert.ToInt32(distance) < 10) { lstATC.Items.Add(new ListViewItem(new string[] { item.callsign.ToString(), item.frequency.ToString(), item.realname.ToString(), distance + " NM" })); lstATC.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); lstATC.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); } else { Console.WriteLine("DEL // Nothing on your Range"); } break; default: break; } } } } timerGetATC.Start(); } }
private static bool IsWithinBoundingBox(GeoCoordinate coordinate, GeoCoordinate corner1, GeoCoordinate corner2, double errorThreshold) { double lat1 = corner1.Latitude, lat2 = corner2.Latitude; if (lat1 < lat2) { double tmp = lat1; lat1 = lat2; lat2 = tmp; } double long1 = corner1.Longitude, long2 = corner2.Longitude; if (long1 < long2) { double tmp = long1; long1 = long2; long2 = tmp; } Contract.Assert(lat1 >= lat2, "Latitudes don't line up"); Contract.Assert(long1 >= long2, "Longitudes don't line up"); return((lat1 + errorThreshold >= coordinate.Latitude && coordinate.Latitude >= lat2 - errorThreshold) && (long1 + errorThreshold >= coordinate.Longitude && coordinate.Longitude >= long2 - errorThreshold)); }
/// <summary> /// Called when the map was first initialized. /// </summary> /// <param name="mapView">Map view.</param> /// <param name="newZoom">New zoom.</param> /// <param name="newTilt">New tilt.</param> /// <param name="newCenter">New center.</param> private void _mapView_MapInitialized(OsmSharp.UI.IMapView mapView, float newZoom, OsmSharp.Units.Angle.Degree newTilt, GeoCoordinate newCenter) { // make sure the center marker stays in place from now on. _centerMarker.MoveWithMap = false; }
public async Task DoWalk(List <GeoCoordinate> points, ISession session, Func <Task> functionExecutedWhileWalking, GeoCoordinate sourceLocation, GeoCoordinate targetLocation, CancellationToken cancellationToken, double walkSpeed = 0.0) { var currentLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude, _client.CurrentAltitude); //filter google defined waypoints and remove those that are too near to the previous ones var waypointsDists = new Dictionary <Tuple <GeoCoordinate, GeoCoordinate>, double>(); var minWaypointsDistance = RandomizeStepLength(_minStepLengthInMeters); for (var i = 0; i < points.Count; i++) { if (i > 0) { var dist = LocationUtils.CalculateDistanceInMeters(points[i - 1], points[i]); waypointsDists[new Tuple <GeoCoordinate, GeoCoordinate>(points[i - 1], points[i])] = dist; } } var tooNearPoints = waypointsDists.Where(kvp => kvp.Value < minWaypointsDistance) .Select(kvp => kvp.Key.Item1) .ToList(); foreach (var tooNearPoint in tooNearPoints) { points.Remove(tooNearPoint); } if (points.Any()) //check if first waypoint is the current location (this is what google returns), in such case remove it! { var firstStep = points.First(); if (firstStep == currentLocation) { points.Remove(points.First()); } } Points = points; var walkedPointsList = new List <GeoCoordinate>(); foreach (var nextStep in points) { currentLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); if (_currentWalkingSpeed <= 0) { _currentWalkingSpeed = session.LogicSettings.WalkingSpeedInKilometerPerHour; } if (session.LogicSettings.UseWalkingSpeedVariant && walkSpeed == 0) { _currentWalkingSpeed = session.Navigation.VariantRandom(session, _currentWalkingSpeed); } var speedInMetersPerSecond = (walkSpeed > 0 ? walkSpeed : _currentWalkingSpeed) / 3.6; var nextStepBearing = LocationUtils.DegreeBearing(currentLocation, nextStep); //particular steps are limited by minimal length, first step is calculated from the original speed per second (distance in 1s) var nextStepDistance = Math.Max(RandomizeStepLength(_minStepLengthInMeters), speedInMetersPerSecond); var waypoint = await LocationUtils.CreateWaypoint(currentLocation, nextStepDistance, nextStepBearing).ConfigureAwait(false); walkedPointsList.Add(waypoint); var previousLocation = currentLocation; //store the current location for comparison and correction purposes var requestSendDateTime = DateTime.Now; await LocationUtils.UpdatePlayerLocationWithAltitude(session, waypoint, (float)speedInMetersPerSecond).ConfigureAwait(false); var realDistanceToTarget = LocationUtils.CalculateDistanceInMeters(currentLocation, targetLocation); if (realDistanceToTarget < 2) { break; } do { cancellationToken.ThrowIfCancellationRequested(); TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested(); var msToPositionChange = (DateTime.Now - requestSendDateTime).TotalMilliseconds; currentLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var currentDistanceToWaypoint = LocationUtils.CalculateDistanceInMeters(currentLocation, nextStep); realDistanceToTarget = LocationUtils.CalculateDistanceInMeters(currentLocation, targetLocation); var realSpeedinMperS = nextStepDistance / (msToPositionChange / 1000); var realDistanceWalked = LocationUtils.CalculateDistanceInMeters(previousLocation, currentLocation); //if the real calculated speed is lower than the one expected, we will raise the speed for the following step double speedRaise = 0; if (realSpeedinMperS < speedInMetersPerSecond) { speedRaise = speedInMetersPerSecond - realSpeedinMperS; } double distanceRaise = 0; if (realDistanceWalked < nextStepDistance) { distanceRaise = nextStepDistance - realDistanceWalked; } var realDistanceToTargetSpeedDown = LocationUtils.CalculateDistanceInMeters(currentLocation, targetLocation); if (realDistanceToTargetSpeedDown < 40) { if (speedInMetersPerSecond > SpeedDownTo) { speedInMetersPerSecond = SpeedDownTo; } } if (session.LogicSettings.UseWalkingSpeedVariant && walkSpeed == 0) { _currentWalkingSpeed = session.Navigation.VariantRandom(session, _currentWalkingSpeed); speedInMetersPerSecond = _currentWalkingSpeed / 3.6; } speedInMetersPerSecond += speedRaise; if (walkSpeed > 0) { speedInMetersPerSecond = walkSpeed / 3.6; } nextStepBearing = LocationUtils.DegreeBearing(currentLocation, nextStep); //setting next step distance is limited by the target and the next waypoint distance (we don't want to miss them) //also the minimal step length is used as we don't want to spend minutes jumping by cm lengths nextStepDistance = Math.Min(Math.Min(realDistanceToTarget, currentDistanceToWaypoint), //also add the distance raise (bot overhead corrections) to the normal step length Math.Max(RandomizeStepLength(_minStepLengthInMeters) + distanceRaise, (msToPositionChange / 1000) * speedInMetersPerSecond) + distanceRaise); int timeToWalk = (int)((nextStepDistance * 1000) / speedInMetersPerSecond); //Logger.Debug($"nextStepDistance {nextStepDistance} need {timeToWalk} ms"); waypoint = await LocationUtils.CreateWaypoint(currentLocation, nextStepDistance, nextStepBearing).ConfigureAwait(false); walkedPointsList.Add(waypoint); //store the current location for comparison and correction purposes previousLocation = currentLocation; requestSendDateTime = DateTime.Now; await LocationUtils.UpdatePlayerLocationWithAltitude(session, waypoint, (float)speedInMetersPerSecond).ConfigureAwait(false); UpdatePositionEvent?.Invoke(session, waypoint.Latitude, waypoint.Longitude, _currentWalkingSpeed); await Task.Delay(timeToWalk).ConfigureAwait(false); if (functionExecutedWhileWalking != null) { await functionExecutedWhileWalking().ConfigureAwait(false); // look for pokemon } } while (LocationUtils.CalculateDistanceInMeters(currentLocation, nextStep) >= 2); UpdatePositionEvent?.Invoke(session, nextStep.Latitude, nextStep.Longitude, _currentWalkingSpeed); } }
/// <summary> /// Sets the map view. /// </summary> /// <param name="center">Center.</param> /// <param name="mapTilt">Map tilt.</param> /// <param name="mapZoom">Map zoom.</param> void IMapView.SetMapView(GeoCoordinate center, Degree mapTilt, float mapZoom) { _mapView.SetMapView(center, mapTilt, mapZoom); }
/// <summary> /// Initializes the View property. /// </summary> public override void LoadView() { base.LoadView(); // initialize OsmSharp native hooks. Native.Initialize(); // enable the loggging. OsmSharp.Logging.Log.Enable(); OsmSharp.Logging.Log.RegisterListener(new OsmSharp.iOS.UI.Log.ConsoleTraceListener()); // initialize map. var map = new Map(); // add a tile layer. map.AddLayer(new LayerTile(@"http://192.168.43.155:1234/default/{0}/{1}/{2}.png")); // map.AddLayer(new LayerMBTile(SQLiteConnection.CreateFrom( // Assembly.GetExecutingAssembly().GetManifestResourceStream(@"OsmSharp.iOS.UI.Sample.kempen.mbtiles"), "map"))); // add an online osm-data->mapCSS translation layer. //map.AddLayer(new OsmLayer(dataSource, mapCSSInterpreter)); // add a pre-processed vector data file. // var sceneStream = Assembly.GetExecutingAssembly().GetManifestResourceStream( // "OsmSharp.iOS.UI.Sample.default.map"); // map.AddLayer(new LayerScene(Scene2D.Deserialize(sceneStream, true))); // var primitivesLayer = new LayerPrimitives(map.Projection); // primitivesLayer.AddPoint(new GeoCoordinate(51.26371, 4.78601), 10, // SimpleColor.FromKnownColor(KnownColor.Blue).Value); // map.AddLayer(primitivesLayer); // // define dummy from and to points. var from = new GeoCoordinate(51.261203, 4.780760); var to = new GeoCoordinate(51.267797, 4.801362); // // // deserialize the pre-processed graph. // var routingSerializer = new CHEdgeDataDataSourceSerializer(false); // TagsCollectionBase metaData = null; // var graphStream = Assembly.GetExecutingAssembly().GetManifestResourceStream( // "OsmSharp.iOS.UI.Sample.kempen-big.osm.pbf.routing"); // var graphDeserialized = routingSerializer.Deserialize(graphStream, out metaData, true); // // // initialize router. // _router = Router.CreateCHFrom(graphDeserialized, new CHRouter(), new OsmRoutingInterpreter()); // // // resolve points. // RouterPoint routerPoint1 = _router.Resolve(Vehicle.Car, from); // RouterPoint routerPoint2 = _router.Resolve(Vehicle.Car, to); // // // calculate route. // Route route = _router.Calculate(Vehicle.Car, routerPoint1, routerPoint2); // RouteTracker routeTracker = new RouteTracker(route, new OsmRoutingInterpreter()); // _enumerator = route.GetRouteEnumerable(10).GetEnumerator(); // // // add a router layer. // _routeLayer = new LayerRoute(map.Projection); // _routeLayer.AddRoute (route, SimpleColor.FromKnownColor(KnownColor.Blue, 125).Value, 12); // map.AddLayer(_routeLayer); // define the mapview. _mapView = new MapView(); //_mapView.MapTapEvent += new MapViewEvents.MapTapEventDelegate(_mapView_MapTapEvent); _mapView.MapAllowTilt = false; _mapView.Map = map; _mapView.MapMaxZoomLevel = 19; _mapView.MapMinZoomLevel = 0; _mapView.MapTilt = 0; _mapView.MapCenter = new GeoCoordinate(51.2633, 4.7853); _mapView.MapZoom = 18; _mapView.MapInitialized += _mapView_MapInitialized; // add markers. var marker = _mapView.AddMarker(from); var popupTextView = new UITextView(); popupTextView.Text = "Hey, this is popup text!"; popupTextView.BackgroundColor = UIColor.FromWhiteAlpha(0.5f, 0.5f); marker.AddPopup(popupTextView, 100, 100); marker = _mapView.AddMarker(to); popupTextView = new UITextView(); popupTextView.Text = "Hey, this is another popup text!"; popupTextView.BackgroundColor = UIColor.FromWhiteAlpha(0.5f, 0.5f); marker.AddPopup(popupTextView, 100, 100); this.AddMarkers(); // add center marker. _centerMarker = _mapView.AddMarker(_mapView.MapCenter); // create the route tracker animator. // _routeTrackerAnimator = new RouteTrackerAnimator(_mapView, routeTracker, 5, 17); // // simulate a number of gps-location update along the calculated route. // Timer timer = new Timer(250); // timer.Elapsed += new ElapsedEventHandler(TimerHandler); // timer.Start(); View = _mapView; }