コード例 #1
0
        /// <summary>
        ///     Starts processing of nmea file using passed delay action.
        ///     Send GeoPosition message to message bus.
        /// </summary>
        public void Start(Action<TimeSpan> delayAction)
        {
            _positionDateTime = null;
            _position = new GeoPosition();
            string line;
            _isStarted = true;
            while ((line = _parser.ReadLine()) != null)
            {
                if (!_isStarted) break;

                if (line.Length <= 0) continue;

                var message = _parser.ParseLine(line);
                if (message == null || !CanSetPositionFromMessage(message) || _position.Date.Year < 2001)
                    continue;

                DateTime currentDateTime = _position.DateTime;
                if (_positionDateTime != null)
                {
                    var sleepTime = currentDateTime - _positionDateTime.Value;
                    delayAction(sleepTime);
                    _messageBus.Send(_position);
                }
                _positionDateTime = currentDateTime;
            }
            _isStarted = false;
            FireDone();
        }
コード例 #2
0
ファイル: App.xaml.cs プロジェクト: Hitchhikrr/OpenStreetApp
        public App()
        {
            UnhandledException += Application_UnhandledException;

            if (System.Diagnostics.Debugger.IsAttached)
            {
                // Zähler für die aktuelle Bildrate anzeigen.
                //Application.Current.Host.Settings.EnableFrameRateCounter = true;

                // Bereiche der Anwendung hervorheben, die mit jedem Bild neu gezeichnet werden.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // Nicht produktiven Visualisierungsmodus für die Analyse aktivieren, 
                // in dem GPU-beschleunigte Bereiche der Seite farbig hervorgehoben werden.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;
            }

            InitializeComponent();

            InitializePhoneApplication();

            if (Microsoft.Devices.Environment.DeviceType == Microsoft.Devices.DeviceType.Emulator)
                lastKnownPosition = new GeoPosition<GeoCoordinate>(DateTimeOffset.Now, 
                    new GeoCoordinate(48.422362, 9.957327));
        }
コード例 #3
0
 public void ChangePosition(DateTimeOffset offset, GeoCoordinate coordinate)
 {
     Position = new GeoPosition<GeoCoordinate>(offset, coordinate);
     if (PositionChanged != null)
     {
         PositionChanged(null, new GeoPositionChangedEventArgs<GeoCoordinate>(Position));
     }
 }
コード例 #4
0
ファイル: Pushpin.cs プロジェクト: qtstc/weassist
 public Pushpin(GeoPosition<GeoCoordinate> position, string type, GeoPosition<GeoCoordinate> referencePosition = null, RoutedEventHandler pushpinEvent = null)
 {
     _referencePosition = referencePosition;
     _pushpinEvent = pushpinEvent;
     _position = position;
     _type = type;
     _pushpinOverlay = GetPushpinOverlay();
 }
コード例 #5
0
 private void OnPositionAvailable(GeoPosition<GeoCoordinate> position)
 {
     if (PositionAvailable != null)
     {
         Deployment.Current.Dispatcher.BeginInvoke(() =>
                 PositionAvailable(this, new EventArgs<Location>(new Location(position.Location.Latitude, position.Location.Longitude))));
     }
 }
コード例 #6
0
ファイル: ParseContract.cs プロジェクト: qtstc/weassist
 /// <summary>
 /// Use a GeoPosition instance to populate a ParseObject
 /// </summary>
 /// <param name="g">the GeoPosition</param>
 /// <param name="p">the ParseObject</param>
 public static void GeoPositionSetParseObject(GeoPosition<GeoCoordinate> g, ParseObject p)
 {
     p[LOCATION] = new ParseGeoPoint(ToParseNaN(g.Location.Latitude), ToParseNaN(g.Location.Longitude));
     p[TIME_STAMP] = g.Timestamp.DateTime;
     p[ALTITUDE] = ToParseNaN(g.Location.Altitude);
     p[HORIZONTAL_ACCURACY] = ToParseNaN(g.Location.HorizontalAccuracy);
     p[VERTICAL_ACCURACY] = ToParseNaN(g.Location.VerticalAccuracy);
     p[SPEED] = ToParseNaN(g.Location.Speed);
     p[COURSE] = ToParseNaN(g.Location.Course);
 }
コード例 #7
0
ファイル: MainPage.xaml.cs プロジェクト: nyghtrocker/Blog
        void myWatcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
             myPosition = myWatcher.Position;
             currentLocation = myWatcher.Position.Location;
             if (isInDriveMode)
             {
                 DrawMyCurrentRoute(currentLocation);
             }

             LocationManager.GetLocationName(UpdateLocation, myPosition.Location.Latitude.ToString(), myPosition.Location.Longitude.ToString());
        }
コード例 #8
0
ファイル: IPSUtils.cs プロジェクト: andresrobinson/ivaps
        private const double R = 3440; //miglia nautiche

        #endregion Fields

        #region Methods

        /// <summary>
        /// Calcola la distanza in MIGLIA NAUTICHE (nm) tra due punti geografici. Il calcolo è svolto con la
        /// formula di Aversine
        /// </summary>
        /// <param name="pos1">punto uno</param>
        /// <param name="pos2">punto 2</param>
        /// <returns>la distanza in miglia nautiche</returns>
        public static double CalulateDistance(GeoPosition pos1, GeoPosition pos2)
        {
            double dLat = toRadian(pos2.Latitude - pos1.Latitude);
            double dLon = toRadian(pos2.Longitude - pos1.Longitude);
            double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
                Math.Cos(toRadian(pos1.Latitude)) * Math.Cos(toRadian(pos2.Latitude)) *
                Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
            double c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a)));
            double d = R * c;
            return d;
        }
コード例 #9
0
ファイル: ScheduledAgent.cs プロジェクト: wortexx/Footprint
 private Position GetPosition(GeoPosition<GeoCoordinate> position)
 {
     if (position.Location.IsUnknown)
     {
         return null;
     }
     return new Position
                {
                    Latitude = position.Location.Latitude,
                    Longitude = position.Location.Longitude,
                    Speed = position.Location.Speed,
                    UtcTicks = position.Timestamp.UtcTicks
                };
 }
