Example #1
0
        public async Task getNearbyToilets(ParseGeoPoint location, Boolean shouldSkip)
        {
            if (currentLocation.Latitude != location.Latitude || currentLocation.Longitude != location.Longitude)
            {
                //New location, so empty data
                _parseToilets.Clear();
                currentLocation = location;
            } 

            var query = new ParseQuery<Toilet>();
            query = query.WhereNear("Location", location);
            query = query.Limit(20);

            if (shouldSkip)
            {
                query = query.Skip(skipCount);
                skipCount += 20;
            }

            IEnumerable<Toilet> result = await query.FindAsync();

            if (shouldSkip)
            {
                result.ToList().ForEach(_parseToilets.Add);
            } else
            {
                _parseToilets.Clear();
                result.ToList().ForEach(_parseToilets.Add);
            }

            foreach (Toilet toilet in _parseToilets)
            {
                toilet.searchLocationPoint = location;
            }
        }
Example #2
0
		async public void SaveToParse ()
		{
			ParseObject checkin;
			if (this.ParseId == null || this.ParseId == "") {
				checkin = new ParseObject ("Checkin");
			} else {
				ParseQuery<ParseObject> query = ParseObject.GetQuery ("Checkin");
				checkin = await query.GetAsync (this.ParseId);
			}

			if (this.Movie != null) {
				checkin ["Pelicula"] = this.Movie.ParseId;
			}
			if (this.User != null) {
				checkin ["Usuario"] = this.User.ParseId;
			}
			checkin ["Coordenadas"] = new Parse.ParseGeoPoint (this.Latitude, this.Longitude);

			await checkin.SaveAsync ().ContinueWith (t => {
				this.ParseId = checkin.ObjectId;
				Console.WriteLine("Saved Checkin in Parse: " + this.ParseId);
				CheckinDB checkinDB = new CheckinDB ();
				checkinDB.Update (this);
			});
		}
 public Items(ParseGeoPoint pgp, int timeStamp, string nameZone, string sURL)
 {
     this.pgp = pgp;
     this.timeStamp = timeStamp;
     this.nameZone = nameZone;
     this.sURL = sURL;
 }
Example #4
0
 /// <summary>
 /// Add a constraint to the query that requires a particular key's coordinates to be
 /// contained within a given rectangular geographic bounding box.
 /// </summary>
 /// <param name="key">The key to be constrained.</param>
 /// <param name="southwest">The lower-left inclusive corner of the box.</param>
 /// <param name="northeast">The upper-right inclusive corner of the box.</param>
 /// <returns>A new query with the additional constraint.</returns>
 public ParseQuery <T> WhereWithinGeoBox(string key, ParseGeoPoint southwest, ParseGeoPoint northeast) => new ParseQuery <T>(this, where : new Dictionary <string, object> {
     { key, new Dictionary <string, object> {
           { "$within", new Dictionary <string, object> {
                                                                                                                                                                                     { "$box", new[] { southwest, northeast } }
                                                                                                                                                                                 } }
       } }
 });
Example #5
0
        public async void SaveEvent(object sender, RoutedEventArgs e) 
        {
                try { 
                if(Activity.Text=="")
                {
                    InvalidInput();
                    return;
                }

                Info data = new Info()
                {
                    UserId = (++App.i).ToString(),
                    Activity = Activity.Text.Trim(),
                    Lat = pin.Location.Position.Latitude,
                    Long = pin.Location.Position.Longitude,
                    Interested = 1
            };
                var DataBase = new ParseObject("Activities");
                DataBase["UserID"] = data.UserId.ToString();
                DataBase["Interested"] = data.Interested;
                DataBase["Activity"] = data.Activity;
                DataBase["Location"] = new ParseGeoPoint(data.Lat, data.Long);
                await DataBase.SaveAsync();
                Frame.Navigate(typeof(Nearby));
            }
            catch(Exception ex)
            {
                Message.Text = ex.Message;
            }


        }
