public static async void CalculateRoute(MapControl mapControl,double startLatitude, double startLongitude, double endLatitude, double endLongitude)
        {
           
            BasicGeoposition startLocation = new BasicGeoposition();
            startLocation.Latitude = startLatitude;
            startLocation.Longitude = startLongitude;
            Geopoint startPoint = new Geopoint(startLocation);

            BasicGeoposition endLocation = new BasicGeoposition();
            endLocation.Latitude = endLatitude;
            endLocation.Longitude = endLongitude;
            Geopoint endPoint = new Geopoint(endLocation);

            MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync(
                startPoint,
                endPoint,
                MapRouteOptimization.Time,
                MapRouteRestrictions.None);

            if (routeResult.Status == MapRouteFinderStatus.Success)
            {
                MapRouteView viewOfRoute = new MapRouteView(routeResult.Route);
                viewOfRoute.RouteColor = Colors.Aqua;
                viewOfRoute.OutlineColor = Colors.Black;

                mapControl.Routes.Add(viewOfRoute);

                await mapControl.TrySetViewBoundsAsync(
                    routeResult.Route.BoundingBox,
                    null,
                    Windows.UI.Xaml.Controls.Maps.MapAnimationKind.Bow);

                var distance = routeResult.Route.LengthInMeters.ToString();
            }
        }
Example #2
0
        private async void button1_Click(object sender, RoutedEventArgs e)
        {
            if (MapControl1.Is3DSupported)
            {
                
                MapControl1.Style = MapStyle.Aerial3D;
                 BasicGeoposition hwGeoposition = new BasicGeoposition() { Latitude = 48.858, Longitude = 2.295 };
                Geopoint hwPoint = new Geopoint(hwGeoposition);

                
                MapScene hwScene = MapScene.CreateFromLocationAndRadius(hwPoint, 80, 0, 60);
                                                                                     
                
                await MapControl1.TrySetSceneAsync(hwScene, MapAnimationKind.Bow);
            }
            else
            {
                
                ContentDialog viewNotSupportedDialog = new ContentDialog()
                {
                    Title = "3D is not supported",
                    Content = "\n3D views are not supported on this device.",
                    PrimaryButtonText = "OK"
                };
                await viewNotSupportedDialog.ShowAsync();
            }
            }
Example #3
0
        public async void setCurrentPos()
        {
            try
            {
                myLocation = await refreshLoc();
                if (myLocation != null)
                {
                    string adresse = await gs.reverseGeocode(myLocation);
                    MapControl1.Center = myLocation;
                    //set a map icon start
                    MapIcon mapIconStart = new MapIcon();
                    mapIconStart.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/map-pin.png"));
                    mapIconStart.Location = myLocation;
                    mapIconStart.NormalizedAnchorPoint = new Point(0.5, 1.0);
                    mapIconStart.Title = string.Format("vous :\n{0}",adresse);
                    mapIconStart.ZIndex = 1;
                    MapControl1.MapElements.Add(mapIconStart);
                    MapControl1.ZoomLevel = 14;
                }
                else
                {
                    Debug.WriteLine("Erreur geoloc Null");
                }
            }
            catch
            {

            }

        }
Example #4
0
 private async void button_Click(object sender, RoutedEventArgs e)
 {
     var accessStatus = await Geolocator.RequestAccessAsync();
     switch (accessStatus)
     {
         case GeolocationAccessStatus.Allowed:
             Geolocator gl = new Geolocator();
             Geoposition gp = await gl.GetGeopositionAsync();
             myloc = gp.Coordinate.Point;
             map1.Center = myloc;
             map1.ZoomLevel = 15;
             map1.LandmarksVisible = true;
             MapIcon mi = new MapIcon();
             mi.Location = myloc;
             mi.NormalizedAnchorPoint = new Point(0.5, 1.0);
             mi.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/pin.png"));
             mi.ZIndex = 0;
             map1.MapElements.Add(mi);
             break;
         case GeolocationAccessStatus.Denied:
             break;
         case GeolocationAccessStatus.Unspecified:
             break;
     }
 }
 public static async Task<String> GetDistrictUsingLocation(Geopoint point)
 {
     MapLocationFinderResult result = await MapLocationFinder.FindLocationsAtAsync(point);
     MapLocation location = result.Locations[0] as MapLocation;
     string district = location.Address.District;
     return district;
 }
Example #6
0
        public MapView()
        {

            mapControl = new MapControl();
            mapControl.ZoomInteractionMode = MapInteractionMode.GestureAndControl;
            mapControl.TiltInteractionMode = MapInteractionMode.GestureAndControl;
            mapControl.MapServiceToken = "ift37edNFjWtwMkOrquL~7gzuj1f0EWpVbWWsBaVKtA~Amh-DIg5R0ZPETQo7V-k2m785NG8XugPBOh52EElcvxaioPYSYWXf96wL6E_0W1g";

            // Specify a known location
            BasicGeoposition cityPosition;
            Geopoint cityCenter;

            cityPosition = new BasicGeoposition() { Latitude = 2.4448143, Longitude = -76.6147395 };
            cityCenter = new Geopoint(cityPosition);

            // Set map location
            mapControl.Center = cityCenter;
            mapControl.ZoomLevel = 13.0f;
            mapControl.LandmarksVisible = true;

            AddIcons();

            this.Children.Add(mapControl);


            //this.Children.Add(_map);
        }
        public static bool Contains(List<Geopoint> polyPoints, Geopoint point)
        {
            bool inside = false;
            Geopoint p1, p2;

            //iterate each side of the polygon
            Geopoint oldPoint = polyPoints[polyPoints.Count - 1];

            foreach (Geopoint newPoint in polyPoints)
            {
                //order points so p1.lat <= p2.lat;
                if (newPoint.Position.Latitude > oldPoint.Position.Latitude)
                {
                    p1 = oldPoint;
                    p2 = newPoint;
                }
                else
                {
                    p1 = newPoint;
                    p2 = oldPoint;
                }

                //test if the line is crossed and if so invert the inside flag.
                if ((newPoint.Position.Latitude < point.Position.Latitude) == (point.Position.Latitude <= oldPoint.Position.Latitude)
                    && (point.Position.Longitude - p1.Position.Longitude) * (p2.Position.Latitude - p1.Position.Latitude)
                     < (p2.Position.Longitude - p1.Position.Longitude) * (point.Position.Latitude - p1.Position.Latitude))
                {
                    inside = !inside;
                }

                oldPoint = newPoint;
            }

            return inside;
        }
        public static IEnumerable<PointList> GetRandomPoints(Geopoint point1, Geopoint point2, int nrOfPoints)
        {
            var result = new List<PointList>();
            var p1 = new BasicGeoposition
            {
                Latitude = Math.Min(point1.Position.Latitude, point2.Position.Latitude),
                Longitude = Math.Min(point1.Position.Longitude, point2.Position.Longitude)
            };
            var p2 = new BasicGeoposition
            {
                Latitude = Math.Max(point1.Position.Latitude, point2.Position.Latitude),
                Longitude = Math.Max(point1.Position.Longitude, point2.Position.Longitude)
            };

            var dLat = p2.Latitude - p1.Latitude;
            var dLon = p2.Longitude - p1.Longitude;

            var r = new Random(DateTime.Now.Millisecond);
            for (var i = 0; i < nrOfPoints; i++)
            {
                var item = new PointList { Name = "Point " + i };
                item.Points.Add(new Geopoint(
                  new BasicGeoposition
                  {
                      Latitude = p1.Latitude + (r.NextDouble() * dLat),
                      Longitude = p1.Longitude + (r.NextDouble() * dLon)
                  }));
                result.Add(item);
            }
            return result;
        }
Example #9
0
 // TODO: test data
 private async void OnLoaded(object sender, RoutedEventArgs e)
 {
     var locator=new Geolocator();
     var geoposition = await locator.GetGeopositionAsync();
     UserLocation = new Geopoint(new BasicGeoposition
     {
         Latitude = geoposition.Coordinate.Latitude,
         Longitude = geoposition.Coordinate.Longitude
     });
     var file = await Package.Current.InstalledLocation.GetFileAsync(@"Assets\service-icon.png");
     var geolocator = new Geolocator();
     var myPosition = await geolocator.GetGeopositionAsync();
     Recipients = new[]
     {
         new Recipient
         {
             Name = "Recipient",
             Birthday = DateTime.Now.AddYears(-20),
             Latitude = myPosition.Coordinate.Latitude,
             Longitude = myPosition.Coordinate.Longitude,
             Description = "I'm so depressed...",
             IsActive = true,
             MainPhoto = await ConvertionExtensions.ReadFile(file)
         }
     };
 }
Example #10
0
        public async void refreshLoc()
        {
            try { 
            var accessStatus = await Geolocator.RequestAccessAsync();
            switch (accessStatus)
            {
                case GeolocationAccessStatus.Allowed:

                    // Get the current location.
                    Geolocator geolocator = new Geolocator();
                    Debug.WriteLine("recup position");
                    Geoposition pos = await geolocator.GetGeopositionAsync();
                    myLocation = pos.Coordinate.Point;
                    Debug.WriteLine(myLocation.SpatialReferenceId);
                    break;

                case GeolocationAccessStatus.Denied:
                    // Handle the case  if access to location is denied.
                    Debug.WriteLine("Geoloc denied");
                    break;

                case GeolocationAccessStatus.Unspecified:
                    Debug.WriteLine("Error unknow");
                    // Handle the case if  an unspecified error occurs.
                    break;
            }
            }
            catch
            {

            }
        }
Example #11
0
        void locator_PositionChanged(Geolocator sender, PositionChangedEventArgs args) {

            var position = args.Position;
            currentLocation = position.Coordinate.Point;
            string longiNew = position.Coordinate.Point.Position.Longitude.ToString();
            string latiNew = position.Coordinate.Point.Position.Latitude.ToString();
            
            //this.currentLocation = position.Coordinate.Point;
            //Zbog prčkanja po UI threadu 
            Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync
            (Windows.UI.Core.CoreDispatcherPriority.Normal, () => {



                if (longi != longiNew || lati != latiNew) {
                    UpdateMap(); //Ažuriraj poziciju na mapi
                    UpdateUICoords(); //ažuriraj prikaz na sučelju
                    UpdateFile(); //Ažuriraj poziciju u fajl    
                }
                
                if (longi != longiNew) longi = longiNew;
                if (lati != latiNew) lati = latiNew;     
                
            });
        }
Example #12
0
        public async Task GetNearMapItems(Geopoint currentGeopoint)
        {
            if (_currentElements == null)
            {
                _currentElements = await _cicloStationService.GetCicloStationsAsync();
            }

            var result = _currentElements.Select(pre => new MapItem()
            {
                Id = pre.id,
                Geopoint = new Geopoint(new BasicGeoposition()
                {
                    Latitude = pre.location.Lat,
                    Longitude = pre.location.Lon
                }),
                ItemType = ItemType.EcobiciStation,
                Name = pre.name
            });

            result = result
                .OrderBy(pre => pre.Geopoint.CalculateDistance(currentGeopoint))
                .Where(pre => pre.Geopoint.CalculateDistance(currentGeopoint) <= 1)
                .Take(5);

            GetNearMapItemsCompleted?.Invoke(this, new NearMapItemEventArgs(result));
        }