コード例 #10
0
ファイル: GeoPositionTest.cs プロジェクト: p3rl/DotIGC
        public void Construction_with_latitude_smaller_than_90_throws_execption()
        {
            var expectedTimestamp = TimeSpan.Zero;
            double expectedLatitude = -90.5;
            double expectedLongitude = 13.34046;
            double expectedPressureAltitude = 100.0;
            double expectedGpsAltitude = 101.0;
            double expectedCourse = 3.45;
            double expectedSpeed = 30.0;

            var coord = new GeoPosition(expectedTimestamp,
                                        expectedLatitude,
                                        expectedLongitude,
                                        expectedPressureAltitude,
                                        expectedGpsAltitude,
                                        expectedCourse,
                                        expectedSpeed);
        }
コード例 #11
0
ファイル: GeoPositionTest.cs プロジェクト: p3rl/DotIGC
        public void Construction_with_course_lesser_than_zero_throws_execption()
        {
            var expectedTimestamp = TimeSpan.Zero;
            double expectedLatitude = -89.0;
            double expectedLongitude = 13.34046;
            double expectedPressureAltitude = 100.0;
            double expectedGpsAltitude = 101.0;
            double expectedCourse = -3.45;
            double expectedSpeed = 0.1;

            var coord = new GeoPosition(expectedTimestamp,
                                        expectedLatitude,
                                        expectedLongitude,
                                        expectedPressureAltitude,
                                        expectedGpsAltitude,
                                        expectedCourse,
                                        expectedSpeed);
        }
コード例 #12
0
        public float getCurrentWeather(string cityName)
        {
            climaCellAPIEndpoint.endpointType = EndpointType.WEATHER;
            AccuWeatherController accuWeatherController = new AccuWeatherController();
            GeoPosition           geoPosition           = accuWeatherController.getGeoPosition(cityName);
            float temperature = 0f;

            string response = getResponse(climaCellAPIEndpoint.getCurrentWeather(geoPosition.Latitude, geoPosition.Longitude));

            System.Diagnostics.Debug.WriteLine(response);

            using (JsonParser <ClimaCellAPIModel> jsonParser = new JsonParser <ClimaCellAPIModel>())
            {
                ClimaCellAPIModel climaCellAPIModel = new ClimaCellAPIModel();
                climaCellAPIModel = jsonParser.parse(response, netCoreVersion);

                temperature = climaCellAPIModel.temp.value;
            }

            return(temperature);
        }
コード例 #13
0
        public float getCurrentWeather(string cityName)
        {
            darkSkyAPIEndpoint.endpointType = EndpointType.FORECAST;
            AccuWeatherController accuWeatherController = new AccuWeatherController();
            GeoPosition           geoPosition           = accuWeatherController.getGeoPosition(cityName);
            float temperature = 0f;

            string response = getResponse(darkSkyAPIEndpoint.getWeatherForecast(geoPosition.Latitude, geoPosition.Longitude));

            System.Diagnostics.Debug.WriteLine(response);

            using (JsonParser <DarkSkyAPIForecastModel> jsonParser = new JsonParser <DarkSkyAPIForecastModel>())
            {
                DarkSkyAPIForecastModel darkSkyCurrentWeatherModel = new DarkSkyAPIForecastModel();
                darkSkyCurrentWeatherModel = jsonParser.parse(response, netCoreVersion);

                temperature = darkSkyCurrentWeatherModel.currently.temperature;
            }

            return(temperature);
        }
コード例 #14
0
        private GPoint MakeGPointFromGeoCoordinatePostion(GeoPosition <GeoCoordinate> position)
        {
            GPoint currentPoint = new GPoint();

            if (position.Location.IsUnknown == false)
            {
                currentPoint.Longitude = position.Location.Longitude;
                currentPoint.Latitude  = position.Location.Latitude;
                currentPoint.Speed     = position.Location.Speed;
                currentPoint.Altitude  = position.Location.Altitude;
                currentPoint.TimeTaken = position.Timestamp;
            }
            else
            {
                currentPoint.Longitude = 0;
                currentPoint.Latitude  = 0;
            }

            System.Diagnostics.Debug.WriteLine(position.Timestamp.ToString());
            return(currentPoint);
        }
コード例 #15
0
        /// <summary>
        /// Callback of the timer. This method will set the new position. In most cases it will add the _dLat and _dLong values
        /// to the current position - to simulate the move in the same directions. When it will hit the city borders, it will generate
        /// new values randomly for the direction. Also the case of where the difference in direction would be zero is not allowed.
        /// </summary>
        /// <param name="obj"></param>
        public void TimerCallBack(Object obj)
        {
            Random r = new Random();
            double newLatitude, newLongitude;

            while (!IsInRange(newLatitude = this.Position.Location.Latitude + _dLat,
                              newLongitude = this.Position.Location.Longitude + _dLong) || (_dLat == 0.0 && _dLong == 0.0))
            {
                _dLat  = (r.NextDouble() - 0.5) * BikeConsts.GPS_SIMULATOR_STEP;
                _dLong = (r.NextDouble() - 0.5) * BikeConsts.GPS_SIMULATOR_STEP;
            }

            //set new position
            _position = new GeoPosition <GeoCoordinate>(DateTime.Now, new GeoCoordinate(newLatitude, newLongitude));

            //fire the event if there are any subscribers
            if (this.PositionChanged != null)
            {
                PositionChanged(this, new GeoPositionChangedEventArgs <GeoCoordinate>(this.Position));
            }
        }
コード例 #16
0
        public PagedResult <SellerMobileGrid> RetrieveSellersByGeoLocation(double latitude, double longitude, string pincode, List <OrderBy> orderBy = null, Paging paging = null)
        {
            var sellerList = new List <SellerMobileGrid>();
            var sellers    = _dataService.RetrievePagedResult <SellerMobileGrid>(s => s.Pincode == pincode);

            foreach (var seller in sellers.Items)
            {
                var startPosition = new GeoPosition()
                {
                    Latitude = latitude, Longitude = longitude
                };
                var endPosition = new GeoPosition()
                {
                    Latitude = seller.Latitude ?? 0.0, Longitude = seller.Longitude ?? 0.0
                };
                var sellerDistance = _googleBusinessService.RetrieveDistanceInKilometer(startPosition, endPosition);
                seller.SellerDistance = Convert.ToDecimal(sellerDistance);
                sellerList.Add(seller);
            }
            return(sellerList.AsQueryable().OrderBy(orderBy).Paginate(paging));
        }