Example #6
0
 /// <summary>
 /// Adds a proximity-based constraint for finding objects with keys whose GeoPoint
 /// values are near the given point.
 /// </summary>
 /// <param name="key">The key that the ParseGeoPoint is stored in.</param>
 /// <param name="point">The reference ParseGeoPoint.</param>
 /// <returns>A new query with the additional constraint.</returns>
 public ParseQuery <T> WhereNear(string key, ParseGeoPoint point)
 {
     return(new ParseQuery <T>(this, where : new Dictionary <string, object> {
         { key, new Dictionary <string, object> {
               { "$nearSphere", point }
           } }
     }));
 }
    public void TestGeoDistanceInRadians() {
      var d2r = Math.PI / 180.0;
      var pointA = new ParseGeoPoint();
      var pointB = new ParseGeoPoint();

      // Zero
      Assert.AreEqual(0.0, pointA.DistanceTo(pointB).Radians, 0.00001);
      Assert.AreEqual(0.0, pointB.DistanceTo(pointA).Radians, 0.00001);

      // Wrap Long
      pointA.Longitude = 179.0;
      pointB.Longitude = -179.0;
      Assert.AreEqual(2 * d2r, pointA.DistanceTo(pointB).Radians, 0.00001);
      Assert.AreEqual(2 * d2r, pointB.DistanceTo(pointA).Radians, 0.00001);

      // North South Lat
      pointA.Latitude = 89.0;
      pointA.Longitude = 0;
      pointB.Latitude = -89.0;
      pointB.Longitude = 0;
      Assert.AreEqual(178 * d2r, pointA.DistanceTo(pointB).Radians, 0.00001);
      Assert.AreEqual(178 * d2r, pointB.DistanceTo(pointA).Radians, 0.00001);

      // Long wrap Lat
      pointA.Latitude = 89.0;
      pointA.Longitude = 0;
      pointB.Latitude = -89.0;
      pointB.Longitude = 179.999;
      Assert.AreEqual(180 * d2r, pointA.DistanceTo(pointB).Radians, 0.00001);
      Assert.AreEqual(180 * d2r, pointB.DistanceTo(pointA).Radians, 0.00001);

      pointA.Latitude = 79.0;
      pointA.Longitude = 90.0;
      pointB.Latitude = -79.0;
      pointB.Longitude = -90.0;
      Assert.AreEqual(180 * d2r, pointA.DistanceTo(pointB).Radians, 0.00001);
      Assert.AreEqual(180 * d2r, pointB.DistanceTo(pointA).Radians, 0.00001);

      // Wrap near pole - somewhat ill conditioned case due to pole proximity
      pointA.Latitude = 85.0;
      pointA.Longitude = 90.0;
      pointB.Latitude = 85.0;
      pointB.Longitude = -90.0;
      Assert.AreEqual(10 * d2r, pointA.DistanceTo(pointB).Radians, 0.00001);
      Assert.AreEqual(10 * d2r, pointB.DistanceTo(pointA).Radians, 0.00001);

      // Reference cities

      // Sydney, Australia
      pointA.Latitude = -34.0;
      pointA.Longitude = 151.0;
      // Buenos Aires, Argentina
      pointB.Latitude = -34.5;
      pointB.Longitude = -58.35;
      Assert.AreEqual(1.85, pointA.DistanceTo(pointB).Radians, 0.01);
      Assert.AreEqual(1.85, pointB.DistanceTo(pointA).Radians, 0.01);
    }
Example #8
0
 /// <summary>
 /// Adds a proximity-based constraint for finding objects with keys whose GeoPoint
 /// values are near the given point and within the maximum distance given.
 /// </summary>
 /// <param name="key">The key that the ParseGeoPoint is stored in.</param>
 /// <param name="point">The reference ParseGeoPoint.</param>
 /// <param name="maxDistance">The maximum distance (in radians) of results to return.</param>
 /// <returns>A new query with the additional constraint.</returns>
 public ParseQuery <T> WhereWithinDistance(
     string key, ParseGeoPoint point, ParseGeoDistance maxDistance)
 {
     return(new ParseQuery <T>(WhereNear(key, point), where : new Dictionary <string, object> {
         { key, new Dictionary <string, object> {
               { "$maxDistance", maxDistance.Radians }
           } }
     }));
 }
Example #9
0
 public SearchAreaBlockModel(double longitude, double latitude, ParseGeoPoint location, int row, int column, string searchAreaId, bool isComplete)
 {
     Latitude = longitude;
     Longitude = latitude;
     Location = location;
     Row = row;
     Column = column;
     SearchAreaId = searchAreaId;
     IsComplete = isComplete;
 }