Example #13
0
        public async Task<MapLocation> GetPositionFromAddressAsync(string address)
        {
            var locator = new Geolocator();
            locator.DesiredAccuracyInMeters = 50;
            TimeSpan maxAge = new TimeSpan(0, 0, 1);
            TimeSpan timeout = new TimeSpan(0, 0, 15);
            // var position = await locator.GetGeopositionAsync();

            var basicGeoposition = new BasicGeoposition();
            var point = new Geopoint(basicGeoposition);

            var mapLocationFinderResult = await MapLocationFinder.FindLocationsAsync(address, point, 2);

            if (mapLocationFinderResult.Status == MapLocationFinderStatus.Success)
            {
                try
                {
                    return mapLocationFinderResult.Locations[0];
                }
                catch (Exception e)
                {
                    return null;
                }
                
                
            }

            return default(MapLocation);
        }
Example #14
0
        private async void button_Click(object sender, RoutedEventArgs e)
        {

            if (MapControl1.IsStreetsideSupported)
            {
                
                
               BasicGeoposition cityPosition = new BasicGeoposition() { Latitude = 48.858, Longitude = 2.295 };
                Geopoint cityCenter = new Geopoint(cityPosition);
                StreetsidePanorama panoramaNearCity = await StreetsidePanorama.FindNearbyAsync(cityCenter);

                
                if (panoramaNearCity != null)
                {
                    
                    StreetsideExperience ssView = new StreetsideExperience(panoramaNearCity);
                    ssView.OverviewMapVisible = true;
                    MapControl1.CustomExperience = ssView;
                }
            }
            else
            {
                
                ContentDialog viewNotSupportedDialog = new ContentDialog()
                {
                    Title = "Streetside is not supported",
                    Content = "\nStreetside views are not supported on this device.",
                    PrimaryButtonText = "OK"
                };
                await viewNotSupportedDialog.ShowAsync();
            }
        }
        async private void button_Click(object sender, RoutedEventArgs e)
        {
            LocationProvider providerLocation = new LocationProvider();

            var accessStatus = await Geolocator.RequestAccessAsync();

            switch (accessStatus)
            {
                case GeolocationAccessStatus.Allowed:

                    // If DesiredAccuracy or DesiredAccuracyInMeters are not set (or value is 0), DesiredAccuracy.Default is used.
                    Geolocator geolocator = new Geolocator { DesiredAccuracyInMeters = 2000 };

                    // Carry out the operation.
                    Geoposition pos = await geolocator.GetGeopositionAsync();
                    Geopoint geo = new Geopoint(new BasicGeoposition { Latitude = pos.Coordinate.Point.Position.Latitude, Longitude = pos.Coordinate.Point.Position.Longitude });

                    providerLocation.AddLocation(geo, 1);


                    this.Frame.Navigate(typeof(Friends), pos);

                    break;

                case GeolocationAccessStatus.Denied:

                    break;

                case GeolocationAccessStatus.Unspecified:

                    break;
            }

        }
Example #16
0
        //string imagerySet = MapType.Aerial.ToString();

        public async Task<WriteableBitmap> RequestImage(Geopoint point)
        {
            
            if (geo == null)
            {
                geo = new Geolocator();
            }
            Geoposition pos = await geo.GetGeopositionAsync();
            //Geopoint point = pos.Coordinate.Point;

            myMap.Center = new Location(point.Position.Latitude, point.Position.Longitude);
            myMap.ZoomLevel = 2;
            myMap.Width = 100;
            this.myMap.Height = 100;
            string url = String.Format("http://dev.virtualearth.net/REST/v1/Imagery/Map/{0}/{1},{2}/{3}" +
                                  "?mapSize={4},{5}&key={6}",
                               //imagerySet,
                               this.myMap.Center.Latitude,
                               this.myMap.Center.Longitude,
                               Math.Floor(this.myMap.ZoomLevel),
                               this.myMap.Width,
                               this.myMap.Height,
                               apiKey);


            var backgroundDownloader = new BackgroundDownloader();
            var file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("tempmapimage.jpg",
                CreationCollisionOption.ReplaceExisting);
            var downloadOperation = backgroundDownloader.CreateDownload(new Uri(url), file);

            await downloadOperation.StartAsync();
            return await BitmapFactory.New(1, 1).FromStream(await file.OpenReadAsync(),
                Windows.Graphics.Imaging.BitmapPixelFormat.Unknown);
        }
Example #17
0
        public AddMapa()
        {
            this.InitializeComponent();

            rootFrame = Window.Current.Content as Frame;

            SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility
                    = AppViewBackButtonVisibility.Visible;

            SystemNavigationManager.GetForCurrentView().BackRequested += AddMapa_BackRequested;

            mapControl.ZoomInteractionMode = MapInteractionMode.GestureAndControl;
            mapControl.TiltInteractionMode = MapInteractionMode.GestureAndControl;
            mapControl.MapServiceToken = "ift37edNFjWtwMkOrquL~7gzuj1f0EWpVbWWsBaVKtA~Amh-DIg5R0ZPETQo7V-k2m785NG8XugPBOh52EElcvxaioPYSYWXf96wL6E_0W1g";

            // Specify a known location

            BasicGeoposition posicion = new BasicGeoposition() { Latitude = 2.4448143, Longitude = -76.6147395 };
            Geopoint point = new Geopoint(posicion);

            // Set map location
            mapControl.Center = point;
            mapControl.ZoomLevel = 13.0f;
            mapControl.LandmarksVisible = true;

            AddIcons();

            //GridMapa.Children.Add(mapControl);

        }
        // http://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn631249.aspx
        public async Task<List<Portable.Model.GeocodeResult>> ExecuteQuery(string query)
        {
            throw new NotImplementedException("Not yet fully implemented, testing only");

            try
            {
                // TODO: center for Austria (lat, lon), hint Austria in search string
                BasicGeoposition queryHint = new BasicGeoposition();
                queryHint.Latitude = 47.643;
                queryHint.Longitude = -122.131;
                Geopoint hintPoint = new Geopoint(queryHint);

                MapLocationFinderResult result = await MapLocationFinder.FindLocationsAsync(query, hintPoint);

                if (result.Status == MapLocationFinderStatus.Success)
                {
                    return result.Locations.Select(l => new Portable.Model.GeocodeResult()
                    {
                        Latitude = l.Point.Position.Latitude,
                        Longitude = l.Point.Position.Longitude,
                        Name = l.DisplayName,
                    }).ToList();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            return new List<GeocodeResult>();
        }
Example #19
0
        public async void SaveNewNote()
        {
            if (!String.IsNullOrEmpty(NewTextTitle) && !String.IsNullOrEmpty(NewTextNote))
            {
                var access = await Geolocator.RequestAccessAsync();

                switch (access)
                {
                    case GeolocationAccessStatus.Allowed:

                        var geolocator = new Geolocator();
                        var geopositon = await geolocator.GetGeopositionAsync();
                        var geopoint = geopositon.Coordinate.Point;
                        NewNoteLocation = geopoint;

                        break;

                    case GeolocationAccessStatus.Unspecified:
                    case GeolocationAccessStatus.Denied:
                        break;
                }

                var note = new Note(NewTextTitle, NewTextNote, DateTime.Now, NewNoteLocation);
                await dataService.AddNote(note);
                NewTextTitle = String.Empty;
                NewTextNote = String.Empty;
                _navigationService.GoBack();

            }
        }
        private async void showSpaceNeedleButton_Click(object sender, RoutedEventArgs e)
        {
            if (myMap.Is3DSupported)
            {
                this.myMap.Style = MapStyle.Aerial3DWithRoads;

                BasicGeoposition spaceNeedlePosition = new BasicGeoposition();
                spaceNeedlePosition.Latitude = 47.6204;
                spaceNeedlePosition.Longitude = -122.3491;

                Geopoint spaceNeedlePoint = new Geopoint(spaceNeedlePosition);

                MapScene spaceNeedleScene = MapScene.CreateFromLocationAndRadius(spaceNeedlePoint,
                                                                                    400, /* show this many meters around */
                                                                                    135, /* looking at it to the south east*/
                                                                                    60 /* degrees pitch */);

                await myMap.TrySetSceneAsync(spaceNeedleScene);
            }
            else
            {
                string status = "3D views are not supported on this device.";
                rootPage.NotifyUser(status, NotifyType.ErrorMessage);
            }

           
        }
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)
		{
			Geopoint myPoint;

			if (e.Parameter == null)
			{
				//Add
				isViewing = false;

				var locator = new Geolocator();
				locator.DesiredAccuracyInMeters = 50;

				// MUST ENABLE THE LOCATION CAPABILITY!!
				var position = await locator.GetGeopositionAsync();
				myPoint = position.Coordinate.Point;
			}
			else
			{
				//View or Delete
				isViewing = true;

				lifeThread = (LifeThread)e.Parameter;
				titleTextBox.Text = lifeThread.Title;
				noteTextBox.Text = lifeThread.Thread;
				addButton.Content = "Delete";

				var myPosition = new Windows.Devices.Geolocation.BasicGeoposition();
				myPosition.Latitude = lifeThread.Latitude;
				myPosition.Longitude = lifeThread.Longitude;

				myPoint = new Geopoint(myPosition);
			}

			await MyMap.TrySetViewAsync(myPoint, 16d);
		}
Example #22
0
        public void addPinsToMap(MapControl mapControl, Action<MapPin> tappedCallback = null)
        {
            removePinsFromMap(mapControl);
            m_mapPins = new List<MapPin>();

            int i = 1;
            DB_station prevStation = null;
            foreach (List<DB_station> route in m_routes)
            {
                foreach(DB_station station in route)
                {
                    if (station == prevStation || (station.latitude == 0f && station.longitude == 0f))
                        continue;

                    // Title for station.
                    string title = "Przystanek " + (i++) + "\n" + station.post_id + " " + station.post_name + "\n" + station.street;

                    // Add pin into map.
                    var location = new Geopoint(new BasicGeoposition()
                    {
                        Latitude = station.latitude,
                        Longitude = station.longitude
                    });
                    MapPin pin = new MapPin(title, station, MapPin.PinType.RegularPin, MapPin.PinSize.Small, tappedCallback);
                    pin.addToMap(mapControl, location);
                    m_mapPins.Add(pin);
                    prevStation = station;
                }
            }
        }
        public MapsViewModel(MapControl mapControl)
        {
            _mapControl = mapControl;
            StopStreetViewCommand = new DelegateCommand(StopStreetView, () => IsStreetView);
            StartStreetViewCommand = new DelegateCommand(StartStreetViewAsync, () => !IsStreetView);

            if (!DesignMode.DesignModeEnabled)
            {
                _dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
            }

            _locator.StatusChanged += async (s, e) =>
            {
                await _dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                PositionStatus = e.Status
                );
            };

            // intialize defaults at startup
            CurrentPosition = new Geopoint(new BasicGeoposition { Latitude = 48.2, Longitude = 16.3 });
            // { Latitude = 47.604, Longitude = -122.329 });
            CurrentMapStyle = MapStyle.Road;
            DesiredPitch = 0;
            ZoomLevel = 12;
        }
 private async void handleResults(PhotoCollection results, ObservableCollection<ThumbnailImage> List)
 {
     foreach (var res in results)
     {
         Geopoint point = null;
         if (res.Longitude != 0 && res.Latitude != 0)
         {
             var position = new BasicGeoposition()
             {
                 Latitude = res.Latitude,
                 Longitude = res.Longitude
             };
             point = new Geopoint(position);
         }
         else if (res.Tags.Contains("cars"))
         {
             var position = new BasicGeoposition()
             {
                 Longitude = 13.416350,
                 Latitude = 52.526105
             };
             point = new Geopoint(position);
         }
         List.Add(new ThumbnailImage() { ImagePath = new Uri(res.ThumbnailUrl), ImageTitle = res.Title, BigImage = new Uri(res.LargeUrl), GeoLocation = point });
     }
 }
        private async void getAddressBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //Request permission to get location
                //Pop up will occur if your app doesnot have permission to access location service of device
                var accessStatus = await Geolocator.RequestAccessAsync();

                switch (accessStatus)
                {
                    case GeolocationAccessStatus.Allowed:
                        // The location to reverse geocode.
                        //For now i am getting my current location
                        Geolocator geolocator = new Geolocator { DesiredAccuracyInMeters = 50, DesiredAccuracy = PositionAccuracy.High }; //Set the desired accuracy that you want in meters
                        Geoposition pos = await geolocator.GetGeopositionAsync();


                        BasicGeoposition location = new BasicGeoposition();
                        location.Latitude = pos.Coordinate.Point.Position.Latitude;
                        location.Longitude = pos.Coordinate.Point.Position.Longitude;

                        Geopoint pointToReverseGeocode = new Geopoint(location);

                        // Reverse geocode the specified geographic location.
                        MapLocationFinderResult result =
                              await MapLocationFinder.FindLocationsAtAsync(pointToReverseGeocode);

                        // If the query returns results, display the name of the town
                        // contained in the address of the first result.
                        if (result.Status == MapLocationFinderStatus.Success)
                        {
                            continent.Text = result.Locations[0].Address.Continent;
                            countryName.Text = result.Locations[0].Address.Country;
                            countryCode.Text = result.Locations[0].Address.CountryCode;
                            region.Text = result.Locations[0].Address.Region;
                            town.Text = result.Locations[0].Address.Town;
                            street.Text = result.Locations[0].Address.Street;
                        }
                        else
                        {
                            await new MessageDialog("Something went wrong. Could not get finish current operation. Error: " + result.Status).ShowAsync();
                        }
                        break;

                    case GeolocationAccessStatus.Denied:
                        //Unable to get data
                        LoadPositionData(null);
                        break;

                    case GeolocationAccessStatus.Unspecified:
                        //Unable to get data
                        LoadPositionData(null);
                        break;
                }
            }
            catch (Exception ex)
            {
                await new MessageDialog("Something went wrong. Could not get finish current operation.").ShowAsync();
            }
        }
 /// <summary>
 /// constructor
 /// </summary>
 public PushPin(string description, Geopoint geopoint, string address)
 {
     InitializeComponent();
     _description = description;
     _geopoint = geopoint;
     _address = address;
     Loaded += PushPin_Loaded;
 }
		public BusStop(string Code, string Name, string FleetOver, Geopoint geo)
		{
			this.Code = Code;
			this.Name = Name;
			this.FleetOver = FleetOver;
			this.geo = geo;
			arrayNode = new List<BusNode>();
		}