コード例 #17
0
        public void setRobotPositionAndDirection(GeoPosition pos, Direction dir)
        {
            MapperVicinity mapperVicinity = CurrentMapper;

            if (pos != null)
            {
                mapperVicinity.robotPosition = (GeoPosition)pos.Clone();
            }

            if (dir != null)
            {
                mapperVicinity.robotDirection = (Direction)dir.Clone();
            }

            // --------- debug ------------

            /*
             * GeoPosition pos1 = (GeoPosition)pos.Clone();
             *
             * pos1.translate(new Distance(1.0d), new Distance(1.0d));     // robot coordinates - right forward
             *
             * DetectedObstacle dobst1 = new DetectedObstacle(pos1) { color = Colors.Red };
             *
             * mapperVicinity.AddDetectedObject(dobst1);
             *
             * GeoPosition pos2 = (GeoPosition)pos.Clone();
             *
             * pos2.translate(new Distance(-1.0d), new Distance(1.0d));     // robot coordinates - left forward
             *
             * DetectedObstacle dobst2 = new DetectedObstacle(pos2) { color = Colors.Yellow };
             *
             * mapperVicinity.AddDetectedObject(dobst2);
             *
             * mapperVicinity.computeMapPositions();
             */
            // --------- end debug ------------

            RedrawMap();
        }
コード例 #18
0
 private void addCurrentGpsPoint()
 {
     if (IsPause)
     {
         return;
     }
     if (isGPSReady())
     {
         GeoPosition <GeoCoordinate> myPosition = myWatcher.Position;
         var location = new GPSPoint((float)myPosition.Location.Latitude,
                                     (float)myPosition.Location.Longitude,
                                     (float)myPosition.Location.Altitude, CurrentSpeed.HasValue?(float)CurrentSpeed.Value:float.NaN,
                                     (float)getCurrentDuration());
         viewModel.Points.Add(location);
         viewModel.RetrieveWeather(location);
     }
     else
     {
         //mark last point as lost connection
         addNotAvailablePoint(false);
     }
 }
コード例 #19
0
        public void GeoLocation_IsValid()
        {
            var l = new GeoPosition(0.0, 0.0);

            Assert.IsTrue(l.IsValidLocation);

            l.Latitude  = -91;
            l.Longitude = -180;
            Assert.IsFalse(l.IsValidLocation);

            l.Latitude  = 91;
            l.Longitude = 180;
            Assert.IsFalse(l.IsValidLocation);

            l.Latitude  = -90;
            l.Longitude = -181;
            Assert.IsFalse(l.IsValidLocation);

            l.Latitude  = 90;
            l.Longitude = 181;
            Assert.IsFalse(l.IsValidLocation);
        }
コード例 #20
0
        public override Task <IEnumerable <IAircraft> > GetAirplanes(GeoPosition centerPosition = null, double radiusDistanceKilometers = 100, bool cacheEnabled = true, string customUrl = "")
        {
            if (centerPosition == null)
            {
                throw new ArgumentException("FlightRadar24 requires the 'centerPosition' parameter.");
            }

            // TO DO Convert this dumb distance to real Lat/Lon distance.
            double rectangleDistance = radiusDistanceKilometers / 100;

            var newUrl = url
                         .Replace("@latNorth", (centerPosition.Latitude - rectangleDistance).ToString(CultureInfo.InvariantCulture))
                         .Replace("@latSouth", (centerPosition.Latitude + rectangleDistance).ToString(CultureInfo.InvariantCulture))
                         .Replace("@lonWest", (centerPosition.Longitude - rectangleDistance).ToString(CultureInfo.InvariantCulture))
                         .Replace("@lonEst", (centerPosition.Longitude + rectangleDistance).ToString(CultureInfo.InvariantCulture));

            return(base.GetAirplanes(
                       centerPosition: centerPosition,
                       radiusDistanceKilometers: 0,
                       cacheEnabled: cacheEnabled,
                       customUrl: newUrl));
        }
コード例 #21
0
        // ==================================================
        // Constructors
        public GeoCountryData(GeoContinents continent, int id, int division, string iso2, string iso3, string oc, string name, string nameLong, string local, string localLong, string abbr10, string abbr15, string abbr30, double latCenter, double lonCenter, double latNorthWest, double lonNorthWest, double latSouthEast, double lonSouthEast)
        {
            Continent = continent;
            CountryID = id;
            Division  = division;

            ISO2 = iso2.ToUpperInvariant();
            ISO3 = iso3.ToUpperInvariant();
            OC   = oc.ToUpperInvariant();

            Name          = name;
            NameLong      = nameLong;
            NameLocal     = local;
            NameLocalLong = localLong;

            Abbr10 = abbr10;
            Abbr15 = abbr15;
            Abbr30 = abbr30;

            Center = new GeoPosition(latCenter, lonCenter);
            Bounds = new GeoRectangle(latNorthWest, lonNorthWest, latSouthEast, lonSouthEast);
        }
コード例 #22
0
        public virtual void calculateZoomFrom(ISet <GeoPosition> paramSet)
        {
            if (paramSet.Count < 2)
            {
                return;
            }
            int         i           = Zoom;
            Rectangle2D rectangle2D = generateBoundingRect(paramSet, i);
            sbyte       b           = 0;

            while (!ViewportBounds.contains(rectangle2D))
            {
                Point2D.Double double = new Point2D.Double(rectangle2D.X + rectangle2D.Width / 2.0D, rectangle2D.Y + rectangle2D.Height / 2.0D);
                GeoPosition geoPosition = TileFactory.pixelToGeo(double, i);
                CenterPosition = geoPosition;
                if (++b > 30 || ViewportBounds.contains(rectangle2D) || ++i > 15)
                {
                    break;
                }
                Zoom        = i;
                rectangle2D = generateBoundingRect(paramSet, i);
            }
        }
コード例 #23
0
        public static GeoPosition ToGeoPosition(this Android.Locations.Location location)
        {
            var result = new GeoPosition
            {
                Longitude = location.Longitude,
                Latitude  = location.Latitude
            };

            if (location.HasAccuracy)
            {
                result.Accuracy = location.Accuracy;
            }
            if (location.HasAltitude)
            {
                result.Altitude = location.Altitude;
            }
            if (location.HasSpeed)
            {
                result.Speed = location.Speed;
            }

            return(result);
        }
コード例 #24
0
        public Location FindPhotoLocation(FileExtendedInfo finfo)
        {
            Location location = null;

            if (finfo.ExifInfo == null)
            {
                return(null);
            }

            if (finfo.ExifInfo.GPS_Latitude.HasValue && finfo.ExifInfo.GPS_Longitude.HasValue)
            {
                var position = new GeoPosition(finfo.ExifInfo.GPS_Latitude.Value, finfo.ExifInfo.GPS_Longitude.Value);

                location = _locationService.GetLocation(position);
            }

            if (location == null)
            {
                location = _locationService.GetLocation(finfo.RelativePath);
            }

            return(location);
        }