Example #10
0
 /// <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);
 }
 public ChallengeViewModel()
 {
     User = new UserViewModel();
     Title = "some challenge";
     Image = new Uri("http://farm8.staticflickr.com/7343/11914204134_8de5a28ff7_z.jpg");
     Location = new ParseGeoPoint(34, 34);
     Distance = "3 miles";
     DistanceCount = 5;
     SolvedCount = 12;
     Created = DateTime.Now;
     CommentListViewModel = new CommentListViewModel();
 }
        public async void Cadastrar()
        {
            DateTime? _datetime = time_abre.Value;
            string hr_abre = _datetime.Value.Hour + ":" + _datetime.Value.Minute;
            
            _datetime = time_fecha.Value;
            string hr_fecha = _datetime.Value.Hour + ":" + _datetime.Value.Minute;

            ListPickerItem selectedItem = (ListPickerItem)lst_segmento.SelectedItem;
            string segmento_lst = (string)selectedItem.Content;
            
            ParseObject cadastro = new ParseObject("Foodtruck");
            try {
                cadastro["idUser"] = Id;
                cadastro["Foodtruck_nome"] = txt_foodtruck_nome.Text;
                cadastro["Segmento"] = segmento_lst;
                cadastro["Hr_abre"] = hr_abre;
                cadastro["Hr_Fecha"] = hr_fecha;
                cadastro["Preco"] = txt_preco.Text;
                cadastro["Telefone"] = txt_telefone.Text;

                GeocodeQuery geocodeQuery = new GeocodeQuery();
                geocodeQuery.GeoCoordinate = new GeoCoordinate();
                geocodeQuery.SearchTerm = txt_local.Text;

                IList<MapLocation> locations = await geocodeQuery.GetMapLocationsAsync();

                foreach (var local in locations)
                {        
                    var point = new ParseGeoPoint(local.GeoCoordinate.Latitude, local.GeoCoordinate.Longitude);
                    cadastro["localizacao"] = point;
                    MessageBoxResult resultado6 = MessageBox.Show("latitude: " + point.Latitude+" longitude: "+ point.Longitude, "Foodtruck Show", MessageBoxButton.OK); 
                }                
                await
                     cadastro.SaveAsync();
            }
            catch (Exception ex) {
                MessageBox.Show("Erro: " + ex);
            }

            MessageBoxResult resultado0 = MessageBox.Show("ID : " + Id, "Foodtruck Show", MessageBoxButton.OK);
            MessageBoxResult resultado1 = MessageBox.Show("Nome : " +txt_foodtruck_nome.Text, "Foodtruck Show", MessageBoxButton.OK);
            MessageBoxResult resultado2 = MessageBox.Show("Segmento : " + segmento_lst, "Foodtruck Show", MessageBoxButton.OK);
            MessageBoxResult resultado3 = MessageBox.Show(hr_abre + " " + hr_fecha , "Foodtruck Show", MessageBoxButton.OK);
            MessageBoxResult resultado4 = MessageBox.Show("Preco : "+ txt_preco.Text, "Foodtruck Show", MessageBoxButton.OK);
            MessageBoxResult resultado5 = MessageBox.Show("tel : "+ txt_telefone.Text, "Foodtruck Show", MessageBoxButton.OK);
            MessageBoxResult resultado = MessageBox.Show("Informacoes cadastradas com sucesso", "Foodtruck Show", MessageBoxButton.OK);

            if (resultado == MessageBoxResult.OK)
                NavigationService.GoBack();
        }
    public void TestGeoPointConstructor() {
      var point = new ParseGeoPoint();
      Assert.AreEqual(0.0, point.Latitude);
      Assert.AreEqual(0.0, point.Longitude);

      point = new ParseGeoPoint(42, 36);
      Assert.AreEqual(42.0, point.Latitude);
      Assert.AreEqual(36.0, point.Longitude);

      point.Latitude = 12;
      point.Longitude = 24;
      Assert.AreEqual(12.0, point.Latitude);
      Assert.AreEqual(24.0, point.Longitude);
    }
Example #14
0
        public async Task<IList<Site>> GetNearbySites(double latitude, double longitude, double distanceRadians = 0)
        {
            if (distanceRadians == 0) distanceRadians = 0.5;
            var pos = new ParseGeoPoint(latitude, longitude);
            var sitesQuery = new ParseQuery<ApParseSite>()
                .WhereWithinDistance("location", pos, new ParseGeoDistance(distanceRadians))
                .Limit(100);

            var sites = await sitesQuery.FindAsync();

            return sites
                .Select(s => ConvertToSite(s, pos))
                .OrderByDescending(s => s.DistanceKm)
                .ToList();
        }
Example #15
0
 public void TestGeoPointCultureInvariantParsing() {
   var originalCulture = Thread.CurrentThread.CurrentCulture;
   foreach (var c in CultureInfo.GetCultures(CultureTypes.AllCultures)) {
     Thread.CurrentThread.CurrentCulture = c;
     var point = new ParseGeoPoint(1.234, 1.234);
     var serialized = Json.Encode(
       new Dictionary<string, object> {
         { "point", NoObjectsEncoder.Instance.Encode(point) }
       });
     var deserialized = ParseDecoder.Instance.Decode(Json.Parse(serialized)) as IDictionary<string, object>;
     var pointAgain = (ParseGeoPoint)deserialized["point"];
     Assert.AreEqual(1.234, pointAgain.Latitude);
     Assert.AreEqual(1.234, pointAgain.Longitude);
   }
 }
Example #16
0
        public ActionResult Create(CreateSearchFormModel model)
        {
            ParseDBUtils.Initialize();
            ISearchAreaFactory searchAreaFactory = new SearchAreaFactory();

            var northeastGeoPoint = new ParseGeoPoint(model.NortheastLatitude, model.NortheastLongitude);
            var southwestGeopoint = new ParseGeoPoint(model.SouthwestLatitude, model.SouthwestLongitude);

            var searchAreaModel = searchAreaFactory.GenerateSearchArea(model.Name, (AreaTypes)Enum.Parse(typeof(AreaTypes), model.AreaType), northeastGeoPoint, southwestGeopoint);
            ParseDBUtils.StoreSearchArea(searchAreaModel);

            var searchAreaBlockModels = searchAreaFactory.GenerateBlocks(searchAreaModel);
            ParseDBUtils.StoreSearchAreaBlocks(searchAreaModel.Id, searchAreaBlockModels);

            return RedirectToAction("Index");
        }