Example #28
0
        public static GeoboundingBox GetBounds(this MapControl map, double extraPercentage)
        {
            Geopoint topLeft = null;

            try
            {
                map.GetLocationFromOffset(new Point(0, 0), out topLeft);
            }
            catch
            {
                var topOfMap = new Geopoint(new BasicGeoposition()
                {
                    Latitude = 85,
                    Longitude = 0
                });

                Point topPoint;
                map.GetOffsetFromLocation(topOfMap, out topPoint);
                map.GetLocationFromOffset(new Point(0, topPoint.Y), out topLeft);
            }

            Geopoint bottomRight = null;
            try
            {
                map.GetLocationFromOffset(new Point(map.ActualWidth, map.ActualHeight), out bottomRight);
            }
            catch
            {
                var bottomOfMap = new Geopoint(new BasicGeoposition()
                {
                    Latitude = -85,
                    Longitude = 0
                });

                Point bottomPoint;
                map.GetOffsetFromLocation(bottomOfMap, out bottomPoint);
                map.GetLocationFromOffset(new Point(0, bottomPoint.Y), out bottomRight);
            }

            if (topLeft != null && bottomRight != null)
            {
                var width = Abs(bottomRight.Position.Longitude - topLeft.Position.Longitude);
                var height = Abs(bottomRight.Position.Latitude - topLeft.Position.Latitude);
                var adjustedTopLeft = new BasicGeoposition()
                {
                    Latitude = topLeft.Position.Latitude + extraPercentage * height,
                    Longitude = topLeft.Position.Longitude - extraPercentage * width,
                };
                var adjustedBottomRight = new BasicGeoposition()
                {
                    Latitude = bottomRight.Position.Latitude - extraPercentage * height,
                    Longitude = bottomRight.Position.Longitude + extraPercentage * width,
                };
                return new GeoboundingBox(adjustedTopLeft, adjustedBottomRight);
            }

            return null;
        }
Example #29
0
 private void buttonJayway_Click(object sender, RoutedEventArgs e)
 {
     var jayway = new Geopoint(new BasicGeoposition() { Latitude = 55.6127809826285, Longitude = 13.0031764693558 });
     var youPin = CreatePin();
     map1.Children.Add(youPin);
     MapControl.SetLocation(youPin, jayway);
     MapControl.SetNormalizedAnchorPoint(youPin, new Point(0.0, 1.0));
     map1.TrySetViewAsync(jayway, 15, 0, 0, MapAnimationKind.Bow);
 }
 private async void Panorama_Click(object sender, RoutedEventArgs e)
 {
     BasicGeoposition cityPosition = new BasicGeoposition() { Latitude = 48.858, Longitude = 2.295 };
     Geopoint cityCenter = new Geopoint(cityPosition);
     StreetsidePanorama panoramaNearCity = await StreetsidePanorama.FindNearbyAsync(cityCenter);
     StreetsideExperience ssView = new StreetsideExperience(panoramaNearCity);
     ssView.OverviewMapVisible = true;
     MapControl1.CustomExperience = ssView;
 }
Example #31
0
        private async Task UpdateMap()
        {
            if (LocationServiceHelper.Instance.Geoposition != null)
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                {
                    try
                    {
                        // Set player icon's position
                        MapControl.SetLocation(PlayerImage, LocationServiceHelper.Instance.Geoposition.Coordinate.Point);
                        // Update Day/Night theme
                        GameMapControl.ColorScheme = ViewModel.CurrentTheme == ElementTheme.Dark
                        ? MapColorScheme.Dark
                        : MapColorScheme.Light;

                        // Update angle and center only if map is not being manipulated
                        if (lastAutoPosition == null)
                        {
                            //Reset of position or first run
                            //Save Center
                            lastAutoPosition = GameMapControl.Center;
                            //Reset orientation to default
                            if (double.IsNaN(GameMapControl.Heading))//DarkAngel: I love non nullable double that can be "!= null and not a number"...
                            {
                                await GameMapControl.TryRotateToAsync(0);
                            }
                        }

                        //Small Trick: I'm not testing lastAutoPosition == GameMapControl.Center because MapControl is not taking exact location when setting center!!
                        string currentCoord =
                            $"{GameMapControl.Center.Position.Latitude: 000.0000} ; {GameMapControl.Center.Position.Longitude: 000.0000}";
                        string previousCoord =
                            $"{lastAutoPosition.Position.Latitude: 000.0000} ; {lastAutoPosition.Position.Longitude: 000.0000}";
                        if (currentCoord == previousCoord && ReactivateMapAutoUpdateButton != null)
                        {
                            //Previous position was set automatically, continue!
                            ReactivateMapAutoUpdateButton.Visibility = Visibility.Collapsed;
                            GameMapControl.Center = LocationServiceHelper.Instance.Geoposition.Coordinate.Point;

                            lastAutoPosition = GameMapControl.Center;

                            if ((SettingsService.Instance.MapAutomaticOrientationMode == MapAutomaticOrientationModes.GPS) &&
                                (
                                    LocationServiceHelper.Instance.Geoposition.Coordinate.Heading.GetValueOrDefault(-1) >= 0 &&
                                    LocationServiceHelper.Instance.Geoposition.Coordinate.Heading.GetValueOrDefault(-1) <= 360
                                ))
                            {
                                await GameMapControl.TryRotateToAsync(LocationServiceHelper.Instance.Geoposition.Coordinate.Heading.GetValueOrDefault(GameMapControl.Heading));
                            }
                            if (SettingsService.Instance.IsRememberMapZoomEnabled)
                            {
                                GameMapControl.ZoomLevel = SettingsService.Instance.Zoomlevel;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        await ExceptionHandler.HandleException(ex);
                    }
                });
            }
        }