コード例 #25
0
        private void ParseCGA(NmeaMessage message)
        {
            GeoPosition position = new GeoPosition();
            double      longitude = 0, latitude = 0;
            var         f = (NmeaField)message.Fields[GGA.FieldIds.PositionFixIndicator];

            if ((f != null) && f.HasValue)
            {
                position.PositionFixIndicator = f.GetInt(position.PositionFixIndicator);
            }
            f = (NmeaField)message.Fields[GGA.FieldIds.X];
            if ((f != null) && f.HasValue)
            {
                longitude = f.GetDouble(_position.Coordinate.Longitude);
            }
            f = (NmeaField)message.Fields[GGA.FieldIds.Y];
            if ((f != null) && f.HasValue)
            {
                latitude = f.GetDouble(_position.Coordinate.Latitude);
            }
            f = (NmeaField)message.Fields[GGA.FieldIds.Utc];
            if ((f != null) && f.HasValue)
            {
                position.Time = f.GetTime(position.Time);
            }
            f = (NmeaField)message.Fields[GGA.FieldIds.Satelites];
            if ((f != null) && f.HasValue)
            {
                position.Satelites = f.GetInt(position.Satelites);
            }
            f = (NmeaField)message.Fields[GGA.FieldIds.Hdop];
            if ((f != null) && f.HasValue)
            {
                position.Hdop = f.GetInt(position.Hdop);
            }
            _position.Coordinate = new GeoCoordinate((float)latitude, (float)longitude);
        }
コード例 #26
0
        /// <summary>
        ///     Starts processing of nmea file using passed delay action.
        ///     Send GeoPosition message to message bus.
        /// </summary>
        public void Start(Action <TimeSpan> delayAction)
        {
            _positionDateTime = null;
            _position         = new GeoPosition();
            string line;

            _isStarted = true;
            while ((line = _parser.ReadLine()) != null)
            {
                if (!_isStarted)
                {
                    break;
                }

                if (line.Length <= 0)
                {
                    continue;
                }

                var message = _parser.ParseLine(line);
                if (message == null || !CanSetPositionFromMessage(message) || _position.Date.Year < 2001)
                {
                    continue;
                }

                DateTime currentDateTime = _position.DateTime;
                if (_positionDateTime != null)
                {
                    var sleepTime = currentDateTime - _positionDateTime.Value;
                    delayAction(sleepTime);
                    _messageBus.Send(_position);
                }
                _positionDateTime = currentDateTime;
            }
            _isStarted = false;
            FireDone();
        }
コード例 #27
0
        public List <Weather2020Forecast> getForecast(string cityName)
        {
            AccuWeatherController accuWeatherController = new AccuWeatherController();

            List <Weather2020Forecast> forecastList = new List <Weather2020Forecast>();

            GeoPosition geoPosition = accuWeatherController.getGeoPosition(cityName);
            string      response    = getResponse(weather2020APIEndpoint.getWeatherForecast(geoPosition.Latitude, geoPosition.Longitude));

            System.Diagnostics.Debug.WriteLine(response);

            using (JsonParser <List <Weather2020APIModel> > jsonParser = new JsonParser <List <Weather2020APIModel> >())
            {
                List <Weather2020APIModel> weather2020APIModel = new List <Weather2020APIModel>();
                weather2020APIModel = jsonParser.parse(response, netCoreVersion);

                foreach (Weather2020APIModel forecast in weather2020APIModel)
                {
                    forecastList.Add(new Weather2020Forecast(forecast.startDate, forecast.temperatureLowCelcius, forecast.temperatureHighCelcius));
                }
            }

            return(forecastList);
        }
コード例 #28
0
        public List <ClimaCellForecast> getForecast(string cityName)
        {
            AccuWeatherController accuWeatherController = new AccuWeatherController();

            List <ClimaCellForecast> forecastList = new List <ClimaCellForecast>();

            GeoPosition geoPosition = accuWeatherController.getGeoPosition(cityName);
            string      response    = getResponse(climaCellAPIEndpoint.getWeatherForecast(geoPosition.Latitude, geoPosition.Longitude));

            System.Diagnostics.Debug.WriteLine(response);

            using (JsonParser <List <ClimaCellForecastModel> > jsonParser = new JsonParser <List <ClimaCellForecastModel> >())
            {
                List <ClimaCellForecastModel> climaCellAPIModel = new List <ClimaCellForecastModel>();
                climaCellAPIModel = jsonParser.parse(response, netCoreVersion);

                foreach (ClimaCellForecastModel forecast in climaCellAPIModel)
                {
                    forecastList.Add(new ClimaCellForecast(forecast.observation_time.value, forecast.temp[0].min.value, forecast.temp[1].max.value));
                }
            }

            return(forecastList);
        }
コード例 #29
0
        /// <summary>
        /// Constructs a simulator which changes current position. Simulates user moving in one directions
        /// until he hits the borders specified by the parameters.
        /// </summary>
        /// <param name="left">Lower left corner of the city</param>
        /// <param name="right">Upper right corner of the city</param>
        /// <param name="interval"></param>
        public GeoCoordinateSimulator(GeoCoordinate center, double radius, int interval)
        {
            _leftCorner  = new GeoCoordinate(center.Latitude - radius, center.Longitude - radius);
            _rightCorner = new GeoCoordinate(center.Latitude + radius, center.Longitude - radius);

            //the values should be in between -180 and 180
            if (_leftCorner.Longitude > 180)
            {
                _leftCorner.Longitude -= 360;
            }

            if (_rightCorner.Longitude > 180)
            {
                _leftCorner.Longitude -= 360;
            }

            //check if the city border parameters are correct
            if (_leftCorner.Latitude > _rightCorner.Latitude ||
                _leftCorner.Longitude > _rightCorner.Longitude)
            {
                throw new ArgumentException("Left corner values should be smaller than right corner values");
            }

            _latRange  = _rightCorner.Latitude - _leftCorner.Latitude;
            _longRange = _rightCorner.Longitude - _leftCorner.Longitude;

            //setting current position to the midle of the city
            _position = new GeoPosition <GeoCoordinate>(DateTime.Now,
                                                        new GeoCoordinate(_leftCorner.Latitude + _latRange / 2, _leftCorner.Longitude + _longRange / 2));

            //set the interval at which the timer should fire
            _interval = interval;

            //simulator can star right when it is created
            Start();
        }