Example #17
0
        private async void AddIcons(ParseGeoPoint lugarPlanEdit)
        {
            ParseQuery<ParseObject> query = ParseObject.GetQuery("Lugares");
            IEnumerable<ParseObject> results = await query.FindAsync();
            ParseObject lugar;
            ParseGeoPoint ubicacion;
            BasicGeoposition position;
            Geopoint point;
            MapIcon mapIcon;

            //posicion actual
            getPosicionActual();

            // Agregarlos al mapa
            int tamanio = results.Count<ParseObject>();


            for (int i = 0; i < tamanio; i++)
            {

                lugar = results.ElementAt<ParseObject>(i);
                ubicacion = lugar.Get<ParseGeoPoint>("ubicacion");

                position = new BasicGeoposition() { Latitude = ubicacion.Latitude, Longitude = ubicacion.Longitude };
                point = new Geopoint(position);

                // MapIcon
                mapIcon = new MapIcon();
                mapIcon.Location = point;
                mapIcon.NormalizedAnchorPoint = new Point(0.5, 1.0);
                mapIcon.Title = lugar.Get<string>("direccion");

                if (ubicacion.Latitude == lugarPlanEdit.Latitude && ubicacion.Longitude == lugarPlanEdit.Longitude)
                {
                    mapIcon.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/posicionPlan.png"));
                }
                else
                {
                    mapIcon.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/bus.png"));
                }
                mapIcon.ZIndex = 0;

                editMap.MapElements.Add(mapIcon);

            }

        }
 /// <summary>
 /// Get the distance in radians between this point and another GeoPoint. This is the smallest angular
 /// distance between the two points.
 /// </summary>
 /// <param name="point">GeoPoint describing the other point being measured against.</param>
 /// <returns>The distance in between the two points.</returns>
 public ParseGeoDistance DistanceTo(ParseGeoPoint point) {
   double d2r = Math.PI / 180; // radian conversion factor
   double lat1rad = Latitude * d2r;
   double long1rad = longitude * d2r;
   double lat2rad = point.Latitude * d2r;
   double long2rad = point.Longitude * d2r;
   double deltaLat = lat1rad - lat2rad;
   double deltaLong = long1rad - long2rad;
   double sinDeltaLatDiv2 = Math.Sin(deltaLat / 2);
   double sinDeltaLongDiv2 = Math.Sin(deltaLong / 2);
   // Square of half the straight line chord distance between both points.
   // [0.0, 1.0]
   double a = sinDeltaLatDiv2 * sinDeltaLatDiv2 +
     Math.Cos(lat1rad) * Math.Cos(lat2rad) * sinDeltaLongDiv2 * sinDeltaLongDiv2;
   a = Math.Min(1.0, a);
   return new ParseGeoDistance(2 * Math.Asin(Math.Sqrt(a)));
 }
        /// <summary>
        /// Begins loading new challenges asynchronously.
        /// </summary>
        /// <param name="skipCount">The number of challenges to skip.</param>
        /// <returns>An awaitable task.</returns>
        protected async override Task LoadDataImpl(bool forceReload = false)
        {
            var geoposition = await Utilities.GeoLocationHelper.GetLocation();
            var geoPoint = new ParseGeoPoint(geoposition.Coordinate.Latitude, geoposition.Coordinate.Longitude);
            var query = ParseObject.GetQuery("Challenge");
            query.WhereNear("location", geoPoint).Limit(20).Skip(CurrentlyLoaded);

            List<Task> challengeTasks = new List<Task>();
            foreach (var challenge in await query.FindAsync())
            {
                var challengeViewModel = new ChallengeViewModel(challenge);
                Challenges.Add(challengeViewModel);
                challengeTasks.Add(challengeViewModel.LoadData());
            }
            await Task.WhenAll(challengeTasks.ToArray());

            CurrentlyLoaded += 20;
        }
        /// <summary>
        /// Get the distance in radians between this point and another GeoPoint. This is the smallest angular
        /// distance between the two points.
        /// </summary>
        /// <param name="point">GeoPoint describing the other point being measured against.</param>
        /// <returns>The distance in between the two points.</returns>
        public ParseGeoDistance DistanceTo(ParseGeoPoint point)
        {
            double d2r              = Math.PI / 180; // radian conversion factor
            double lat1rad          = Latitude * d2r;
            double long1rad         = longitude * d2r;
            double lat2rad          = point.Latitude * d2r;
            double long2rad         = point.Longitude * d2r;
            double deltaLat         = lat1rad - lat2rad;
            double deltaLong        = long1rad - long2rad;
            double sinDeltaLatDiv2  = Math.Sin(deltaLat / 2);
            double sinDeltaLongDiv2 = Math.Sin(deltaLong / 2);
            // Square of half the straight line chord distance between both points.
            // [0.0, 1.0]
            double a = sinDeltaLatDiv2 * sinDeltaLatDiv2 +
                       Math.Cos(lat1rad) * Math.Cos(lat2rad) * sinDeltaLongDiv2 * sinDeltaLongDiv2;

            a = Math.Min(1.0, a);
            return(new ParseGeoDistance(2 * Math.Asin(Math.Sqrt(a))));
        }