Example #32
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            var cameFrom = this.Frame.BackStack.LastOrDefault();

            if (cameFrom != null && e.Parameter != null)
            {
                if (cameFrom.SourcePageType == typeof(GroupPage))
                {
                    var model = e.Parameter as Map;
                    MapViewModel.Map = model;

                    _currentMap = model.Id; // current mapId

                    // locationIds + locationsData (longtitute / latitute)
                    _locationsAssociated = await MapViewModel.GetLocationsAssociatedWithMap(_currentMap);

                    _locationsData = await MapViewModel.GetLocationsDataAssociatedWithMap(_locationsAssociated);


                    var landmarks = _points;
                    // if locations exists will be displayed on the map
                    foreach (MapLocation loc in _locationsAssociated)
                    {
                        if (loc != null)
                        {
                            var currentLocation = loc.LocationId;
                            var note            = await MapViewModel.GetAssociatedNoteData(currentLocation);

                            // get the longt and lat
                            BasicGeoposition _pos = new BasicGeoposition {
                                Latitude = Convert.ToDouble(loc.Location.Latitude), Longitude = Convert.ToDouble(loc.Location.Longitude)
                            };
                            Geopoint _position = new Geopoint(_pos);

                            var _spaceNeedleIcon = new MapIcon
                            {
                                Location = _position,
                                NormalizedAnchorPoint = new Point(0.5, 1.0),
                                ZIndex = 0,
                                // point will be added with defined name
                                Title = note.Title
                            };

                            landmarks.Add(_spaceNeedleIcon);

                            var LandMarksLayer = new MapElementsLayer
                            {
                                ZIndex      = 1,
                                MapElements = landmarks
                            };

                            MemoMap.Layers.Add(LandMarksLayer);
                        }
                        else if (loc == null) // if there are no points in the database related with current map
                        {
                            return;           // exit the loop
                        }
                    }
                }
                else
                {
                    var model = (e.Parameter as UserMap).Map;
                    MapViewModel.Map = model;    // the current map will be loaded in MapViewModel.Map
                    _currentMap      = model.Id; // current mapId

                    // locationIds + locationsData (longtitute / latitute)
                    _locationsAssociated = await MapViewModel.GetLocationsAssociatedWithMap(_currentMap);

                    _locationsData = await MapViewModel.GetLocationsDataAssociatedWithMap(_locationsAssociated);


                    var landmarks = _points;
                    // if locations exists will be displayed on the map
                    foreach (MapLocation loc in _locationsAssociated)
                    {
                        if (loc != null)
                        {
                            var currentLocation = loc.LocationId;
                            var note            = await MapViewModel.GetAssociatedNoteData(currentLocation);

                            // get the longt and lat
                            BasicGeoposition _pos = new BasicGeoposition {
                                Latitude = Convert.ToDouble(loc.Location.Latitude), Longitude = Convert.ToDouble(loc.Location.Longitude)
                            };
                            Geopoint _position = new Geopoint(_pos);

                            var _spaceNeedleIcon = new MapIcon
                            {
                                Location = _position,
                                NormalizedAnchorPoint = new Point(0.5, 1.0),
                                ZIndex = 0,
                                // point will be added with defined name
                                Title = note.Title
                            };

                            landmarks.Add(_spaceNeedleIcon);

                            var LandMarksLayer = new MapElementsLayer
                            {
                                ZIndex      = 1,
                                MapElements = landmarks
                            };

                            MemoMap.Layers.Add(LandMarksLayer);
                        }
                        else if (loc == null) // if there are no points in the database related with current map
                        {
                            return;           // exit the loop
                        }
                    }

                    base.OnNavigatedTo(e);
                }
            }
        }
 /// <summary>
 /// <see cref="Windows.UI.Xaml.Controls.Maps.MapControl.GetOffsetFromLocation"/>
 /// </summary>
 public void GetOffsetFromLocation(Geopoint location, out Point offset)
 {
     UwpControl.GetOffsetFromLocation(location.UwpInstance, out Windows.Foundation.Point uwpOffset);
     offset = new Point(uwpOffset);
 }
        /*
         * /// <summary>
         * /// <see cref="Windows.UI.Xaml.Controls.Maps.MapControl.TrySetViewBoundsAsync"/>
         * /// </summary>
         * /// <returns>IAsyncOperation</returns>
         * public Task<bool> TrySetViewBoundsAsync(GeoboundingBox bounds, Windows.UI.Xaml.Thickness? margin, MapAnimationKind animation) => UwpControl.TrySetViewBoundsAsync(bounds, margin, animation);
         */

        /// <summary>
        /// <see cref="Windows.UI.Xaml.Controls.Maps.MapControl"/>
        /// </summary>
        /// <returns>IAsyncOperation</returns>
        public Task <bool> TrySetViewAsync(Geopoint center) => UwpControl.TrySetViewAsync(center.UwpInstance).AsTask();
 /// <summary>
 /// <see cref="Windows.UI.Xaml.Controls.Maps.MapControl"/>
 /// </summary>
 /// <returns>IAsyncOperation</returns>
 public Task <bool> TrySetViewAsync(Geopoint center, double?zoomLevel, double?heading, double?desiredPitch) => UwpControl.TrySetViewAsync(center.UwpInstance, zoomLevel, heading, desiredPitch).AsTask();
 /// <summary>
 /// <see cref="Windows.UI.Xaml.Controls.Maps.MapControl"/>
 /// </summary>
 /// <returns>IAsyncOperation</returns>
 public Task <bool> TrySetViewAsync(Geopoint center, double?zoomLevel, double?heading, double?desiredPitch, MapAnimationKind animation) => UwpControl.TrySetViewAsync(center.UwpInstance, zoomLevel, heading, desiredPitch, (Windows.UI.Xaml.Controls.Maps.MapAnimationKind)(int) animation).AsTask();
Example #37
0
 public PjcStore(string name, StoreType storeType, Geopoint geopoint)
 {
     Name      = name;
     StoreType = storeType;
     Geopoint  = geopoint;
 }
Example #38
0
        public static void SetViewArea(this MapControl map, Geopoint p1, Geopoint p2)
        {
            var b = GeoboundingBox.TryCompute(new[] { p1.Position, p2.Position });

            map.TrySetViewBoundsAsync(b, new Thickness(1.0), MapAnimationKind.Bow);
        }
Example #39
0
        //this part is to handel the different states of the GPS
        private async void geolocator_StatusChanged(Geolocator sender, StatusChangedEventArgs args)
        {
            string status = "";

            switch (args.Status)
            {
            case PositionStatus.Disabled:
                await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    status              = "GPS Disabled";
                    gpsoff.Opacity      = 1;
                    refresher.Opacity   = 1;
                    refresher.IsEnabled = true;
                });

                break;

            case PositionStatus.Initializing:
                await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    status              = "Initializing";
                    gpsoff.Opacity      = 0;
                    refresher.Opacity   = 0;
                    refresher.IsEnabled = false;
                });

                break;

            //when gps is ready
            case PositionStatus.Ready:         status = "GPS is ready";
                //finding the longitude and latitude
                var position = await locator.GetGeopositionAsync();

                MainPage.MyLongitude = position.Coordinate.Longitude.ToString();
                MainPage.MyLatitude  = position.Coordinate.Latitude.ToString();
                BasicGeoposition myLocation = new BasicGeoposition
                {
                    Longitude = position.Coordinate.Longitude,
                    Latitude  = position.Coordinate.Latitude
                };
                //finding the exact place the town, region
                Geopoint pointToReverseGeocode = new Geopoint(myLocation);
                MapLocationFinderResult result = await MapLocationFinder.FindLocationsAtAsync(pointToReverseGeocode);

                await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    MainPage.MyWilaya  = result.Locations[0].Address.Region;
                    MainPage.MyCountry = result.Locations[0].Address.Country;
                    MainPage.MyCommune = result.Locations[0].Address.Town;
                    header.Text        = "Latitude " + MainPage.MyLatitude +
                                         "Longitude " + MainPage.MyLongitude +
                                         "Country " + MainPage.MyCountry +
                                         "Commune " + MainPage.MyCommune +
                                         "Wilaya  " + MainPage.MyWilaya;
                    //this place is to hide the progress ring and display the main menu button
                    main_ring.IsActive    = false;
                    Compagnship.IsEnabled = true;
                    Compagnship.Opacity   = 1;
                    urgent.IsEnabled      = true;
                    urgent.Opacity        = 1;
                    reparation.IsEnabled  = true;
                    reparation.Opacity    = 1;
                    volunteer.IsEnabled   = true;
                    volunteer.Opacity     = 1;
                    main_textblock.Text   = "";
                });

                break;

            case PositionStatus.NotAvailable:
            case PositionStatus.NotInitialized:
            case PositionStatus.NoData:
                break;
            }
            //this is the dispatcher is to modify the GUI thread values from a different thread
            await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { header.Text = status; });
        }
Example #40
0
 private void Instance_OnBuddyLocationUpdate(Geopoint obj)
 {
     BuddyLocation = obj;
 }
Example #41
0
        public MainPage()
        {
            InitializeComponent();

            if (ResponsiveStateGroup.CurrentState == desktopViewVisualState)
            {
                //this should use "-1 * CoreApplication.GetCurrentView().TitleBar.Height" but it returns 0 at this point :(
                SetMapBottomMargin(-32);
            }

            NavigationCacheMode = NavigationCacheMode.Required;

            CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar = true;

            Map.Loaded += async(sender, args) =>
            {
                SetMapBottomMargin(0);

                Debug.WriteLine("[MainView] map: map loaded");
                if (_initialMapBbox != null)
                {
                    Debug.WriteLine("[MainView] map: map loaded, set initial bounds");
                    await Map.TrySetViewBoundsAsync(_initialMapBbox, null, MapAnimationKind.None);

                    _zoomedToInitialView = true;
                }
                else if (_initialCoordinates != null)
                {
                    Debug.WriteLine("[MainView] map: map loaded, set initial coords");
                    await Map.TrySetViewAsync(_initialCoordinates, null, null, null, MapAnimationKind.None);

                    _zoomedToInitialView = true;
                }
                _mapLoaded = true;
            };

            Messenger.Default.Register(this, (ZoomMapToBoundsMessage msg) =>
            {
                if (!_mapLoaded)
                {
                    _initialMapBbox = msg.BoundingBox;
                    //set initial bbox as the following won't work while splash screen is still visible
                }
                else
                {
                    DispatcherHelper.CheckBeginInvokeOnUI(async() =>
                    {
                        Debug.WriteLine("[MainView] map: zoom map to bounds msg");
                        await Map.TrySetViewBoundsAsync(msg.BoundingBox, null, MapAnimationKind.Bow);
                        _zoomedToInitialView = _mapLoaded;
                    });
                }
            });

            Messenger.Default.Register(this, (ZoomMapToCoordinateMessage msg) =>
            {
                if (!_mapLoaded)
                {
                    _initialCoordinates = msg.Point;
                    //set initial coordinates as the following won't work while splash screen is still visible
                }
                else
                {
                    DispatcherHelper.CheckBeginInvokeOnUI(async() =>
                    {
                        Debug.WriteLine("[MainView] map: zoom map to coordinates msg");
                        await
                        Map.TrySetViewAsync(msg.Point, null, null, null, MapAnimationKind.Bow);
                        _zoomedToInitialView = _mapLoaded;
                    });
                }
            });

            Messenger.Default.Register(this, (ShowSearchResultOnMapMessage msg) =>
            {
                DispatcherHelper.CheckBeginInvokeOnUI(async() =>
                {
                    DrawingService.DrawSearchResult(Map, msg.Result);
                    Debug.WriteLine("[MainView] map: show search result - wait until initial view was zoomed to");
                    await WaitForInitialMapZoom();
                    Debug.WriteLine("[MainView] map: show search result");
                    await Map.TrySetViewAsync(msg.Result.Point, null, null, null, MapAnimationKind.Bow);
                });
            });

            Messenger.Default.Register(this, (HideSearchResultOnMapMessage msg) =>
            {
                DrawingService.RemoveSearchResult(Map);
            });

            Messenger.Default.Register(this, (InfoDialogToggleVisibilityMessage msg) =>
            {
                FindName(nameof(InfoDialog));
                _infoDialogVisible    = msg.IsVisible;
                InfoDialog.Visibility = msg.Visibility;
            });

            Messenger.Default.Register(this, async(UpdateParkingLotListSelectionMessage msg) =>
            {
                Debug.WriteLine("[MainView] update parking lot list: message received");
                SetParkingLotListSelectionVisualState();
            });

            Vm.PropertyChanged += OnViewModelPropertyChanged;

            ParkingLotList.SelectionChanged += (sender, args) =>
            {
                try
                {
                    ParkingLotList.ScrollIntoView(ParkingLotList.SelectedItem);
                }
                catch (Exception)
                {
                    Debug.WriteLine("Cannot scroll currenct parking lot list item...");
                }
            };

            Map.MapElementClick += (sender, args) =>
            {
                Vm.SelectedParkingLot = DrawingService.GetParkingLotOfIcon(args.MapElements.GetTopmostIcon());
            };

            SystemNavigationManager.GetForCurrentView().BackRequested += (sender, args) =>
            {
                if (_infoDialogVisible)
                {
                    Messenger.Default.Send(new InfoDialogToggleVisibilityMessage(false));
                    args.Handled = true;
                }
            };

            UpdateParkingLotFilter();
        }