コード例 #30
0
 public void OnPositionChanged(GeoPosition <GeoCoordinate> position)
 {
     if (!position.Location.IsUnknown)
     {
         var message = MessageGeoLive as TLMessage70;
         if (message != null)
         {
             var mediaGeoLive = message.Media as TLMessageMediaGeoLive;
             if (mediaGeoLive != null && mediaGeoLive.Active)
             {
                 var geoPoint = mediaGeoLive.Geo as TLGeoPoint;
                 if (geoPoint != null)
                 {
                     var oldLocation = new GeoCoordinate(geoPoint.Lat.Value, geoPoint.Long.Value);
                     if (oldLocation.GetDistanceTo(position.Location) >= Constants.MinDistanceToUpdateLiveLocation)
                     {
                         var liveLocationService = IoC.Get <ILiveLocationService>();
                         liveLocationService.UpdateAsync(message,
                                                         new TLGeoPoint
                         {
                             Lat  = new TLDouble(position.Location.Latitude),
                             Long = new TLDouble(position.Location.Longitude)
                         },
                                                         result => Execute.BeginOnUIThread(() =>
                         {
                             mediaGeoLive.EditDate = message.EditDate;
                             mediaGeoLive.NotifyOfPropertyChange(() => mediaGeoLive.Geo);
                             mediaGeoLive.NotifyOfPropertyChange(() => mediaGeoLive.EditDate);
                             mediaGeoLive.NotifyOfPropertyChange(() => mediaGeoLive.Active);
                         }));
                     }
                 }
             }
         }
     }
 }
コード例 #31
0
        public ITypeSearch <LocationItemPage> ApplyFilter(ITypeSearch <LocationItemPage> query, NameValueCollection filters)
        {
            var filterString = filters["d"];

            if (!string.IsNullOrWhiteSpace(filterString))
            {
                var stringDistances = filterString.Split(',').ToList();
                if (stringDistances.Any())
                {
                    var userLocation    = GeoPosition.GetUsersLocation().ToFindLocation();
                    var distances       = ParseDistances(stringDistances);
                    var distancesFilter = SearchClient.Instance.BuildFilter <LocationItemPage>();
                    distancesFilter = distances.Aggregate(distancesFilter,
                                                          (current, distance) =>
                                                          current.Or(x => x.Coordinates.WithinDistanceFrom(
                                                                         new GeoLocation(userLocation.Latitude,
                                                                                         userLocation.Longitude),
                                                                         ((int)distance.From.Value).Kilometers(),
                                                                         ((int)distance.To.Value).Kilometers())));
                    query = query.Filter(x => distancesFilter);
                }
            }
            return(query);
        }
コード例 #32
0
ファイル: Cercanos.xaml.cs プロジェクト: alebanzas/GuiaT.WP
        void GetColectivosCercanos()
        {
            ResetUI();
            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                ConnectionError.Visibility = Visibility.Visible;
                Dispatcher.BeginInvoke(() => MessageBox.Show("Ha habido un error intentando acceder a los nuevos datos o no hay conexiones de red disponibles.\nPor favor asegúrese de contar con acceso de red y vuelva a intentarlo."));
                return;
            }

            GeoPosition <GeoCoordinate> currentLocation = PositionService.GetCurrentLocation();

            if (!App.Configuration.IsLocationEnabled)
            {
                Dispatcher.BeginInvoke(() => MessageBox.Show("Para buscar colectivos cercanos, por favor, active la función de localización en la configuración de la aplicación."));
                return;
            }
            if (currentLocation == null)
            {
                Dispatcher.BeginInvoke(() => MessageBox.Show("Para buscar colectivos cercanos, por favor, active la función de localización."));
                return;
            }

            ProgressBar.Show("Buscando más cercanos...");
            if (ViewModel.Items.Count == 0)
            {
                Refreshing.Visibility = Visibility.Visible;
            }
            SetApplicationBarEnabled(false);
            CancelarRequest();

            var client = new HttpClient();

            _httpReq = client.Get("/transporte/cercano".ToApiCallUri());
            _httpReq.BeginGetResponse(HTTPWebRequestCallBack, _httpReq);
        }
コード例 #33
0
        private Location CreateLocation(string address, GeoPosition position,
                                        GeocodingRequestResult response)
        {
            Location location;

            location = new Location();

            location.Id = _locationRepo.GetNewId();

            location.SearchedAddress  = address.RemoveDiacritics();
            location.SearchedPosition = position;
            location.Position         = new GeoPosition(response.results.First().Latitude, response.results.First().Longitude);

            location.Country = response.GetCountry();
            location.City    = response.GetCity();
            location.State   = response.GetState();

            location.DisplayName = BuildDisplayName(location.City, location.State, location.Country);

            var exitingLocation = _locationRepo.GetLocation(location.DisplayName);

            if (exitingLocation != null)
            {
                return(exitingLocation);
            }

            location.Excluded = IsExcludedLocation(location) || IsInHomeArea(location);

            Debug.WriteLine($"New location for {address} {location.Id} {location.DisplayName} ");

            _newLocations.Add(location);
            _locationRepo.Add(location);

            SaveLocations();
            return(location);
        }
コード例 #34
0
        /// <summary>
        /// Searches google for places by name
        /// </summary>
        public ActionResult Search(PlaceSearchModel search)
        {
            var model = InitModel();

            search = search ?? new PlaceSearchModel();
            model.SearchCriteria = search;
            model.SearchResults  = new List <CartoPlaceInfo>();

            if (!String.IsNullOrWhiteSpace(search.Location))
            {
                model.SearchResults = _cartoPlaceService.LookupLocations(search.Location.Trim());
            }
            else if (!String.IsNullOrWhiteSpace(search.Name))
            {
                model.SearchResults = _cartoPlaceService.LookupPlaces(search.Name, search.Country);
            }
            else if (search.Latitude.HasValue && search.Longitude.HasValue)
            {
                var position = new GeoPosition(search.Latitude.Value, search.Longitude.Value);
                model.SearchResults = _cartoPlaceService.LookupLocations(position);
            }

            return(View(model));
        }
コード例 #35
0
 public GeoCoordinateWatcher(GeoPositionAccuracy desiredAccuracy)
 {
     DesiredAccuracy = desiredAccuracy;
       Status = GeoPositionStatus.Initializing;
       Position = new GeoPosition<GeoCoordinate>(DateTimeOffset.Now, InitialPosition);
 }