Example #21
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            bool isConnected = NetworkInterface.GetIsNetworkAvailable();
            if (!isConnected)
            {
                await new MessageDialog("No internet connection is avaliable. The full functionality of the app isn't avaliable.").ShowAsync();
                Application.Current.Exit();
            }

            Geolocator geolocator = new Geolocator();
            Geoposition pos = await geolocator.GetGeopositionAsync();
            var geo = new ParseGeoPoint(pos.Coordinate.Point.Position.Latitude, pos.Coordinate.Point.Position.Longitude);
            try { 
            ParseQuery<ParseObject> query = ParseObject.GetQuery("Activities")
                .WhereWithinDistance("Location", geo, ParseGeoDistance.FromMiles(10)).OrderByDescending("Interested");
            IEnumerable<ParseObject> nearbyLocations = await query.FindAsync();
            List<Info> users = new List<Info>();
            foreach (var item in nearbyLocations)
            {
                Info variable = new Info();
                variable.Activity = item.Get<String>("Activity");
                variable.Interested = item.Get<int>("Interested");
                variable.ObjID = item.ObjectId;
                ParseGeoPoint point = item.Get<ParseGeoPoint>("Location");
                variable.Lat = point.Latitude;
                variable.Long = point.Longitude;
                users.Add(variable);

            }
            Activities.ItemsSource = users;
           
                
            }
            catch(Exception ex)
            {
                Heading.Text = ex.Message;
            }
            
            Windows.Phone.UI.Input.HardwareButtons.BackPressed += App.HardwareButtons_BackPressed;
        }
Example #22
0
 private Site ConvertToSite(ApParseSite s, ParseGeoPoint p)
 {
     return new Site
     {
         SiteId = s.SiteId,
         SiteName = s.SiteName,
         Forsamling = s.Forsamling,
         Socken = s.Socken,
         Lan = s.Lan,
         SiteYCoord = s.SiteYCoord,
         SiteXCoord = s.SiteXCoord,
         Kommun = s.Kommun,
         Landskap = s.Landskap,
         UseCount = s.UseCount,
         Latitude = s.Location.Latitude,
         Longitude = s.Location.Longitude,
         Accuracy = s.Accuracy,
         ParentId = s.ParentId,
         IsPublic = s.IsPublic,
         DistanceKm = (p.Latitude == 0 && p.Longitude == 0) ? 0 : s.Location.DistanceTo(p).Kilometers
     };
 }
Example #23
0
		public async void ExportFilesOnParse (string type,  double latitude, double longitude, string address, string comment)
		{
			ParseGeoPoint location = new ParseGeoPoint (latitude, longitude);
			string sdCardPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
			string name = "image.jpg";
			string filePath = System.IO.Path.Combine(sdCardPath, name);
			byte[] data = System.IO.File.ReadAllBytes (filePath);

			ParseFile file = new ParseFile (name, data);

	/*		var sdCardPathID = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
			var filePathID = System.IO.Path.Combine(sdCardPathID+"/Application/Root Studio", "UserId.xml");
			if (System.IO.File.Exists (filePathID)) {
				FileStream fStream = new FileStream(filePathID, FileMode.Open, FileAccess.Read);

				var myBinaryFormatter = new BinaryFormatter ();
				var mc = (string)myBinaryFormatter.Deserialize (fStream);
				fStream.Close();

			}*/
			var problemObject = new ParseObject ("problem");
			problemObject ["description"] = type;
			problemObject ["coordinates"] = location;
			problemObject ["image"] = file;
			problemObject ["address"] = address;
			problemObject ["comment"] = comment;
			Android.Widget.Toast.MakeText(this, "it's work", Android.Widget.ToastLength.Short).Show();
			await problemObject.SaveAsync ();
		}