Example #42
0
        public Malaria()
        {
            this.InitializeComponent();
            double minx = 25.216945;
            double miny = 82.870921;
            double maxx = 25.347000;
            double maxy = 83.105367;

            Random random = new Random();
            int    i, j;
            int    noclus = 9, pop = 50;

            for (i = 0; i < pop; i++)
            {
                cx[i]     = new double();
                cy[i]     = new double();
                clusno[i] = new int();
                cx[i]     = minx + (maxx - minx) * random.NextDouble();
                cy[i]     = miny + (maxy - miny) * random.NextDouble();
            }


            for (i = 0; i < noclus; i++)
            {
                clusx[i] = new double();
                clusy[i] = new double();
                clusx[i] = minx + (maxx - minx) * random.NextDouble();
                clusy[i] = miny + (maxy - miny) * random.NextDouble();
            }

            int    iter = 0, maxiter = 5, p;
            double m1, m2, sx, sy;

            List <int>[] lista = new List <int> [10];
            while (iter < maxiter)
            {
                for (i = 0; i < noclus; i++)
                {
                    lista[i] = new List <int>();
                }
                for (i = 0; i < pop; i++)
                {
                    m1 = dis(cx[i], cy[i], clusx[0], clusy[0]);
                    p  = 0;
                    for (j = 1; j < noclus; j++)
                    {
                        m2 = dis(cx[i], cy[i], clusx[j], clusy[j]);
                        if (m2 < m1)
                        {
                            m1 = m2;
                            p  = j;
                        }
                    }
                    lista[p].Add(i);
                    clusno[i] = p;
                }
                for (i = 0; i < noclus; i++)
                {
                    sx = 0;
                    sy = 0;
                    for (j = 0; j < lista[i].Count; j++)
                    {
                        sx += cx[lista[i][j]];
                        sy += cy[lista[i][j]];
                    }
                    clusx[i] = sx / lista[i].Count;
                    clusy[i] = sy / lista[i].Count;
                }

                iter++;
            }

            for (i = 0; i < pop; i++)
            {
                // Create a MapIcon.
                BasicGeoposition snPosition = new BasicGeoposition()
                {
                    Latitude = cx[i], Longitude = cy[i]
                };
                Geopoint snPoint = new Geopoint(snPosition);
                list[i] = new MapIcon();
                list[i].NormalizedAnchorPoint = new Point(0.5, 1.0);
                list[i].Location = snPoint;
                //list[i].Title = "Point" + clusno[i].ToString();
                list[i].ZIndex = 0;
                if (clusno[i] == 0)
                {
                    list[i].Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/red.png"));
                }
                else if (clusno[i] == 1)
                {
                    list[i].Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/green.png"));
                }
                else if (clusno[i] == 2)
                {
                    list[i].Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/yellow.png"));
                }
                else if (clusno[i] == 3)
                {
                    list[i].Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/blue.png"));
                }
                else if (clusno[i] == 4)
                {
                    list[i].Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/orange.png"));
                }
                else if (clusno[i] == 5)
                {
                    list[i].Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/cyan.png"));
                }
                else if (clusno[i] == 6)
                {
                    list[i].Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/maroon.png"));
                }
                else if (clusno[i] == 7)
                {
                    list[i].Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/purple.png"));
                }
                else if (clusno[i] == 8)
                {
                    list[i].Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/pink.png"));
                }

                list[i].CollisionBehaviorDesired = MapElementCollisionBehavior.RemainVisible;

                // Add the MapIcon to the map.
                Map.MapElements.Add(list[i]);
            }

            double userx = 25.262078;
            double usery = 82.993473;

            BasicGeoposition cPosition = new BasicGeoposition()
            {
                Latitude = userx, Longitude = usery
            };
            Geopoint cPoint = new Geopoint(cPosition);
            MapIcon  user   = new MapIcon();

            user.NormalizedAnchorPoint = new Point(0.5, 1.0);
            user.ZIndex   = 0;
            user.Location = cPoint;
            user.Image    = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/star.png"));
            user.CollisionBehaviorDesired = MapElementCollisionBehavior.RemainVisible;
            Map.MapElements.Add(user);

            Map.Center    = cPoint;
            Map.ZoomLevel = 12.5;

            m1 = dis(cx[0], cy[0], userx, usery);
            p  = 0;
            for (i = 1; i < noclus; i++)
            {
                m2 = dis(cx[i], cy[i], userx, usery);
                if (m2 < m1)
                {
                    m1 = m2;
                    p  = i;
                }
            }
            int flag = 0;

            if (lista[p].Count > 20)
            {
                flag = 1;
            }

            if (flag == 1)
            {
                ShowToast("\n\nBe precautious!\n\n", "\n\nThere is a high number of cases of Malaria near your location. Do take appropriate precautionary measures.\n");
            }
        }
 public MapPageViewModel()
 {
     _locationService = new LocationService();
     Center           = new Geopoint(_defaultPosition);
     ZoomLevel        = DefaultZoomLevel;
 }
Example #44
0
        private async void OriginTxt_SuggestionChosen(AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args)
        {
            var pre = args.SelectedItem as PlaceAutoComplete.Prediction;

            if (pre == null)
            {
                return;
            }
            sender.Text = pre.description;

            if (pre.description == "MyLocation")
            {
                if (sender.Name == "OriginTxt")
                {
                    var p = (await ViewModel.MapViewVM.GeoLocate.GetGeopositionAsync()).Coordinate.Point;
                    DirectionsMainUserControl.Origin = p;
                    DirectionsMainUserControl.AddPointer(p, "Origin");
                }
                else if (sender.Name == "DestTxt")
                {
                    var p = (await ViewModel.MapViewVM.GeoLocate.GetGeopositionAsync()).Coordinate.Point;
                    DirectionsMainUserControl.Destination = p;
                    DirectionsMainUserControl.AddPointer(p, "Destination");
                }
                else
                {
                    var index = sender.Name.Replace("WayPoint", string.Empty);
                    DirectionsMainUserControl.WayPoints[Convert.ToInt32(index)] = (await ViewModel.MapViewVM.GeoLocate.GetGeopositionAsync()).Coordinate.Point;
                }
            }
            else if (pre.description.StartsWith("Saved:"))
            {
                var savedplaces = SavedPlacesVM.GetSavedPlaces();
                var res         = savedplaces.Where(x => x.PlaceName == pre.description.Replace("Saved:", string.Empty)).FirstOrDefault();
                if (sender.Name == "OriginTxt")
                {
                    var p = new Geopoint(new BasicGeoposition()
                    {
                        Latitude = res.Latitude, Longitude = res.Longitude
                    });
                    DirectionsMainUserControl.Origin = p;
                    DirectionsMainUserControl.AddPointer(p, "Origin");
                }
                else if (sender.Name == "DestTxt")
                {
                    var p = new Geopoint(new BasicGeoposition()
                    {
                        Latitude = res.Latitude, Longitude = res.Longitude
                    });
                    DirectionsMainUserControl.Destination = p;
                    DirectionsMainUserControl.AddPointer(p, "Destination");
                }
                else
                {
                    var index = sender.Name.Replace("WayPoint", string.Empty);
                    DirectionsMainUserControl.WayPoints[Convert.ToInt32(index)] = new Geopoint(new BasicGeoposition()
                    {
                        Latitude = res.Latitude, Longitude = res.Longitude
                    });
                }
            }
            else
            {
                var res = await GeocodeHelper.GetInfo(pre.place_id);

                if (res == null)
                {
                    return;
                }
                var ploc = res.results.FirstOrDefault().geometry.location;
                if (sender.Name == "OriginTxt")
                {
                    var p = new Geopoint(new BasicGeoposition()
                    {
                        Latitude = ploc.lat, Longitude = ploc.lng
                    });
                    DirectionsMainUserControl.Origin = p;
                    DirectionsMainUserControl.AddPointer(p, "Origin");
                }
                else if (sender.Name == "DestTxt")
                {
                    var p = new Geopoint(new BasicGeoposition()
                    {
                        Latitude = ploc.lat, Longitude = ploc.lng
                    });
                    DirectionsMainUserControl.Destination = p;
                    DirectionsMainUserControl.AddPointer(p, "Destination");
                }
                else
                {
                    var index = sender.Name.Replace("WayPoint", string.Empty);
                    DirectionsMainUserControl.WayPoints[Convert.ToInt32(index)] = new Geopoint(new BasicGeoposition()
                    {
                        Latitude = ploc.lat, Longitude = ploc.lng
                    });
                }
            }
        }