コード例 #36
0
 internal Geoposition(GeoPosition <GeoCoordinate> position)
 {
     _position                 = position;
     Coordinate.Timestamp      = position.Timestamp;
     Coordinate.PositionSource = PositionSource.Unknown;
 }
コード例 #37
0
    internal static Position GetPosition(GeoPosition<GeoCoordinate> position)
    {
      if (position.Location.IsUnknown)
        return null;

      var p = new Position();
      p.Accuracy = position.Location.HorizontalAccuracy;
      p.Longitude = position.Location.Longitude;
      p.Latitude = position.Location.Latitude;

      if (!Double.IsNaN(position.Location.VerticalAccuracy) && !Double.IsNaN(position.Location.Altitude))
      {
        p.AltitudeAccuracy = position.Location.VerticalAccuracy;
        p.Altitude = position.Location.Altitude;
      }

      if (!Double.IsNaN(position.Location.Course))
        p.Heading = position.Location.Course;

      if (!Double.IsNaN(position.Location.Speed))
        p.Speed = position.Location.Speed;

      p.Timestamp = position.Timestamp;

      return p;
    }
コード例 #38
0
ファイル: GeoPosition.cs プロジェクト: henrikrtfm/Seerefine
 protected bool Equals(GeoPosition other)
 {
     return Longitude.Equals(other.Longitude) && Latitude.Equals(other.Latitude);
 }
コード例 #39
0
ファイル: GpsManager.cs プロジェクト: NoamSheffer/WazeWP7
        private static void readRecordedData()
        {
            String name = "/WazeWP7;component/resources/points.csv";
            StreamResourceInfo ri = App.GetResourceStream(new Uri(name, UriKind.Relative));
            byte[] buffer = new byte[ri.Stream.Length];
            StreamReader sr = new StreamReader(ri.Stream);
            string s = sr.ReadLine();
            while (s != null)
            {
                string[] items = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                double longitude = double.Parse(items[0]);
                double latitude = double.Parse(items[1]);
                double speed = double.Parse(items[2]);
                double course = double.Parse(items[3]);
                DateTime time = DateTime.Parse(items[5]);

                GeoPosition<GeoCoordinate> position = new GeoPosition<GeoCoordinate>();
                position.Location = new GeoCoordinate();
                position.Location.Longitude = longitude;
                position.Location.Latitude = latitude;
                position.Location.Speed = speed;
                position.Location.Course = course;
                position.Timestamp = time;

                points.Add(position);

                s = sr.ReadLine();
            }
        }
コード例 #40
0
ファイル: GpsManager.cs プロジェクト: NoamSheffer/WazeWP7
        private void UpdatePosition(GeoPosition<GeoCoordinate> position)
        {
            try
            {
                int c_pos1 = CibylCallTable.getAddressByName("roadmap_gpsj2me_pos1");
                int c_pos2 = CibylCallTable.getAddressByName("roadmap_gpsj2me_pos2");

                UIWorker.addUIEvent(c_pos1,
                                    (int)(position.Location.Latitude * 1000000),
                                    (int)(position.Location.Longitude * 1000000),
                                    0,
                                    0, false);

                DateTime Now = DateTime.Now.ToUniversalTime();
                DateTime baseTime = new DateTime(1970, 1, 1, 0, 0, 0);
                long currentTimeMillis = (Now - baseTime).Ticks / 10000;

                UIWorker.addUIEvent(c_pos2,
                                    'A',
                                    //(int)(position.Timestamp.Ticks / 1000),
                                    //(int)DateTime.Now.Ticks / 10000 / 1000,
                                    (int)currentTimeMillis / 1000,
                                    (int)(position.Location.Speed * 2), // Convert to ~knots
                                    (int)position.Location.Course, false);

                if (meOnMapMenuItem != null)
                {
                    //meOnMapMenuItem.CallCallback();
                }

            }
            catch (Exception ex)
            {
                Logger.log("Exception in do_async_connect_cb: " + ex);
            }
        }
コード例 #41
0
 public bool IsInside(GeoPosition position)
 {
     return GreatArc.Distance(_center, position) <= _radius;
 }
コード例 #42
0
        private void RaisePositionChangedEvent()
        {
            var eventHandler = PositionChanged;
            var position = _position;

            if (eventHandler != null && position != null)
            {
                _position = null;

                var locationServicePosition = position.ToLocationServicePosition();

                eventHandler(this, new LocationServicePositionChangedEventArgs(locationServicePosition));
            }
        }
コード例 #43
0
 public Distance distanceToWp(GeoPosition myPos)
 {
     return(geoPosition.distanceFrom(myPos));
 }
コード例 #44
0
ファイル: WayPoint.cs プロジェクト: jelknab/FamilieWandelPad
 public WayPoint(GeoPosition routePoint) : base(routePoint.Latitude, routePoint.Longitude)
 {
 }