Example #24
0
        protected async void Button1_Click(object sender, EventArgs e)
        {
            ParseObject job = new ParseObject(typeof(Job).Name);
            ParseObject empjob = new ParseObject(typeof(EmpJobRelation).Name);
            var locationService = new GoogleLocationService();
            var point = locationService.GetLatLongFromAddress(txtlocation.Text);
            DateTime selected=Calendar1.SelectedDate;

            DateTime dt = new DateTime(selected.Year, selected.Month, selected.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
            //var latitude = point.Latitude;
            //var longitude = point.Longitude;
            //Response.Write(latitude + "" + longitude);
            var addpoint = new ParseGeoPoint(point.Latitude, point.Longitude);
            try
            {
                var selectedValue = LiEmployee.SelectedItem;
                //User userObject = items[selectedValue];
                //Response.Write((selectedValue.Value));


                job[MemberInfoGetting.GetMemberName(() => new Job().name)] = JobTitle.Text;
                job[MemberInfoGetting.GetMemberName(() => new Job().description)] = JobDescription.Text;
                //job[MemberInfoGetting.GetMemberName(() => new Job().EmployeeId)] = selectedValue.Value;
                job[MemberInfoGetting.GetMemberName(() => new Job().content)] = JsonConvert.SerializeObject(allcontent);
                job[MemberInfoGetting.GetMemberName(() => new Job().Status)] = JobControlls.JobStatusCode[8];
                job[MemberInfoGetting.GetMemberName(() => new Job().jobDate)] = dt;
                job[MemberInfoGetting.GetMemberName(() => new Job().location)]=txtlocation.Text;
                job[MemberInfoGetting.GetMemberName(() => new Job().locCoordinate)]=addpoint;
                empjob[MemberInfoGetting.GetMemberName(() => new Job().EmployeeId)]=selectedValue.Value;
                
                await job.SaveAsync();
                await empjob.SaveAsync();
                IEnumerable<ParseObject> query  =await ParseObject.GetQuery(typeof(EmpJobRelation).Name)
                    .WhereEqualTo(MemberInfoGetting.GetMemberName(() => new Job().EmployeeId), selectedValue.Value).FindAsync();
                foreach (ParseObject obj in query)
                {
                    empjobrel.Add(new EmpJobRelation()
                    {
                        Id=obj.ObjectId
                    }
                        );
 
                }
                //ParseObject p;
                //var relaiton = p.GetRelation<ParseObject>("UserRelation");
                foreach(var a in empjobrel)
                {

                    job[MemberInfoGetting.GetMemberName(() => new Job().UserRelation)] = a.Id;
                }
                
                await job.SaveAsync();
                Lblerror.Text = "Saved Successfully";
                

            }
            catch(Exception en)
            {
                Lblerror.Text = en.Message;
            }
            //var newJob = new Job { JobName = JobTitle.Text, JobDesc = JobDescription.Text, AssignedUser = selectedValue.Value };
            ////Debug.WriteLine("" + selectedValue.Id);
            // await InsertnewJob(newJob);
        }
Example #25
0
        public Models.Search.SearchAreaModel GenerateSearchArea(string name, AreaTypes areaType, ParseGeoPoint northeastGeopoint, ParseGeoPoint southwestGeopoint)
        {
            Guid id = Guid.NewGuid();
            string id_str = id.ToString();

            double neLng = northeastGeopoint.Longitude;
            double neLat = northeastGeopoint.Latitude;
            double swLng = southwestGeopoint.Longitude;
            double swLat = southwestGeopoint.Latitude;

            SearchAreaModel searchAreaModel = new SearchAreaModel(id_str, name, areaType, northeastGeopoint, neLng, neLat, swLng, swLat, false);

            return searchAreaModel;
        }
 public void TestEncodeParseGeoPoint() {
   ParseGeoPoint point = new ParseGeoPoint(3.22, 32.2);
   IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(point) as IDictionary<string, object>;
   Assert.AreEqual("GeoPoint", value["__type"]);
   Assert.AreEqual(3.22, value["latitude"]);
   Assert.AreEqual(32.2, value["longitude"]);
 }
Example #27
0
        public List<SearchAreaBlockModel> GenerateBlocks(SearchAreaModel searchArea)
        {
            //Calculates the "X" distance for the search area in meters.
            double horizontalDistance = calculate(searchArea.NortheastLatitude,
                searchArea.NortheastLongitude, searchArea.NortheastLatitude, searchArea.SouthwestLongitude);

            //Calculates the "Y" distance for the search area in meters.
            double verticalDistance = calculate(searchArea.NortheastLatitude,
                searchArea.NortheastLongitude, searchArea.SouthwestLatitude, searchArea.NortheastLongitude);

            //Calculates NE Corner Coordinates
            Tuple<double, double> NWCorner = new Tuple<double, double>(searchArea.NortheastLatitude, searchArea.SouthwestLongitude);

            //Assignes the vertical and horizontal values of the blocks to blockHeight and blockWidth based on the entered terrainType.
            double blockHeight;
            double blockWidth;
            switch (searchArea.AreaType)
            {
                case AreaTypes.Field:
                    blockHeight = 50;
                    blockWidth = 50;
                    break;
                case AreaTypes.Forest:
                    blockHeight = 25;
                    blockWidth = 25;
                    break;
                case AreaTypes.DenseForest:
                    blockHeight = 10;
                    blockWidth = 10;
                    break;
                case AreaTypes.Mountains:
                    blockHeight = 5;
                    blockWidth = 5;
                    break;
                default:
                    blockHeight = 0;
                    blockWidth = 0;
                    throw new InvalidOperationException();
            }
            //Calculates the number of blocks needed and creates an array with that ammount.
            int numberOfXBlocks = (int)Math.Ceiling(horizontalDistance / blockWidth);
            int numberOfYBlocks = (int)Math.Ceiling(verticalDistance / blockHeight);
            SearchAreaBlockModel[,] blockArray = new SearchAreaBlockModel[numberOfXBlocks, numberOfYBlocks];

            //creates a tuple with the coordinates for the first block.
            Tuple<double, double> block0Coords = calculateDisplacement(NWCorner.Item1, NWCorner.Item2, blockWidth / 2, -(blockHeight / 2));
            double arrayLatitude = block0Coords.Item1;
            double arrayLongitude = block0Coords.Item2;

            for (int row = 0; row < numberOfXBlocks; row++)
            {
                //if we're not on the first row, a change in the vertical coordinates for the array.
                if (row != 0)
                {
                    Tuple<double, double> vertChangeCoords = calculateDisplacement(arrayLatitude, arrayLongitude, 0, blockHeight);
                    arrayLatitude = vertChangeCoords.Item1;
                }
                for (int column = 0; column < numberOfYBlocks; column++)
                {
                    //if the end of the column is reached then the longitude is reset to the first blocks coordinates.
                    if (column == 0)
                    {
                        //sets the array longitude to the first blocks longitude.
                        arrayLongitude = block0Coords.Item2;
                    }
                    //A random ID and a Geopoint for the block is created.
                    Guid randomID = System.Guid.NewGuid();
                    string id = randomID.ToString();

                    ParseGeoPoint arrayLocation = new ParseGeoPoint(arrayLatitude, arrayLongitude);

                    //A new searchAreaBlockModel is created in the curent cell with all the given information.
                    blockArray[row, column] = new SearchAreaBlockModel(arrayLongitude, arrayLatitude, arrayLocation, row, column, id, false);

                    //implements longitude change
                    Tuple<double, double> horizChangeCoords = calculateDisplacement(arrayLatitude, arrayLongitude, blockWidth, 0);
                    arrayLongitude = horizChangeCoords.Item2;

                }
            }

            //Adds the blockArray to a list in order from the top left to the bottom right.
            List<SearchAreaBlockModel> lastList = new List<SearchAreaBlockModel>();
            for (int row = 0; row < numberOfXBlocks; row++)
            {
                for (int column = 0; column < numberOfYBlocks; column++)
                {
                    lastList.Add(blockArray[row, column]);
                }
            }
            return lastList;
        }
 public static string RelativeDistanceTo(this ParseGeoPoint position1, ParseGeoPoint position2)
 {
     var distance = position1.DistanceTo(position2).Miles;
     if (distance < 0.5)
     {
         return Math.Round((distance * 5280), 0) + " feet";
     }
     else if (distance < 1)
     {
         return Math.Round(distance, 2) + " miles";
     }
     return Math.Round(distance) == 1 ? Math.Round(distance) + " mile" : Math.Round(distance) + " miles";
 }
        private async void loc_food()
        {
            ParseQuery<ParseObject> query_geo = ParseObject.GetQuery("Foodtruck").WhereEqualTo("idUser", Id);
            IEnumerable<ParseObject> resultado_geo = await query_geo.FindAsync();

            //Posicao atual
            MyGeolocator = new Geolocator();
            MyGeolocator.DesiredAccuracyInMeters = 20;
            MyGeoPosition = await MyGeolocator.GetGeopositionAsync(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10));

            local_latitude = MyGeoPosition.Coordinate.Latitude;
            local_longitude = MyGeoPosition.Coordinate.Longitude;

            var ponto = new ParseGeoPoint(local_latitude, local_longitude);
 
            foreach (ParseObject foodgeo in resultado_geo)
            {
                foodgeo["localizacao"] = ponto;
                foodgeo["latitude"] = local_latitude.ToString();
                foodgeo["longitude"] = local_longitude.ToString();
                await
                    foodgeo.SaveAsync();
            }

            txt_localizacao.Visibility = Visibility.Visible;

            MessageBoxResult localizador = MessageBox.Show("Geolocalizacao atualizada com sucesso." , "FoodTruckShow!", MessageBoxButton.OK);
        }