Example #45
0
        // Simone Marra
        private void UpdateCornersBounds(MapControl map)
        {
            Geopoint topLeft     = null;
            Geopoint topRight    = null;
            Geopoint bottomLeft  = null;
            Geopoint bottomRight = null;

            // TODO: [Simone] I'm not sure about the catch code... I have not tested it yet!

            try
            {
                map.GetLocationFromOffset(new Windows.Foundation.Point(0, 0), out topLeft);
            }
            catch
            {
                var topOfMap = new Geopoint(new BasicGeoposition()
                {
                    Latitude  = 85,
                    Longitude = 0
                });

                map.GetOffsetFromLocation(topOfMap, out Windows.Foundation.Point topPoint);
                map.GetLocationFromOffset(new Windows.Foundation.Point(0, topPoint.Y), out topLeft);
            }

            try
            {
                map.GetLocationFromOffset(new Windows.Foundation.Point(map.ActualWidth, 0), out topRight);
            }
            catch
            {
                var topOfMap = new Geopoint(new BasicGeoposition()
                {
                    Latitude  = 85,
                    Longitude = 0
                });

                map.GetOffsetFromLocation(topOfMap, out Windows.Foundation.Point topPoint);
                map.GetLocationFromOffset(new Windows.Foundation.Point(topPoint.X, topPoint.Y), out topRight);
            }

            try
            {
                map.GetLocationFromOffset(new Windows.Foundation.Point(map.ActualWidth, map.ActualHeight), out bottomRight);
            }
            catch
            {
                var bottomOfMap = new Geopoint(new BasicGeoposition()
                {
                    Latitude  = -85,
                    Longitude = 0
                });

                map.GetOffsetFromLocation(bottomOfMap, out Windows.Foundation.Point bottomPoint);
                map.GetLocationFromOffset(new Windows.Foundation.Point(bottomPoint.X, bottomPoint.Y), out bottomRight);
            }

            try
            {
                map.GetLocationFromOffset(new Windows.Foundation.Point(0, map.ActualHeight), out bottomLeft);
            }
            catch
            {
                var bottomOfMap = new Geopoint(new BasicGeoposition()
                {
                    Latitude  = -85,
                    Longitude = 0
                });

                map.GetOffsetFromLocation(bottomOfMap, out Windows.Foundation.Point bottomPoint);
                map.GetLocationFromOffset(new Windows.Foundation.Point(0, bottomPoint.Y), out bottomLeft);
            }

            if ((topLeft != null) && (topRight != null) && (bottomLeft != null) && (bottomRight != null))
            {
                var farLeft   = new Position(topLeft.Position.Latitude, topLeft.Position.Longitude);
                var farRight  = new Position(topRight.Position.Latitude, topRight.Position.Longitude);
                var nearLeft  = new Position(bottomLeft.Position.Latitude, bottomLeft.Position.Longitude);
                var nearRight = new Position(bottomRight.Position.Latitude, bottomRight.Position.Longitude);

                Element.Region = new MapRegion(nearLeft, nearRight, farLeft, farRight);
            }
        }
Example #46
0
 public static Location ToLocation(this Geopoint location)
 {
     return(new Location(location.Position.Latitude, location.Position.Longitude));
 }
Example #47
0
        private async void Map_Loaded(object sender, RoutedEventArgs e)
        {
            errormessage.Text = "";
            string apiKey = "";

            //Create an HTTP client object
            HttpClient httpClient1 = new HttpClient();

            Uri requestUri1 = new Uri("https://funcappformail.azurewebsites.net/api/GPSGetKey?code=DP9x6xuw5LrZ09paLdpRkaIXSu2Ad4sjX3nJL6C1WauW5UikOW7W1g==");

            HttpStringContent stringContent = new HttpStringContent(
                "{ \"key\": \"key\"}",
                UnicodeEncoding.Utf8, "application/json");

            try
            {
                HttpResponseMessage getResponse = await httpClient1.PostAsync(requestUri1, stringContent);

                if ((int)getResponse.StatusCode != 200)
                {
                    errormessage.Text = getResponse.StatusCode.ToString();
                }
                else
                {
                    apiKey = await getResponse.Content.ReadAsStringAsync();

                    apiKey = apiKey.Remove(0, 1);
                    apiKey = apiKey.Remove(apiKey.Length - 1, 1);
                }
            }
            catch (Exception ex)
            {
                if (ex.HResult.ToString("X") == "80072EE7")
                {
                    errormessage.Text = "Error: " + ex.HResult.ToString("X") + " Message: check your internet connection";
                }
                else
                {
                    errormessage.Text = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
                }
            }
            ///////////////////////////////////////////////////////////////////////////
            System.Diagnostics.Debug.Write("line 120 " + Globals._email);
            if (PMap.IsEnabled)
            {
                //PMap.Style = MapStyle;
                PMap.Style = MapStyle.Terrain;

                PMap.MapServiceToken = apiKey;
                System.Diagnostics.Debug.Write("line 132 " + Globals._email);
                HttpClient httpClient = new HttpClient();
                Uri        requestUri = new Uri("https://firsthellojunk.azurewebsites.net/api/FetchPatient?code=LBn9ZSPhn7U5ZsKYaC4ICiP5KX6v/tcpxj855db4Vh6p8lsR2FAHUA==&email=" + Globals._email + "&password=nopw");

                try
                {
                    HttpResponseMessage response = await httpClient.GetAsync(requestUri);

                    if ((int)response.StatusCode != 200)

                    {
                        System.Diagnostics.Debug.Write("line 136 " + Globals._email);
                        errormessage.Text = "patient info unavailable";
                    }
                    else
                    {
                        var textResponse = await response.Content.ReadAsStringAsync();

                        var settings              = textResponse.Trim('"').Split(',');
                        var readsLatitude         = settings[8].Split(' ');
                        var readsLatitudeString   = readsLatitude[readsLatitude.Length - 1];
                        var readsLongtitude       = settings[9].Split(' ');
                        var readsLongtitudeString = readsLongtitude[readsLongtitude.Length - 1];
                        System.Diagnostics.Debug.Write("line 148 " + readsLongtitudeString);
                        BasicGeoposition location = new BasicGeoposition();
                        location.Latitude  = double.Parse(readsLatitudeString, System.Globalization.CultureInfo.InvariantCulture);
                        location.Longitude = double.Parse(readsLongtitudeString, System.Globalization.CultureInfo.InvariantCulture);
                        Geopoint pointOfPosition = new Geopoint(location);


                        MapLocationFinderResult result = await MapLocationFinder.FindLocationsAtAsync(pointOfPosition);


                        if (result.Status == MapLocationFinderStatus.Success && result.Locations.Count > 0)
                        {
                            //create POI
                            MapIcon myPOI = new MapIcon {
                                Location = pointOfPosition, Title = "Patient's Location", NormalizedAnchorPoint = new Point(1.5, 1.0), ZIndex = 0
                            };
                            // Display an image of a MapIcon
                            myPOI.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/pin.png"));
                            // add to map and center it
                            PMap.MapElements.Add(myPOI);
                            PMap.Center    = pointOfPosition;
                            PMap.ZoomLevel = 10;

                            MapScene mapScene = MapScene.CreateFromLocationAndRadius(new Geopoint(location), 500, 150, 70);
                            await PMap.TrySetSceneAsync(mapScene);
                        }
                        else
                        {
                            errormessage.Text = "Not Found";
                        }
                    }
                }
                catch (Exception ex)
                {
                    errormessage.Text = "Location not found";
                }
            }
        }
        public async void dajLokaciju()
        {
            Geoposition pos = null;
            //da li se smije uzeti lokacija, trazi se odobrenje od korisnika (takodjer treba i capability)
            var accessStatus = await Geolocator.RequestAccessAsync();

            if (accessStatus == GeolocationAccessStatus.Allowed)
            {
                //uzimanje pozicije ako smije
                Geolocator geolocator = new Geolocator {
                    DesiredAccuracyInMeters = 10
                };
                pos = await geolocator.GetGeopositionAsync();
            }
            //tacka iz pozicije
            TrenutnaLokacija = pos.Coordinate.Point;
            Lokacija         = "Geolokacija Lat: " + TrenutnaLokacija.Position.Latitude + " Lng: " + TrenutnaLokacija.Position.Longitude;
            //uzeti adresu na osnovu GeoTacke
            MapLocationFinderResult result = await MapLocationFinder.FindLocationsAtAsync(pos.Coordinate.Point);

            //Nadje li adresu ispisi je
            if (result.Status == MapLocationFinderStatus.Success)
            {
                Adresa = "Adresa je " + result.Locations[0].Address.Street;
            }
            //nacrtati pravougaonik na mapi za oblast gdje bi korisnik mogao biti
            double      centerLatitude  = Mapa.Center.Position.Latitude;
            double      centerLongitude = Mapa.Center.Position.Longitude;
            MapPolyline mapPolyline     = new MapPolyline();

            mapPolyline.Path = new Geopath(new List <BasicGeoposition>()
            {
                new BasicGeoposition()
                {
                    Latitude = centerLatitude - 0.0005, Longitude = centerLongitude - 0.001
                },
                new BasicGeoposition()
                {
                    Latitude = centerLatitude + 0.0005, Longitude = centerLongitude - 0.001
                },
                new BasicGeoposition()
                {
                    Latitude = centerLatitude + 0.0005, Longitude = centerLongitude + 0.001
                },
                new BasicGeoposition()
                {
                    Latitude = centerLatitude - 0.0005, Longitude = centerLongitude + 0.001
                },
                new BasicGeoposition()
                {
                    Latitude = centerLatitude - 0.0005, Longitude = centerLongitude - 0.001
                }
            });
            mapPolyline.StrokeColor     = Colors.Black;
            mapPolyline.StrokeThickness = 3;
            mapPolyline.StrokeDashed    = true;
            Mapa.MapElements.Add(mapPolyline);
            BasicGeoposition pozicija = new BasicGeoposition()
            {
                Latitude = centerLatitude, Longitude = centerLongitude
            };

            TrenutnaLokacija = new Geopoint(pozicija);
        }
 /// <summary>
 /// <see cref="Windows.UI.Xaml.Controls.Maps.MapControl"/>
 /// </summary>
 /// <returns>IAsyncOperation</returns>
 public Task <bool> TrySetViewAsync(Geopoint center, double?zoomLevel) => UwpControl.TrySetViewAsync(center.UwpInstance, zoomLevel).AsTask();
 /// <summary>
 /// <see cref="Windows.UI.Xaml.Controls.Maps.MapControl.TryPanToAsync"/>
 /// </summary>
 /// <returns>IAsyncOperation</returns>
 public Task <bool> TryPanToAsync(Geopoint location) => UwpControl.TryPanToAsync(location.UwpInstance).AsTask();
 /// <summary>
 /// <see cref="Windows.UI.Xaml.Controls.Maps.MapControl.IsLocationInView"/>
 /// </summary>
 public void IsLocationInView(Geopoint location, out bool isInView) => UwpControl.IsLocationInView(location.UwpInstance, out isInView);
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedTo(e);
            this.navigationHelper.OnNavigatedTo(e);
            ContengRentRoom data       = e.Parameter as ContengRentRoom;
            string          partyTitle = (string)e.Parameter;

            lblTitle.Text = partyTitle;
            // Load data
            MobileServiceInvalidOperationException exception = null;

            try
            {
                items = await partyTable
                        .Where(Party => Party.partyTitle == partyTitle)
                        .ToCollectionAsync();
            }
            catch (MobileServiceInvalidOperationException ex)
            {
                exception = ex;
            }
            if (exception != null)
            {
                await new MessageDialog(exception.Message, "Error loading items").ShowAsync();
            }
            else
            {
                // Show data
                lblTitle.Text     = items[0].partyTitle;
                lblTime.Text      = items[0].time;
                lblContact.Text   = items[0].contact;
                lblContent.Text   = items[0].content;
                lblCrowd.Text     = items[0].crowd;
                lblPrice.Text     = items[0].price;
                tbxPublisher.Text = items[0].publisher;
                lblAddress.Text   = items[0].address;
                try
                {
                    // Download image from blob
                    // Souece: http://stackoverflow.com/questions/23256372/windows-phone-8-1-loading-images-from-remote-urls-placeholder
                    Uri         myUri = new Uri(items[0].imageAddress, UriKind.Absolute);
                    BitmapImage bmi   = new BitmapImage();
                    bmi.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                    bmi.UriSource     = myUri;
                    img.Source        = bmi;

                    // Show room location on map
                    // Authorization of map services
                    map.MapServiceToken = "QRJj0BZ57yT77gTeYfN-uw";

                    // Show current location
                    // Source: https://msdn.microsoft.com/en-us/magazine/dn818495.aspx

                    geolocator  = new Geolocator();
                    geoposition = await geolocator.GetGeopositionAsync();

                    result = await MapLocationFinder.FindLocationsAsync(items[0].address, geoposition.Coordinate.Point, 1);

                    map.Center    = result.Locations[0].Point;
                    map.ZoomLevel = 15;

                    //Pin image
                    MapIcon mapIcon = new MapIcon();
                    mapIcon.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/MapPin.png"));
                    mapIcon.NormalizedAnchorPoint = new Point(0.25, 0.9);
                    mapIcon.Location = result.Locations[0].Point;
                    mapIcon.Title    = "Room is here";
                    map.MapElements.Add(mapIcon);
                }
                catch (Exception ex)
                {
                    MessageDialog msgbox = new MessageDialog("Failed to acquire information: " + ex.Message);
                    await msgbox.ShowAsync();
                }
            }
            Ring.IsActive = false;
            // Get number from contact
            GlobalMethod global = new GlobalMethod();

            callNumber      = global.getNumber(items[0].contact);
            btnCall.Content = "Call " + callNumber;
            btnSMS.Content  = "SMS " + callNumber;

            // Get the drive rout between two points
            // Source: https://msdn.microsoft.com/en-us/magazine/dn818495.aspx
            try
            {
                BasicGeoposition startLocation = new BasicGeoposition();
                startLocation.Altitude  = geoposition.Coordinate.Point.Position.Altitude;
                startLocation.Latitude  = geoposition.Coordinate.Point.Position.Latitude;
                startLocation.Longitude = geoposition.Coordinate.Point.Position.Longitude;
                Geopoint         startPoint  = new Geopoint(startLocation);
                BasicGeoposition endLocation = new BasicGeoposition();
                endLocation.Altitude  = result.Locations[0].Point.Position.Altitude;
                endLocation.Latitude  = result.Locations[0].Point.Position.Latitude;
                endLocation.Longitude = result.Locations[0].Point.Position.Longitude;
                Geopoint endPoint = new Geopoint(endLocation);
                // Get the route between the points.
                MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync(
                    startPoint, endPoint,
                    MapRouteOptimization.Time, MapRouteRestrictions.None, 290);

                // Display the route between two points
                if (routeResult.Status == MapRouteFinderStatus.Success)
                {
                    // Use the route to initialize a MapRouteView.
                    MapRouteView viewOfRoute = new MapRouteView(routeResult.Route);
                    viewOfRoute.RouteColor   = Colors.Blue;
                    viewOfRoute.OutlineColor = Colors.Blue;
                    // Add the new MapRouteView to the Routes collection
                    // of the MapControl.
                    map.Routes.Add(viewOfRoute);
                    // Fit the MapControl to the route.
                    await map.TrySetViewBoundsAsync(
                        routeResult.Route.BoundingBox,
                        null,
                        Windows.UI.Xaml.Controls.Maps.MapAnimationKind.Bow);
                }
                // Display summary info about the route.
                // Source: https://msdn.microsoft.com/en-us/magazine/dn818495.aspx
                route.Inlines.Add(new Run()
                {
                    Text = "Total estimated time (minutes) = " + routeResult.Route.EstimatedDuration.TotalMinutes.ToString("F1")
                });
                route.Inlines.Add(new LineBreak());
                route.Inlines.Add(new Run()
                {
                    Text = "Total length (kilometers) = "
                           + (routeResult.Route.LengthInMeters / 1000).ToString("F1")
                });
                route.Inlines.Add(new LineBreak());
                // Display the directions.
                route.Inlines.Add(new Run()
                {
                    Text = "DIRECTIONS"
                });
                route.Inlines.Add(new LineBreak());
                route.Inlines.Add(new LineBreak());
                // Loop through the legs and maneuvers.

                foreach (MapRouteLeg leg in routeResult.Route.Legs)
                {
                    foreach (MapRouteManeuver maneuver in leg.Maneuvers)
                    {
                        route.Inlines.Add(new Run()
                        {
                            Text = maneuver.InstructionText
                        });
                        route.Inlines.Add(new LineBreak());
                    }
                }
            }
            catch
            {
                await new MessageDialog("No route from your location to party location.").ShowAsync();
            }
        }