コード例 #45
0
		private void WatcherOnPositionChanged (object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
		{
			if (e.Position.Location.IsUnknown)
				return;

			bool isRecent = (e.Position.Timestamp - this.start).TotalMilliseconds < this.timeout;

			if (e.Position.Location.HorizontalAccuracy <= this.desiredAccuracy && isRecent)
				this.tcs.TrySetResult (Geolocator.GetPosition (e.Position));

			if (this.bestPosition == null || e.Position.Location.HorizontalAccuracy < this.bestPosition.Location.HorizontalAccuracy)
				this.bestPosition = e.Position;
		}
コード例 #46
0
ファイル: City.cs プロジェクト: sureshpon/TSP
 /// <summary>
 /// Initializes a new instance of the <see cref="City"/> class.
 /// </summary>
 /// <param name="name">The name of the city</param>
 /// <param name="location">The geographic coordinate of the city</param>
 public City(string name, GeoPosition location)
 {
     Name     = name;
     Location = location;
 }
コード例 #47
0
ファイル: MainPage.xaml.cs プロジェクト: frappaa/SunInfo
 void RefreshPosition(GeoPosition<GeoCoordinate> position)
 {
     _currLatitude = new Degree(position.Location.Latitude);
     _currLongitude = new Degree(position.Location.Longitude);
 }
コード例 #48
0
        /// <summary>
        /// Processed the watcher <see cref="GeoCoordinateWatcher.PositionChanged" /> event.
        /// </summary>
        /// <param name="e">The <see cref="GeoPositionChangedEventArgs{GeoCoordinate}" /> instance containing the event data.</param>
        protected override void OnPositionChanged(GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            _position = e.Position;

            if (_reportInterval == 0)
            {
                RaisePositionChangedEvent();
            }
        }
コード例 #49
0
 public Circle(string id, GeoPosition center, Length radius)
 {
     _id = id;
     _center = center;
     _radius = radius;
 }
コード例 #50
0
 private void ParseCGA(NmeaMessage message)
 {
     GeoPosition position = new GeoPosition();
     double longitude = 0, latitude = 0;
     var f = (NmeaField) message.Fields[GGA.FieldIds.PositionFixIndicator];
     if ((f != null) && f.HasValue)
     {
         position.PositionFixIndicator = f.GetInt(position.PositionFixIndicator);
     }
     f = (NmeaField) message.Fields[GGA.FieldIds.X];
     if ((f != null) && f.HasValue)
     {
         longitude = f.GetDouble(_position.Coordinate.Longitude);
     }
     f = (NmeaField) message.Fields[GGA.FieldIds.Y];
     if ((f != null) && f.HasValue)
     {
         latitude = f.GetDouble(_position.Coordinate.Latitude);
     }
     f = (NmeaField) message.Fields[GGA.FieldIds.Utc];
     if ((f != null) && f.HasValue)
     {
         position.Time = f.GetTime(position.Time);
     }
     f = (NmeaField) message.Fields[GGA.FieldIds.Satelites];
     if ((f != null) && f.HasValue)
     {
         position.Satelites = f.GetInt(position.Satelites);
     }
     f = (NmeaField) message.Fields[GGA.FieldIds.Hdop];
     if ((f != null) && f.HasValue)
     {
         position.Hdop = f.GetInt(position.Hdop);
     }
     _position.Coordinate = new GeoCoordinate((float)latitude, (float)longitude);
 }
コード例 #51
0
ファイル: GpsManager.cs プロジェクト: NoamSheffer/WazeWP7
 private void TimerCallbackEmulator(object state)
 {
     if (point_index >= points.Count - 1)
         point_index = 0;
     last_position = points[point_index];
     last_update_time = DateTime.UtcNow;
     UpdatePosition(points[point_index++]);
 }
        public GeoPosition<GeoCoordinate> GetCurrentLocation()
        {
            GeoCoordinateWatcher gcw = new GeoCoordinateWatcher();
            GeoPosition<GeoCoordinate> currentCoordinate = new GeoPosition<GeoCoordinate>();
            currentCoordinate.Location = new GeoCoordinate(47.627903, -122.143185);

            var CurrentLocation = gcw.Position;

            if (!CurrentLocation.Location.IsUnknown)
            {
                currentCoordinate.Location.Latitude = CurrentLocation.Location.Latitude;
                currentCoordinate.Location.Longitude = CurrentLocation.Location.Longitude;
            }

            return currentCoordinate;
        }
コード例 #53
0
ファイル: GpsManager.cs プロジェクト: NoamSheffer/WazeWP7
 public void gps_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
 {
     UpdatePosition(e.Position);
     last_update_time = DateTime.UtcNow;
     last_position = e.Position;
 }
コード例 #54
0
ファイル: ParseContract.cs プロジェクト: qtstc/weassist
            /// <summary>
            /// Convert a ParseObject to its GeoPosition counterpart
            /// </summary>
            /// <param name="p">the ParseObject instance</param>
            /// <returns>the GeoPosition object</returns>
            public static GeoPosition<GeoCoordinate> ParseObjectToGeoPosition(ParseObject p)
            {
                GeoPosition<GeoCoordinate> g = new GeoPosition<GeoCoordinate>();

                g.Timestamp = new DateTimeOffset(p.Get<DateTime>(TIME_STAMP));
                ParseGeoPoint pGeoPoint = p.Get<ParseGeoPoint>(LOCATION);

                g.Location = new GeoCoordinate();
                if (pGeoPoint.Latitude != NaNforParse)
                    g.Location.Latitude = pGeoPoint.Latitude;
                if (pGeoPoint.Longitude != NaNforParse)
                    g.Location.Longitude = pGeoPoint.Longitude;

                Double pAltitude = p.Get<Double>(ALTITUDE);
                if (pAltitude != NaNforParse)
                    g.Location.Altitude = pAltitude;

                Double pHAccuracy = p.Get<Double>(HORIZONTAL_ACCURACY);
                if (pHAccuracy != NaNforParse)
                    g.Location.HorizontalAccuracy = pHAccuracy;

                Double pVAccuracy = p.Get<Double>(VERTICAL_ACCURACY);
                if (pVAccuracy != NaNforParse)
                    g.Location.VerticalAccuracy = pVAccuracy;

                Double pSpeed = p.Get<Double>(SPEED);
                if (pSpeed != NaNforParse)
                    g.Location.Speed = pSpeed;

                Double pCourse = p.Get<Double>(COURSE);
                if (pCourse != NaNforParse)
                    g.Location.Course = pCourse;

                return g;
            }
コード例 #55
0
 public void SelectSectionPoint(Section section, GeoPosition point)
 {
     SelectedSectionPoint = point;
 }
コード例 #56
0
		private void ProcessPosition(GeoPosition<GeoCoordinate> position)
		{
			if (position == null || position.Location == null || position.Location.IsUnknown)
			{
				return;
			}

			// Stores the new valid position.
			DeviceLocation = position.Location;

			// Uses the location's course if the compass is not enabled.
			if (!Compass.IsSupported)
			{
				DeviceHeading = position.Location.Course;
			}
		}
コード例 #57
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public static LocationSearchResult reverseSearch(org.jdesktop.swingx.mapviewer.GeoPosition paramGeoPosition, int paramInt1, int paramInt2) throws Exception
        public static LocationSearchResult reverseSearch(GeoPosition paramGeoPosition, int paramInt1, int paramInt2)
        {
            LocationSearchResult locationSearchResult = new LocationSearchResult();

            locationSearchResult.PlaceList = new List <object>();
            string str = StringUtils.replace("http://nominatim.openstreetmap.org/reverse?format=xml&lat={A}&lon={B}&zoom={C}&addressdetails=1", "{A}", "" + paramGeoPosition.Latitude);

            str = StringUtils.replace(str, "{B}", "" + paramGeoPosition.Longitude);
            double d = paramInt1 * 19.0D / paramInt2;

            paramInt1 = (int)(19.0D - d - 0.5D);
            if (paramInt1 == 0)
            {
                paramInt1 = 1;
            }
            else if (paramInt1 >= 19)
            {
                paramInt1 = 18;
            }
            str = StringUtils.replace(str, "{C}", "" + paramInt1);
            URL           uRL           = new URL(str);
            URLConnection uRLConnection = uRL.openConnection();

            uRLConnection.setRequestProperty("User-agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/2.0.0.9");
            uRLConnection.ConnectTimeout = 4000;
            uRLConnection.ReadTimeout    = 30000;
            Stream    inputStream = uRLConnection.InputStream;
            SAXReader sAXReader   = new SAXReader();
            Document  document    = sAXReader.read(inputStream);
            Element   element     = document.RootElement;

            locationSearchResult.Query_string = element.attributeValue("query_string");
            locationSearchResult.Polygon      = (new bool?(element.attributeValue("polygon")));
            LocationPlace locationPlace = new LocationPlace();

            locationPlace.Lat = "" + paramGeoPosition.Latitude;
            locationPlace.Lon = "" + paramGeoPosition.Longitude;
            System.Collections.IEnumerator iterator = element.elementIterator();
            while (iterator.MoveNext())
            {
                Element element1 = (Element)iterator.Current;
                if (element1.Name.Equals("result"))
                {
                    locationPlace.Place_id     = element1.attributeValue("place_id");
                    locationPlace.Osm_type     = element1.attributeValue("osm_type");
                    locationPlace.Osm_id       = element1.attributeValue("osm_type");
                    locationPlace.Display_name = element1.StringValue;
                    continue;
                }
                if (element1.Name.Equals("addressparts"))
                {
                    System.Collections.IEnumerator iterator1 = element1.elementIterator();
                    while (iterator1.MoveNext())
                    {
                        Element element2 = (Element)iterator1.Current;
                        if (element2.Name.Equals("station"))
                        {
                            locationPlace.Station = element2.StringValue;
                            continue;
                        }
                        if (element2.Name.Equals("road"))
                        {
                            locationPlace.Road = element2.StringValue;
                            continue;
                        }
                        if (element2.Name.Equals("suburb"))
                        {
                            locationPlace.Suburb = element2.StringValue;
                            continue;
                        }
                        if (element2.Name.Equals("village"))
                        {
                            locationPlace.Village = element2.StringValue;
                            continue;
                        }
                        if (element2.Name.Equals("city"))
                        {
                            locationPlace.City = element2.StringValue;
                            continue;
                        }
                        if (element2.Name.Equals("postcode"))
                        {
                            locationPlace.Postcode = element2.StringValue;
                            continue;
                        }
                        if (element2.Name.Equals("country"))
                        {
                            locationPlace.Country = element2.StringValue;
                            continue;
                        }
                        if (element2.Name.Equals("country_code"))
                        {
                            locationPlace.Country_code = element2.StringValue;
                            continue;
                        }
                        if (element2.Name.Equals("county"))
                        {
                            locationPlace.County = element2.StringValue;
                            continue;
                        }
                        if (element2.Name.Equals("state"))
                        {
                            locationPlace.State = element2.StringValue;
                            continue;
                        }
                        if (element2.Name.Equals("hamlet"))
                        {
                            locationPlace.Hamlet = element2.StringValue;
                            continue;
                        }
                        if (element2.Name.Equals("town"))
                        {
                            locationPlace.Town = element2.StringValue;
                            continue;
                        }
                        if (element2.Name.Equals("residential"))
                        {
                            locationPlace.Residential = element2.StringValue;
                            continue;
                        }
                        if (element2.Name.Equals("house"))
                        {
                            locationPlace.House = element2.StringValue;
                            continue;
                        }
                        if (element2.Name.Equals("place"))
                        {
                            locationPlace.Place = element2.StringValue;
                        }
                    }
                }
            }
            locationSearchResult.PlaceList.Add(locationPlace);
            return(locationSearchResult);
        }
コード例 #58
0
        private void ChangeStatusWithEvent(GeoPositionStatus status, GeoCoordinate currentLocation)
        {
            Position = new GeoPosition<GeoCoordinate>(DateTimeOffset.Now, currentLocation);
              ChangeStatusWithEvent(status);

              if (PositionChanged != null)
              {
            PositionChanged(this, new GeoPositionChangedEventArgs<GeoCoordinate>(Position));
              }
        }
コード例 #59
0
        public int SaveFile(GeoPosition<GeoCoordinate> Position = null)
        {
            if (Position == null)
            {
                GeoCoordinateWatcher watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
                watcher.Start();
                Position = watcher.Position;
            }

            var fileName = CurrentFileName();

            var tempFileName = "record.gpx.temp";
            var count = 0;
            bool firstRun = true;
            IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication();
            if (isStore.FileExists(tempFileName))
            {
                isStore.DeleteFile(tempFileName);
            }
            if (isStore.FileExists(fileName))
            {
                firstRun = false;
                isStore.MoveFile(fileName, tempFileName);
            }

            using (IsolatedStorageFileStream input = new IsolatedStorageFileStream(tempFileName, System.IO.FileMode.OpenOrCreate, FileAccess.Read, isStore))
            using (IsolatedStorageFileStream output = new IsolatedStorageFileStream(fileName, System.IO.FileMode.OpenOrCreate, FileAccess.Write, isStore))
            using (GpxWriter writer = new GpxWriter(output))
            {
                GpxWayPoint last = null;
                if (!firstRun)
                {
                    using (GpxReader reader = new GpxReader(input))
                    {
                        while (reader.Read())
                        {
                            switch (reader.ObjectType)
                            {
                                case GpxObjectType.WayPoint:
                                    count++;
                                    writer.WriteWayPoint(reader.WayPoint);
                                    last = reader.WayPoint;
                                    break;
                            }
                        }
                    }
                }

                IsolatedStorageSettings.ApplicationSettings["LastLocation"] = last;
                IsolatedStorageSettings.ApplicationSettings.Save();

                if (double.IsNaN(Position.Location.Latitude) || double.IsNaN(Position.Location.Longitude))
                {
                    return count;
                }
                if (last == null || last.Time.ToString() != Position.Timestamp.UtcDateTime.ToString())
                {
                    writer.WriteWayPoint(new GpxWayPoint
                    {
                        Latitude = Position.Location.Latitude,
                        Longitude = Position.Location.Longitude,
                        Elevation = Position.Location.Altitude,
                        Time = Position.Timestamp.UtcDateTime,
                    });
                    count++;
                }
            }
            return count;
        }
コード例 #60
0
 public PointOfInterest(GeoPosition wp) : base(wp.Latitude, wp.Longitude)
 {
 }