Example #30
0
        public async Task<IHttpActionResult> NuevaActividad([FromBody]Actividad act)
        {
            try
            {
                ParseObject actividad = new ParseObject("Actividad");
                actividad["nombre"] = act.nombre;
                actividad["fecha"] = act.fecha;
                actividad["capacidad"] = act.capacidad;
                actividad["mensaje"] = act.mensaje;
                Byte[] bytes = Convert.FromBase64String(act.foto);
                ParseFile foto = new ParseFile("foto.png", bytes);
                await foto.SaveAsync();
                actividad["foto"] = foto;
                actividad["usuario"] = await ParseUser.Query.GetAsync(act.idUsuario);
                actividad["Lugar"] = new ParseGeoPoint(act.lugar.lat, act.lugar.lon);
                await actividad.SaveAsync();

               
                Actividad acti = new Actividad();
                acti.idActividad = actividad.ObjectId;
                acti.idUsuario = actividad.Get<ParseUser>("usuario").ObjectId;
                acti.capacidad = actividad.Get<int>("capacidad");
                acti.mensaje = actividad.Get<string>("mensaje");
                acti.nombre = actividad.Get<string>("nombre");
                acti.fecha = actividad.Get<string>("fecha");
                acti.foto = actividad.Get<ParseFile>("foto").Url.AbsoluteUri;
                return Ok(acti);
            }
            catch (ParseException e)
            {
                return InternalServerError(e);
            }
        }
Example #31
0
 public async Task<IHttpActionResult> EditarActividad([FromBody]Actividad act)
 {
     try
     {
         ParseQuery<ParseObject> query = ParseObject.GetQuery("Actividad");
         ParseObject actividad = await query.GetAsync(act.idActividad);
         actividad["nombre"] = act.nombre;
         actividad["fecha"] = act.fecha;
         actividad["capacidad"] = act.capacidad;
         actividad["mensaje"] = act.mensaje;
         actividad["Lugar"] = new ParseGeoPoint(act.lugar.lat, act.lugar.lon);
         if (act.foto != null) {
             Byte[] bytes = Convert.FromBase64String(act.foto);
             ParseFile foto = new ParseFile("foto.png", bytes);
             await foto.SaveAsync();
             actividad["foto"] = foto;
         }
         
         await actividad.SaveAsync();
         return Ok(actividad);
     }
     catch (ParseException e)
     {
         return InternalServerError(e);
     }
 }