Example #53
0
 /// <summary>
 /// Gets a circle of 180 points around the specified center with respect to the specified radius. 
 /// </summary>
 /// <param name="center">
 /// The center point to get a circle of points around.
 /// </param>
 /// <param name="radius">
 /// The radius for the circle.
 /// </param>
 /// <returns>
 /// Returns a collection of <see cref="BasicGeoposition"/> forming the circle.
 /// </returns>
 public static IEnumerable<BasicGeoposition> GetCirclePoints(
     this Geopoint center,
     double radius)
 {
     return GetCirclePoints(center, radius, 180);
 }
Example #54
0
 private async void Map_Loaded(object sender, RoutedEventArgs e)
 {
     Geopoint gentPoint = new Geopoint(gentLocation);
     await BingMap.TrySetSceneAsync(MapScene.CreateFromLocationAndRadius(gentPoint, 5000));
 }
Example #55
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="source"></param>
        async protected override void OnNavigatedTo(NavigationEventArgs source)
        {
            //Debug.WriteLine("NSP here");

            DataContext = null;
            DataContext = App.routeListViewModel;
            //string vehicleTime = e.AddedItems[0].ToString();
            Debug.WriteLine("NSP transitSel: " + App.lastState.vehicleScheduledTime);

            string vehicleID = "";
            string stopLng   = "";
            string stopLat   = "";
            string stopName  = "";
            string scheduled = "";
            //var vehicleClass = App.routeListViewModel.arrivals.Where(e => String.Equals(e.scheduled, source.Parameter)).Select(ret => ret);
            var vehicleClass = App.routeListViewModel.arrivals.Where(e => String.Equals(e.scheduled, App.lastState.vehicleScheduledTime)).Select(ret => ret);


            foreach (var ret in vehicleClass)
            {
                string[] schList = ret.scheduled.Split();
                scheduled = schList[1] + " " + schList[2];
                vehicleID = ret.vehicleID;
                stopLng   = ret.lng;
                stopLat   = ret.lat;
                stopName  = ret.desc;
            }

            //NSP write out the lat/lng from the webpage
            //string vehicleID = App.lastState.vehicleID;

            cTitleBox.Text = stopName + " - " + scheduled;

            transitLocationViewModel.loadLocationInfo(vehicleID);

            // Add the MapControl and the specify maps authentication key.
            MapControl MapControl = new MapControl();

            MapControl.ZoomInteractionMode = MapInteractionMode.GestureAndControl;
            MapControl.TiltInteractionMode = MapInteractionMode.GestureAndControl;
            MapControl.MapServiceToken     = "d8l9b6RU2EcjMncrRwx4~fKKyHyzPFPmghAi-JVfP0w~Anvx0AfcGv4Xz3O6Y_K9TNDFSsU8-LJ4ycFNteI-emI3Ts_2rn61pJL78fKq8sp0";
            transitMap.Children.Add(MapControl);

            // Specify lat, lng for the vehicle
            BasicGeoposition vehiclePosition = new BasicGeoposition()
            {
                Latitude = Convert.ToDouble(transitLocationViewModel.vehicleLocation.latitude), Longitude = Convert.ToDouble(transitLocationViewModel.vehicleLocation.longitude)
            };
            Geopoint vehiclePoint = new Geopoint(vehiclePosition);

            // Create a MapIcon for Vehicles
            MapIcon mapIcon1 = new MapIcon();

            mapIcon1.Location = vehiclePoint;
            mapIcon1.NormalizedAnchorPoint = new Point(0.5, 1.0);
            mapIcon1.Title  = "Arrives " + scheduled;
            mapIcon1.ZIndex = 0;

            // Specify lat, lng for the vehicle
            // BasicGeoposition snPosition = new BasicGeoposition() { Latitude = Convert.ToDouble(stopLat), Longitude = Convert.ToDouble(stopLng) };
            BasicGeoposition snPosition = new BasicGeoposition()
            {
                Latitude = Convert.ToDouble(stopLat), Longitude = Convert.ToDouble(stopLng)
            };

            Geopoint stopPoint = new Geopoint(snPosition);

            // Create a MapIcon for the stop
            MapIcon mapIcon2 = new MapIcon();

            mapIcon2.Location = stopPoint;
            mapIcon2.NormalizedAnchorPoint = new Point(0.5, 1.0);
            mapIcon2.Title  = stopName;
            mapIcon2.ZIndex = 0;

            // Add the MapIcon to the map.
            MapControl.MapElements.Add(mapIcon1);
            MapControl.MapElements.Add(mapIcon2);

            double stopLatDoub    = Convert.ToDouble(stopLat);
            double stopLngDoub    = Convert.ToDouble(stopLng);
            double vehicleLatDoub = Convert.ToDouble(transitLocationViewModel.vehicleLocation.latitude);
            double vehicleLngDoub = Convert.ToDouble(transitLocationViewModel.vehicleLocation.longitude);
            double averageLat     = (stopLatDoub + vehicleLatDoub) / 2;
            double averageLng     = (stopLngDoub + vehicleLngDoub) / 2;


            // Specify lat, lng for the vehicle
            //BasicGeoposition test = new BasicGeoposition() { Latitude = averageLat, Longitude = averageLng };
            //Geopoint testPoint = new Geopoint(test);
            //double bigLat = functions.findMax(stopLatDoub, vehicleLatDoub);
            //double lowLat = functions.findMin(stopLatDoub, vehicleLatDoub);
            //double bigLng = functions.findMax(stopLngDoub, vehicleLngDoub);
            //double lowLng = functions.findMin(stopLngDoub, vehicleLngDoub);
            //BasicGeoposition northWest = new BasicGeoposition() { Latitude = stopLatDoub, Longitude = stopLngDoub };
            //BasicGeoposition southEast = new BasicGeoposition() { Latitude = vehicleLatDoub, Longitude = vehicleLngDoub };

            //List<BasicGeoposition> basicPositions = new List<BasicGeoposition>();
            //basicPositions.Add(new BasicGeoposition() { Latitude = lowLat, Longitude = bigLng });
            //basicPositions.Add(new BasicGeoposition() { Latitude = bigLat, Longitude = lowLng });

            //this.Map.TrySetViewBoundsAsync(GeoboundingBox.TryCompute(basicPositions), null, MapAnimationKind.Default);
            //GeoboundingBox.TryCompute(basicPositions)
            // Center the map over the POI.
            MapControl.Center = stopPoint;
            //GeoboundingBox bBox = new GeoboundingBox(northWest, southEast);
            //await MapControl.TrySetViewBoundsAsync(GeoboundingBox.TryCompute(basicPositions), null, MapAnimationKind.Default);
            //MapControl.TrySetViewBoundsAsync(bBox, 10, animation: 0);
            MapControl.ZoomLevel = 14;
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.Parameter != null)
            {
                geolocator.DesiredAccuracyInMeters = 150;
                // получаем позицию
                var position = await geolocator.GetGeopositionAsync();

                // установка этой позиции на карте
                // Specify a known location.
                BasicGeoposition snPosition = new BasicGeoposition()
                {
                    Latitude = position.Coordinate.Point.Position.Latitude, Longitude = position.Coordinate.Point.Position.Longitude
                };
                Geopoint snPoint = new Geopoint(snPosition);

                // Create a MapIcon.
                MapIcon mapIcon2 = new MapIcon();
                mapIcon2.Location = snPoint;
                mapIcon2.NormalizedAnchorPoint = new Point(0.5, 1.0);



                mapIcon2.Title  = e.Parameter.ToString();
                mapIcon2.ZIndex = 0;
                objectList.Add(mapIcon2);
                // Add the MapIcon to the map.
                foreach (MapIcon o in objectList)
                {
                    map.MapElements.Add(o);
                }
            }



            try
            {
                map.MapServiceToken = "mapToken";
                // получаем инструмент геолокации

                //точность геолокации до 150 метров
                geolocator.DesiredAccuracyInMeters = 150;
                // получаем позицию
                var position = await geolocator.GetGeopositionAsync();

                // установка этой позиции на карте
                // Specify a known location.
                BasicGeoposition snPosition = new BasicGeoposition()
                {
                    Latitude = position.Coordinate.Point.Position.Latitude, Longitude = position.Coordinate.Point.Position.Longitude
                };
                Geopoint snPoint = new Geopoint(snPosition);

                // Create a MapIcon.
                MapIcon mapIcon1 = new MapIcon();
                mapIcon1.Location = snPoint;
                mapIcon1.NormalizedAnchorPoint = new Point(0.5, 1.0);
                mapIcon1.Title  = "Вы";
                mapIcon1.ZIndex = 0;

                // Add the MapIcon to the map.
                map.MapElements.Add(mapIcon1);

                // Center the map over the POI.
                map.Center    = snPoint;
                map.ZoomLevel = 14;
            }
            catch
            {
                MessageDialog msgbox = new MessageDialog("Невозможно получить данные местоположения", "Ошибка");
                await msgbox.ShowAsync();
            }
        }
        private async void Page_Loading(FrameworkElement sender, object args)
        {
            var configSettings = await getConfigSettings("ConfigSettings.txt");

            foreach (string configItemLine in configSettings)
            {
                string[] configItem = configItemLine.Split('=');
                string   itemName   = configItem[0].Trim();
                string   value      = configItem[1].Trim();
                switch (itemName)
                {
                case "Token":
                    MapControl.MapServiceToken = value;
                    break;

                case "LatitudeNorth":
                    Double.TryParse(value, out LatitudeNorth);
                    break;

                case "LatitudeSouth":
                    Double.TryParse(value, out LatitudeSouth);
                    break;

                case "LongitudeEast":
                    Double.TryParse(value, out LongitudeEast);
                    break;

                case "LongitudeWest":
                    Double.TryParse(value, out LongitudeWest);
                    break;

                case "ServicebusEndpoint":
                    servicebusEndpoint = value;
                    break;

                case "QueueName":
                    queueName = value;
                    break;

                case "CameraQueueName":
                    cameraQueueName = value;
                    break;

                case "SASKeyName":
                    sharedAccessKeyName = value;
                    break;

                case "SASKey":
                    sharedAccessKey = $"{value}=";     // SAS tokens have an "=" at the end which will be stripped by the Split function earlier
                    break;

                default: break;
                }
            }

            BasicGeoposition mapCenter = new BasicGeoposition();

            mapCenter.Latitude  = (LatitudeNorth + LatitudeSouth) / 2;
            mapCenter.Longitude = (LongitudeEast + LongitudeWest) / 2;
            Geopoint center = new Geopoint(mapCenter);

            MapControl.Center    = center;
            MapControl.ZoomLevel = 11;
        }