Example #32
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            planitem = e.Parameter as PlanItem;
            plan = planitem.obj;

            editNombre.Text = plan.Get<string>("nombre");
            editDescripcion.Text = plan.Get<string>("descripcion");
            char[] delimeter = { '/', ' ', ':' };
            string[] fechaCom = plan.Get<string>("fecha").Split(delimeter);

            string fec = fechaCom[1] + "/" + fechaCom[0] + "/" + fechaCom[2];
            editFecha.Date = DateTime.Parse(fec);

            string hor = fechaCom[3];
            string minute = fechaCom[4];
            string am_pm = fechaCom[5];

            string horaOrga = organizarHora(hor, minute, am_pm);

            //editFecha.Date = DateTime.Parse(fechaCom[0]);

            editHora.Time = TimeSpan.Parse(horaOrga);

            ParseFile file = plan.Get<ParseFile>("imagen");
            Uri ur = file.Url;
            BitmapImage img = new BitmapImage(ur);
            editImage.Source = img;

            NombreLugarTxt.Text = plan.Get<string>("direccion");

            gPoint = plan.Get<ParseGeoPoint>("lugar");

            // Specify a known location

            BasicGeoposition posicion = new BasicGeoposition() { Latitude = gPoint.Latitude, Longitude = gPoint.Longitude };
            Geopoint point = new Geopoint(posicion);

            // Set map location
            editMap.Center = point;
            editMap.ZoomLevel = 17.0f;
            editMap.LandmarksVisible = true;


            AddIcons(gPoint);

        }
Example #33
0
	IEnumerator LoadNearestScores()
	{

		ParseGeoPoint userLocation = new ParseGeoPoint(LocationScript.Latitude,LocationScript.Longitude);
		ParseQuery<ParseObject> query = ParseObject.GetQuery("GameScore").OrderByDescending("score").Limit(5);
		ParseQuery<ParseObject> nearestQuery = ParseObject.GetQuery("GameScore").WhereWithinDistance("geo_pos",userLocation,ParseGeoDistance.FromKilometers(2)).OrderByDescending("score").Limit(5);




		var resultTask = query.FindAsync();

		while (!resultTask.IsCompleted) yield return null;

		if (resultTask.IsFaulted || resultTask.IsCanceled) 
		{
			// Handle error
		} 
		else
		{
			var results = resultTask.Result;


			//var resultsList = results.OrderBy(item=>item.Get<int>("score")).Reverse().ToList();
			foreach(var item in results) 
			{

				Debug.Log("name: "+item["player_name"]);
				Debug.Log("score: "+item["score"]);

				scoresList.Add(new Scores{name=item["player_name"].ToString(),score=item["score"].ToString()});
			}
		}


		//////////////////
		/// 
		 resultTask = nearestQuery.FindAsync();
		
		while (!resultTask.IsCompleted) yield return null;
		
		if (resultTask.IsFaulted || resultTask.IsCanceled) 
		{
			// Handle error
		} 
		else
		{
			var results = resultTask.Result;
			Debug.Log ("NEAREST COUNT " + results.Count());
			
			//var resultsList = results.OrderBy(item=>item.Get<int>("score")).Reverse().ToList();
			foreach(var item in results) 
			{
				
				Debug.Log("name: "+item["player_name"]);
				Debug.Log("score: "+item["score"]);
				
				nearestScoresList.Add(new Scores{name=item["player_name"].ToString(),score=item["score"].ToString()});
			}
		}


	}
Example #34
0
    void signUp()
    {
        user = new ParseUser(){
            Username = username,
            Password = password,
            Email = email
        };

        int results = 0;
        ParseQuery<ParseUser> query = new ParseQuery<ParseUser>();
        query.WhereEqualTo ("username", username).CountAsync ().ContinueWith (t => {
            results += t.Result;
            query.WhereEqualTo ("email", email).CountAsync ().ContinueWith (s => {
                results += s.Result;
                if(results > 0){
                    print ("User or email already exists");
                    return;
                }
                if(!Regex.IsMatch(email, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z")){
                    print("Invalid email address");
                    return;
                }

                user["Geolocation"] = new ParseGeoPoint( lat, lon );
                user["Messages"] = new List<string> ();

                Task signuptask = user.SignUpAsync ();
                print ("Success");
                ParseUser.LogInAsync(username, password);
                if (ParseUser.CurrentUser.IsAuthenticated) {
                    print ("Logged In");
                    loggedin = true;
                }
            });
        });
            GameObject temp = GameObject.Instantiate(Resources.Load("Entity"), new Vector3(0f, 0f, 0f), new Quaternion(0, 0, 0, 0)) as GameObject;
            temp.GetComponent<Entity> ().setUID (ParseUser.CurrentUser.ObjectId);
            GameObject chat = GameObject.Instantiate(Resources.Load("Chatroom"), new Vector3(0f, 0f, 0f), new Quaternion(0, 0, 0, 0)) as GameObject;
            chat.GetComponent<Chatroom>().entity = temp.GetComponent<Entity>();
            chat.GetComponent<Chatroom>().userId = ParseUser.CurrentUser.ObjectId;
    }