Example #58
0
 public async void SetCenterLocation(Geopoint point)
 {
     await Map.TrySetViewAsync(point ?? DataSource.Kot.Location);
 }
Example #59
0
        void AddPushPins()
        {
            var MyLandmarks = new List <MapElement>();

            BasicGeoposition snPosition = new BasicGeoposition {
                Latitude = 47.620, Longitude = -122.349
            };
            Geopoint snPoint = new Geopoint(snPosition);

            var spaceNeedleIcon = new MapIcon
            {
                Location = snPoint,
                NormalizedAnchorPoint = new Point(0.5, 1.0),
                ZIndex = 0,
                Title  = "Pin 1"
            };

            spaceNeedleIcon.Tag = "Tag Pin 1";
            MyLandmarks.Add(spaceNeedleIcon);

            BasicGeoposition snPosition2 = new BasicGeoposition {
                Latitude = 41.622, Longitude = -122.340
            };
            Geopoint snPoint2         = new Geopoint(snPosition2);
            var      spaceNeedleIcon2 = new MapIcon
            {
                Location = snPoint2,
                NormalizedAnchorPoint = new Point(0.5, 1.0),
                ZIndex = 0,
                Title  = "Pin 3"
            };

            MyLandmarks.Add(spaceNeedleIcon2);

            //
            BasicGeoposition snPosition3 = new BasicGeoposition {
                Latitude = 47.620, Longitude = -117.549
            };
            Geopoint snPoint3         = new Geopoint(snPosition3);
            var      spaceNeedleIcon3 = new MapIcon
            {
                Location = snPoint3,
                NormalizedAnchorPoint = new Point(0.5, 1.0),
                ZIndex = 0,
                Title  = "Pin 2"
            };

            MyLandmarks.Add(spaceNeedleIcon3);


            BasicGeoposition snPosition4 = new BasicGeoposition {
                Latitude = 41.622, Longitude = -117.549
            };
            Geopoint snPoint4         = new Geopoint(snPosition4);
            var      spaceNeedleIcon4 = new MapIcon
            {
                Location = snPoint4,
                NormalizedAnchorPoint = new Point(0.5, 1.0),
                ZIndex = 0,
                Title  = "Pin 4"
            };

            //MyLandmarks.Add(spaceNeedleIcon4);
            //

            var LandmarksLayer = new MapElementsLayer
            {
                ZIndex      = 1,
                MapElements = MyLandmarks
            };

            var MyLandmarks2 = new List <MapElement>();

            MyLandmarks2.Add(spaceNeedleIcon4);
            var LandmarksLayer2 = new MapElementsLayer
            {
                ZIndex      = 1,
                MapElements = MyLandmarks2
            };

            // MyLandmarks.Add(spaceNeedleIcon4);
            LandmarksLayer.MapElementClick += MapElement_ClickEvent;
            myMap.Layers.Add(LandmarksLayer);
            LandmarksLayer2.MapElementClick += MapElement_ClickEvent2;
            myMap.Layers.Add(LandmarksLayer2);
        }
        private async void MapControl_Loaded(object sender, RoutedEventArgs e)
        {
            var maps         = sender as MapControl;
            var accessStatus = await Geolocator.RequestAccessAsync();

            if (accessStatus == GeolocationAccessStatus.Allowed)
            {
                //current location
                Geolocator  geolocator = new Geolocator();
                Geoposition pos        = await geolocator.GetGeopositionAsync();

                Geopoint         myLocation      = pos.Coordinate.Point;
                BasicGeoposition myLocationBasic = new BasicGeoposition()
                {
                    Latitude = pos.Coordinate.Latitude, Longitude = pos.Coordinate.Longitude
                };

                //destination coordinates
                BasicGeoposition desPosition = new BasicGeoposition()
                {
                    Latitude = ViewModel.SelectedHangout.Latii, Longitude = ViewModel.SelectedHangout.Longi
                };
                Geopoint destPoint = new Geopoint(desPosition);


                // Create a MapIcon.
                MapIcon currentLocation = new MapIcon();
                currentLocation.Location = myLocation;
                currentLocation.NormalizedAnchorPoint = new Point(0.5, 1.0);
                currentLocation.Title  = "Current Location";
                currentLocation.ZIndex = 0;
                currentLocation.Image  = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/blue-marker-icon.png"));


                // Destination
                MapIcon destination = new MapIcon();
                destination.Location = destPoint;
                destination.NormalizedAnchorPoint = new Point(0.5, 1.0);
                destination.Title  = ViewModel.SelectedHangout.Name;
                destination.ZIndex = 0;
                destination.Image  = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/red-marker-icon.png"));

                //Map Route Finder
                MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync(
                    new Geopoint(myLocationBasic),
                    new Geopoint(desPosition),
                    MapRouteOptimization.Time,
                    MapRouteRestrictions.None);

                //Route Intialize
                if (routeResult.Status == MapRouteFinderStatus.Success)
                {
                    //Distance-Time-Direction
                    ViewModel.Time     = "Total estimated time : " + Math.Round((decimal)routeResult.Route.EstimatedDuration.TotalMinutes, 2).ToString() + " min";
                    ViewModel.Distance = "Total length : " + Math.Round((decimal)routeResult.Route.LengthInMeters / 1000, 3).ToString() + " km";
                    StringBuilder routeInfo = new StringBuilder();
                    routeInfo.Append("DIRECTIONS\n");
                    foreach (MapRouteLeg leg in routeResult.Route.Legs)
                    {
                        foreach (MapRouteManeuver maneuver in leg.Maneuvers)
                        {
                            routeInfo.AppendLine(maneuver.InstructionText);
                        }
                    }
                    ViewModel.Directions = routeInfo.ToString();

                    // Use the route to initialize a MapRouteView.
                    MapRouteView viewOfRoute = new MapRouteView(routeResult.Route);
                    viewOfRoute.RouteColor   = (Color)this.Resources["PrimaryColor"];
                    viewOfRoute.OutlineColor = Colors.Black;

                    // Add the new MapRouteView to the Routes collection
                    // of the MapControl.
                    maps.Routes.Add(viewOfRoute);

                    // Fit the MapControl to the route.
                    await maps.TrySetViewBoundsAsync(
                        routeResult.Route.BoundingBox,
                        null,
                        Windows.UI.Xaml.Controls.Maps.MapAnimationKind.None);
                }


                //map initialization
                maps.MapElements.Add(destination);
                maps.MapElements.Add(currentLocation);
                maps.Center           = myLocation;
                maps.ZoomLevel        = 14;
                maps.LandmarksVisible = true;
            }
        }