private void ShowUser(bool focus) { try // определение местоположения { Location currentPosition = ARDisplay.Location; if (focus) { MapPanel.SetView(currentPosition, 13); } DrawUser(currentPosition); } #pragma warning disable CS0168 // The variable 'e' is declared but never used catch (Exception e) #pragma warning restore CS0168 // The variable 'e' is declared but never used { MessageBoxResult mbr = MessageBox.Show("Не могу отобразить тебя на карте, так как у тебя отключено определение местоположения.\nОткрыть настройки, чтобы включить его?", "Местоположение", MessageBoxButton.OKCancel); if (mbr == MessageBoxResult.OK) { #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call. Launcher.LaunchUriAsync(new Uri("ms-settings-location:")); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call. } } }
void pinMarker_Tap(object sender, System.Windows.Input.GestureEventArgs e) { var map = Control; var mapTile = (MapTile)Element; PinMarker pinMarker = sender as PinMarker; tapMarker = pinMarker; MapPinData data = pinMarker.DataContext as MapPinData; var centerLocation = new System.Device.Location.GeoCoordinate(Math.Round(map.Center.Latitude, 4), Math.Round(map.Center.Longitude, 4)); var pinLocation = new System.Device.Location.GeoCoordinate(Math.Round(data.Latitude, 4), Math.Round(data.Longitude, 4)); //map.Center = pinLocation; //mapTile.ShowDetailInfo(data.Id); if (centerLocation == pinLocation) { mapTile.ShowPinDetailInfo(data.Id); } else { map.ViewChanged += map_ViewChanged; map.SetView(pinLocation, map.ZoomLevel, MapAnimationKind.Linear); } }
//return the distance from the acuurateDrop to the estimate drop public float EvaluateDistance(Drop d1, Drop d2) { var sCoord = new System.Device.Location.GeoCoordinate(d1.Estimeated_lat, d1.Estimeated_log); var eCoord = new System.Device.Location.GeoCoordinate(d2.Estimeated_lat, d2.Estimeated_log); return((float)sCoord.GetDistanceTo(eCoord)); }
private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)// ********* { var rootObject = JsonConvert.DeserializeObject <RootObject>(e.Result); int x = 0; foreach (var book in rootObject.sfx_web_service) { foreach (var item in book.maps) { MapIcon mpi = new MapIcon(); /*System.Diagnostics.Debug.WriteLine(item.place + " id "); * System.Diagnostics.Debug.WriteLine("-103." + item.longitude + " nombre "); * System.Diagnostics.Debug.WriteLine("20." + item.latitude + " imagen ");*/ if (x <= 4) { mpi.longitud = iteso[x, 1].ToString(); mpi.latitud = iteso[x, 0].ToString(); x++; } else if (x == 5) { break; } else { mpi.longitud = "-103." + item.longitude; mpi.latitud = "20." + item.latitude; } Location offset = new Location() { Latitude = Convert.ToDouble(mpi.latitud), Longitude = Convert.ToDouble(mpi.longitud), //Latitude = 20.609597, //Longitude = -103.412007, //Latitude = 20.725220,//zoo //Longitude = -103.307884, //zoo //Latitude = iteso[x,0], //Longitude = iteso[x,1], Altitude = Double.NaN // NaN will keep it on the horizon }; System.Diagnostics.Debug.WriteLine(offset.Latitude + " nombre "); System.Diagnostics.Debug.WriteLine(offset.Longitude + " imagen "); dest = new GeoCoordinate(offset.Latitude, offset.Longitude); me = MyMap.Center; Double distance = me.GetDistanceTo(dest); distance = Math.Round(distance, 0); mpi.lugar = item.place + " " + distance.ToString() + " m"; System.Diagnostics.Debug.WriteLine(distance + " distancia"); AddLabel(offset, item.place + " " + distance.ToString() + " m"); listPushpin.Add(mpi); } } drawPushpin(listPushpin); }
public async void newCenter() { Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracyInMeters = 50; Geoposition position = await geolocator.GetGeopositionAsync( maximumAge: TimeSpan.FromMinutes(1), timeout: TimeSpan.FromSeconds(30)); System.Device.Location.GeoCoordinate newCenter = new System.Device.Location.GeoCoordinate(position.Coordinate.Latitude, position.Coordinate.Longitude); map2.Center = newCenter; }
/// <summary> /// Allows you to set the center of a Map control using a Windows.Devices.Geolocation.Geocoordinate /// </summary> /// <param name="map">the Map control instance</param> /// <param name="coord">The Geocoordinate object to use to set the center of the map</param> public static void SetCenter(this Microsoft.Phone.Maps.Controls.Map map, Windows.Devices.Geolocation.Geocoordinate coord) { System.Device.Location.GeoCoordinate centre = new System.Device.Location.GeoCoordinate() { Latitude = coord.Latitude, Longitude = coord.Longitude, }; map.Center = centre; }
public GpsDataViewModel(AgresivityCalculator calculator) { MovementThreshold = 5; _calculator = calculator; _watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High); _watcher.MovementThreshold = MovementThreshold; _watcher.PositionChanged += _watcher_PositionChanged; GpsData = new System.Device.Location.GeoCoordinate(); GpsData.Speed = 54; }
public async void newCenter() { Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracyInMeters = 50; Geoposition position = await geolocator.GetGeopositionAsync( maximumAge : TimeSpan.FromMinutes(1), timeout : TimeSpan.FromSeconds(30)); System.Device.Location.GeoCoordinate newCenter = new System.Device.Location.GeoCoordinate(position.Coordinate.Latitude, position.Coordinate.Longitude); map1.Center = newCenter; }
public LocationMarker(ScnDiscounts.Helpers.GeoCoordinate coordinates) { System.Windows.Controls.Image imgPin = new System.Windows.Controls.Image(); BitmapImage bmp = new BitmapImage(new Uri(@"/assets/MapPins/ic_pin_navigation.png", UriKind.Relative)); imgPin.Source = bmp; //imgPin.Width = 60; //imgPin.Height = 60; Content = imgPin; GeoCoordinate = new System.Device.Location.GeoCoordinate(coordinates.Latitude, coordinates.Longitude); PositionOrigin = new System.Windows.Point(0.0, 0.0); }
/// <summary> /// Calculates the direct distance between two points. /// </summary> /// <param name="a"> /// The first point /// </param> /// <param name="b"> /// The second point /// </param> /// <returns> /// The direct distance between the two points. /// </returns> static public double DistanceTo(this Location here, Location there) { var r = 6371; var dLat = (there.Latitude - here.Latitude).ToRadian(); var dLon = (there.Longitude - here.Longitude).ToRadian(); var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(here.Latitude.ToRadian()) * Math.Cos(there.Latitude.ToRadian()) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2); var c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a))); var d = r * c; return(d * 1000); }
private GeoLocation GetVisitorLatLong() { GeoCoordinateWatcher watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default); var userLocation = new GeoLocation(); watcher.Start(); System.Device.Location.GeoCoordinate coord = watcher.Position.Location; if (!watcher.Position.Location.IsUnknown) { userLocation.Latitude = coord.Latitude; userLocation.Longitude = coord.Longitude; } return(userLocation); }
void map_ViewChanged(object sender, MapViewChangedEventArgs e) { (sender as Map).ViewChanged -= map_ViewChanged; var map = Control; var mapTile = (MapTile)Element; MapPinData data = tapMarker.DataContext as MapPinData; var centerLocation = new System.Device.Location.GeoCoordinate(Math.Round(map.Center.Latitude, 4), Math.Round(map.Center.Longitude, 4)); var pinLocation = new System.Device.Location.GeoCoordinate(Math.Round(data.Latitude, 4), Math.Round(data.Longitude, 4)); if (centerLocation == pinLocation) { mapTile.ShowPinDetailInfo(data.Id); } }
// public TestViewModel(IWalkerDataService walkerDataService) public Wp8AppHubViewModel(INavigationService navigationService) { _navigationService = navigationService; _walkerDataService = new WalkerDataService(); _logger = new AdpLogger(); GeoCoordinate = new System.Device.Location.GeoCoordinate(); // Messenger.Default.Register<Wp8AppHubViewModel>(this, HandleMessengerMessage); Messenger.Default.Register<string>(this, HandleMessengerStringMessage); ConfigureMapModes(); _walkerAppSettings = new WalkerAppSettings(); if (_walkerAppSettings.AzureEnabled) DoIt(); else Activities = new ObservableCollection<Walk>(); ElapsedTime = "n/a"; }
public PinMarker(MapPinData pinData) { if (pinData.PrimaryCategory != null) { System.Windows.Controls.Image imgPin = new System.Windows.Controls.Image(); var categoryParam = CategoryHelper.CategoryList[pinData.PrimaryCategory.TypeCode]; BitmapImage bmp = new BitmapImage(new Uri(categoryParam.Icon, UriKind.Relative)); imgPin.Source = bmp; //imgPin.Width = 60; //imgPin.Height = 60; Content = imgPin; DataContext = pinData; GeoCoordinate = new System.Device.Location.GeoCoordinate(pinData.Latitude, pinData.Longitude); PositionOrigin = new System.Windows.Point(0.0, 0.0); } }
/// <summary> /// Calculates the distance between two points in 3D space. /// </summary> /// <param name="a"> /// The first point /// </param> /// <param name="b"> /// The second point /// </param> /// <returns> /// The distance between the two points in 3D space. /// </returns> /// <remarks> /// This method assumes 1 3D unit = 1 meter. This method is also not incredibly accurate /// but it's accurate enough for the scales used in most AR applications. /// </remarks> static public Vector3 DistanceTo3D(this Location a, Location b) { // Use GeoCoordinate provided methods to calculate distance. Use // same longitude on both points to calculate latitude distance and // use same latitude on both points to calculate longitude distance. float latitudeMeters = (float)a.DistanceTo(new Location() { Latitude = b.Latitude, Longitude = a.Longitude }); float longitudeMeters = (float)a.DistanceTo(new Location() { Latitude = a.Latitude, Longitude = b.Longitude }); // Invert the distance sign if necessary to account for direction if (a.Latitude < b.Latitude) { latitudeMeters *= -1; } if (a.Longitude > b.Longitude) { longitudeMeters *= -1; } float altitudeMeters = 0f; #if WP7 // Now calculate the altitude difference, but only if both sides of the equation have altitudes if ((!double.IsNaN(a.Altitude)) && (!double.IsNaN(b.Altitude))) { // Calculate altitudeMeters = (float)(b.Altitude - a.Altitude); // Deal with really small double values getting converted to floats if (float.IsInfinity(altitudeMeters)) { altitudeMeters = 0; } } #endif // Return the new point return(new Vector3(longitudeMeters, altitudeMeters, latitudeMeters)); }
//void cityLookup_cityFoundEvent(string city) //{ //this.currentCity = city; //InitializeMap(); //} public void InitializeMap() { //currentCity = "Valletta"; // get all localized entries IEnumerator localizedEntries = LocationData.Instance.GetEnumerator(); //List<GeoCoordinate> locations = new List<GeoCoordinate>(); imageLayer = new MapLayer(); map1.Children.Add(imageLayer); detailsCanvas = new Canvas(); map1.Children.Add(detailsCanvas); // loop through localized entries while ( localizedEntries.MoveNext() ) { KeyValuePair<string, SimpleCoordinates> entry = (KeyValuePair<string, SimpleCoordinates>)localizedEntries.Current; if ( LocationIsClose(entry.Value.Latitude, entry.Value.Longitude) ) { //Pushpin pin = new Pushpin(); GeoCoordinate location = new System.Device.Location.GeoCoordinate(entry.Value.Latitude, entry.Value.Longitude); // locations.Add(location); Image pinImage = new Image(); pinImage.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("marker-red.png", UriKind.Relative)); pinImage.Opacity = 0.9; pinImage.Stretch = System.Windows.Media.Stretch.None; pinImage.Tag = entry.Key; pinImage.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(pin_Tap); imageLayer.AddChild(pinImage, location); } } // set map view map1.SetView(new GeoCoordinate(currentLat, currentLon), 15.0); }
void MyPositionChanged(GeoPositionChangedEventArgs<GeoCoordinate> e) { if (!GpsIsDisbaled) { Deployment.Current.Dispatcher.BeginInvoke(() => { System.Device.Location.GeoCoordinate geo = new System.Device.Location.GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude); map1.Mode = new Microsoft.Phone.Controls.Maps.AerialMode(true); //map1.over map1.SetView(geo, 16); myList.LoadStopsByLocation(e.Position.Location.Latitude, e.Position.Location.Longitude); watcher.Stop(); }); } }
/// <summary> /// Custom method called from the PositionChanged event handler /// </summary> /// <param name="e"></param> void MyPositionChanged(GeoPositionChangedEventArgs<GeoCoordinate> e) { // Update the map to show the current location System.Device.Location.GeoCoordinate ppLoc = new System.Device.Location.GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude); model.PushPins.Remove(model.PushPins.Where(p => p.IsPostion == true).SingleOrDefault()); model.PushPins.Add(new PushPinModel { Location = ppLoc, PinSource = "Resources/redpin.png", IsPostion = true }); PopupText.Visibility = Visibility.Collapsed; foreach (var pin in model.PushPins.Where(p=>p.IsPostion==false)) { if (pin.Location.Longitude - _threshold < ppLoc.Longitude && pin.Location.Longitude + _threshold > ppLoc.Longitude && pin.Location.Latitude - _threshold < ppLoc.Latitude && pin.Location.Latitude + _threshold > ppLoc.Latitude) { PopupText.Visibility = Visibility.Visible; PopupText.Text = "Gratulacje! Doszedłeś do celu"; MapLayer.SetPosition(PopupText, ppLoc); model.PushPins.Remove(pin); break; } } DataContext = model; mapMain.SetView(ppLoc, 10.0); }
void ResetMap() { System.Device.Location.GeoCoordinate ppLoc = new System.Device.Location.GeoCoordinate(0.1, 0.1); mapMain.SetView(ppLoc, 1); //update pushpin location and show //MapLayer.SetPosition(ppLocation, ppLoc); //ppLocation.Visibility = System.Windows.Visibility.Collapsed; }
void pinMarker_Tap(object sender, System.Windows.Input.GestureEventArgs e) { var map = Control; var mapTile = (MapTile)Element; PinMarker pinMarker = sender as PinMarker; tapMarker = pinMarker; MapPinData data = pinMarker.DataContext as MapPinData; var centerLocation = new System.Device.Location.GeoCoordinate(Math.Round(map.Center.Latitude, 4), Math.Round(map.Center.Longitude, 4)); var pinLocation = new System.Device.Location.GeoCoordinate(Math.Round(data.Latitude, 4), Math.Round(data.Longitude, 4)); //map.Center = pinLocation; //mapTile.ShowDetailInfo(data.Id); if (centerLocation == pinLocation) mapTile.ShowPinDetailInfo(data.Id); else { map.ViewChanged += map_ViewChanged; map.SetView(pinLocation, map.ZoomLevel, MapAnimationKind.Linear); } }
/// <summary> /// if your location is added-> update location /// else -> add your location mark /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void _mapProcess_LocatorPositionChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { _yourLocation = sender as GeoCoordinate; if (_markIcon == null) Dispatcher.BeginInvoke(() => { AddYourLocation(); myMapControl.SetView(_yourLocation, 14, 0.2); }); else Dispatcher.BeginInvoke(() => { Microsoft.Phone.Controls.Maps.MapLayer.SetPosition(_markIcon, _yourLocation); }); }
void map_ViewChanged(object sender, MapViewChangedEventArgs e) { (sender as Map).ViewChanged -= map_ViewChanged; var map = Control; var mapTile = (MapTile)Element; MapPinData data = tapMarker.DataContext as MapPinData; var centerLocation = new System.Device.Location.GeoCoordinate(Math.Round(map.Center.Latitude, 4), Math.Round(map.Center.Longitude, 4)); var pinLocation = new System.Device.Location.GeoCoordinate(Math.Round(data.Latitude, 4), Math.Round(data.Longitude, 4)); if (centerLocation == pinLocation) mapTile.ShowPinDetailInfo(data.Id); }
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { base.OnNavigatedTo(e); LocationAssistant.Instance.WalkingPositionChanged += OnWalkingPositionChanged; IAppInfo iai = Application.Current as IAppInfo; if (iai != null) { _map.CredentialsProvider = new ApplicationIdCredentialsProvider(iai.BKey); } // TODO: TOMBSTONE NICE TO HAVE: Get the center point for tombing' string val; if (NavigationContext.QueryString.TryGetValue("name", out val)) { _placeName = val; } if (NavigationContext.QueryString.TryGetValue("address", out val)) { _placeAddress = val; } if (NavigationContext.QueryString.TryGetValue("localUri", out val)) { Uri uri; if (Uri.TryCreate(val, UriKind.Relative, out uri)) { _placeLocalUri = uri; } } string lat = string.Empty; string @long = string.Empty; if (NavigationContext.QueryString.TryGetValue("lat", out lat) && NavigationContext.QueryString.TryGetValue("long", out @long)) { var geoCoordinate = new System.Device.Location.GeoCoordinate(double.Parse(lat, CultureInfo.InvariantCulture), double.Parse(@long, CultureInfo.InvariantCulture)); _itemLocation = geoCoordinate; _map.SetView(geoCoordinate, 14); if (_placePushpin != null && _layer.Children.Contains(_placePushpin)) { _layer.Children.Remove(_placePushpin); _placePushpin = null; } _placePushpin = new Pushpin(); _placePushpin.Location = geoCoordinate; _placePushpin.Content = new MapPlaceInformation(_placeName, _placeAddress, _placeLocalUri); _placePushpin.ContentTemplate = LayoutRoot.Resources["PlaceInformationDataTemplate"] as DataTemplate; if (_gpsPushpin == null) { _gpsPushpin = new Pushpin(); _gpsPushpin.Location = LocationAssistant.Instance.LastKnownLocation.AsGeoCoordinate(); var cs = LayoutRoot.Resources["MePushpinStyle"] as Style; _gpsPushpin.Style = cs; _layer.Children.Add(_gpsPushpin); } _layer.Children.Add(_placePushpin); } if (State.ContainsKey(MapModeTombstoneKey)) { _isSatelliteViewOn = (bool)State[MapModeTombstoneKey]; } //SetupAppBar(); UpdateMode(); if (Environment.OSVersion.Version.Minor >= 1) { // mango hack var st = typeof(SystemTray); var opacity = st.GetProperty("Opacity"); if (opacity != null) { opacity.SetValue(null, 0.65, null); SystemTray.IsVisible = true; } } }
private void routeService_CalculateRouteCompleted(object sender, routeservice.CalculateRouteCompletedEventArgs e) { // If the route calculate was a success and contains a route, then draw the route on the map. if ((e.Result.ResponseSummary.StatusCode == routeservice.ResponseStatusCode.Success) & (e.Result.Result.Legs.Count != 0)) { // Set properties of the route line you want to draw. Color routeColor = Colors.Blue; SolidColorBrush routeBrush = new SolidColorBrush(routeColor); MapPolyline routeLine = new MapPolyline(); routeLine.Locations = new LocationCollection(); routeLine.Stroke = routeBrush; routeLine.Opacity = 0.65; routeLine.StrokeThickness = 5.0; // Retrieve the route points that define the shape of the route. foreach (Location p in e.Result.Result.RoutePath.Points) { routeLine.Locations.Add(new Location { Latitude = p.Latitude, Longitude = p.Longitude }); } // Add a map layer in which to draw the route. MapLayer myRouteLayer = new MapLayer(); map1.Children.Add(myRouteLayer); // Add the route line to the new layer. myRouteLayer.Children.Add(routeLine); // Figure the rectangle which encompasses the route. This is used later to set the map view. double centerlatitude = (routeLine.Locations[0].Latitude + routeLine.Locations[routeLine.Locations.Count - 1].Latitude) / 2; double centerlongitude = (routeLine.Locations[0].Longitude + routeLine.Locations[routeLine.Locations.Count - 1].Longitude) / 2; Location centerloc = new Location(); centerloc.Latitude = centerlatitude; centerloc.Longitude = centerlongitude; double north, south, east, west; if ((routeLine.Locations[0].Latitude > 0) && (routeLine.Locations[routeLine.Locations.Count - 1].Latitude > 0)) { north = routeLine.Locations[0].Latitude > routeLine.Locations[routeLine.Locations.Count - 1].Latitude ? routeLine.Locations[0].Latitude : routeLine.Locations[routeLine.Locations.Count - 1].Latitude; south = routeLine.Locations[0].Latitude < routeLine.Locations[routeLine.Locations.Count - 1].Latitude ? routeLine.Locations[0].Latitude : routeLine.Locations[routeLine.Locations.Count - 1].Latitude; } else { north = routeLine.Locations[0].Latitude < routeLine.Locations[routeLine.Locations.Count - 1].Latitude ? routeLine.Locations[0].Latitude : routeLine.Locations[routeLine.Locations.Count - 1].Latitude; south = routeLine.Locations[0].Latitude > routeLine.Locations[routeLine.Locations.Count - 1].Latitude ? routeLine.Locations[0].Latitude : routeLine.Locations[routeLine.Locations.Count - 1].Latitude; } if ((routeLine.Locations[0].Longitude < 0) && (routeLine.Locations[routeLine.Locations.Count - 1].Longitude < 0)) { west = routeLine.Locations[0].Longitude < routeLine.Locations[routeLine.Locations.Count - 1].Longitude ? routeLine.Locations[0].Longitude : routeLine.Locations[routeLine.Locations.Count - 1].Longitude; east = routeLine.Locations[0].Longitude > routeLine.Locations[routeLine.Locations.Count - 1].Longitude ? routeLine.Locations[0].Longitude : routeLine.Locations[routeLine.Locations.Count - 1].Longitude; } else { west = routeLine.Locations[0].Longitude > routeLine.Locations[routeLine.Locations.Count - 1].Longitude ? routeLine.Locations[0].Longitude : routeLine.Locations[routeLine.Locations.Count - 1].Longitude; east = routeLine.Locations[0].Longitude < routeLine.Locations[routeLine.Locations.Count - 1].Longitude ? routeLine.Locations[0].Longitude : routeLine.Locations[routeLine.Locations.Count - 1].Longitude; } // For each geocode result (which are the waypoints of the route), draw a dot on the map. foreach (geocodeservice.GeocodeResult gr in geocodeResults) { Ellipse point = new Ellipse(); point.Width = 10; point.Height = 10; point.Fill = new SolidColorBrush(Colors.Red); point.Opacity = 0.65; location.Latitude = gr.Locations[0].Latitude; location.Longitude = gr.Locations[0].Longitude; MapLayer.SetPosition(point, location); MapLayer.SetPositionOrigin(point, PositionOrigin.Center); // Add the drawn point to the route layer. myRouteLayer.Children.Add(point); } // Set the map view using the rectangle which bounds the rendered route. //map1.SetView(rect); double latitude = 0.0; double longtitude = 0.0; map1.SetView(location, 12); map1.Center = location; GeoCoordinate CurrentLocCoordinate = new System.Device.Location.GeoCoordinate(latitude, longtitude); } }
private async void Button_Click(object sender, RoutedEventArgs e) { var btn = sender as Button; switch (btn.Tag.ToString()) { case "1": Geolocator geo = new Geolocator(); aboveMap.Text = "Getting location"; Geoposition pos = await geo.GetGeopositionAsync(); aboveMap.Text = "Got location"; pos2 = new GeoCoordinate(pos.Coordinate.Latitude, pos.Coordinate.Longitude); theMap.SetView(pos2, 16); break; case "2": if (pos2 == null) { return; } var ml = new MapLayer(); Microsoft.Phone.Maps.Toolkit.Pushpin pp = new Pushpin(); pp.GeoCoordinate = pos2; MapOverlay mo = new MapOverlay(); //mo.GeoCoordinate = pos2; mo.Content = pp; ml.Add(mo); theMap.Layers.Add(ml); break; case "3": ObservableCollection <BusStopVM> obco; List <BusStopVM> ls; Uri apilink = new Uri(GetRequest(pos2)); Debugger.Log(0, "", GetRequest(pos2) + "\n"); Abovelist.Text = "loading"; var response = await DownloadString(apilink); //var ls = DataLoader.GetStops(response); //var obco = new ObservableCollection<BusStopVM>(DataLoader.GetStops(response)); ls = JsonConvert.DeserializeObject <List <BusStopVM> >(response); obco = new ObservableCollection <BusStopVM>(ls); Abovelist.Text = "response: " + response.Length + ", obco: " + obco.Count; if (obco.Count > 0) { Abovelist.Text += ", first: " + obco[0].Name; } //foreach (var bs in obco) PivotVM.Instance.BusStops.Add(bs); PivotVM.Instance.BusStops = obco; //App.ViewModel.BusStops = obco; //stoplist.ItemsSource = obco; //stoplist.ItemsSource = ls; //mapitems = new MapItemsControl(); GetMPC().ItemsSource = obco; Abovelist.Text = (GetMPC().ItemsSource as ObservableCollection <BusStopVM>).Count.ToString(); break; } }
/// <summary> /// Main loop for Activity tracking. /// Start and stops an activity. /// Persists to /// - SkyDrive /// - Azure /// - .gpx file viewer /// as determined by SettingsView.xaml /// </summary> public async void ToggleActivity() { if (Vm == null) Vm = SimpleIoc.Default.GetInstance<Wp8AppHubViewModel>(); if (isActive) { Vm.StatusMessages += "ToggleActivity Stop"; activityTimer.Stop(); isActive = false; _activity.Stop = DateTime.Now; activityEnd = _CurrentGeoCoordinate; TimeSpan ts = _activity.Stop - _activity.Start; var distance = (activityEnd).GetDistanceTo(activityBegin); _activity.Distance = distance; var distanceInFeet = distance * 3.281; var distanceInMiles = distanceInFeet / 5280; if (Geos.Count > 0) { string skyDriveFileName = "Walker"; skyDriveFileName += DateTime.Now.ToString("yyyy-MM-dd-hh-mm"); skyDriveFileName += ".gpx"; _logger.Log(this, skyDriveFileName); byte[] bytes = Encoding.UTF8.GetBytes(ToGpx()); MemoryStream gpxMemoryStream = new MemoryStream(bytes); try { if (_client == null) { // _client = new LiveConnectClient(e.Session); _client = App.LiveConnectClient; } _logger.Log(this, "_client.UploadAsync(MeDetails.TopLevelSkyDriveFolder, skyDriveFileName, gpxMemoryStream,"); var result = await _client.UploadAsync(MeDetails.TopLevelSkyDriveFolder, skyDriveFileName, gpxMemoryStream, OverwriteOption.Overwrite); _logger.Log(this, "Upload to skyDrive apparently worked!", result.ToString()); // var success = await Windows.System.Launcher.LaunchFileAsync(ms); // var success = await Windows.System.Launcher. LaunchFileAsync(ms); } catch (Exception ex) { _logger.Log(this, "Upload to skyDrive exception: ", ex.ToString()); } gpxMemoryStream.Dispose(); if (_walkerAppSettings.GpxEnabled) LaunchGpxFileAssociation(skyDriveFileName); PersistIt(skyDriveFileName); } Vm.StatusMessages = string.Empty; Vm.StatusMessages += String.Format("Walked: {0:0000.00} meters ({2:00.000} miles) in {1} seconds.\n", distance, ts.ToString(), distanceInMiles); Vm.StatusMessages += String.Format("(new calc) Walked: {0:0000.00} meters \n", _CurrentDistance); _CurrentDistance = 0; } else { Vm.StatusMessages += "ToggleActivity Start"; StartTimer(); isActive = true; _activity = new Walk(); _activity.Start = DateTime.Now; activityBegin = _CurrentGeoCoordinate; Geos = new List<GeoCoordinate>(); // clear Geos list as we're starting a new activity track. Geos.Add(_CurrentGeoCoordinate); // Begin activity with current location. } }
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { base.OnNavigatedTo(e); LocationAssistant.Instance.WalkingPositionChanged += OnWalkingPositionChanged; IAppInfo iai = Application.Current as IAppInfo; if (iai != null) { _map.CredentialsProvider = new ApplicationIdCredentialsProvider(iai.BKey); } // TODO: TOMBSTONE NICE TO HAVE: Get the center point for tombing' string val; if (NavigationContext.QueryString.TryGetValue("name", out val)) { _placeName = val; } if (NavigationContext.QueryString.TryGetValue("address", out val)) { _placeAddress = val; } if (NavigationContext.QueryString.TryGetValue("localUri", out val)) { Uri uri; if (Uri.TryCreate(val, UriKind.Relative, out uri)) { _placeLocalUri = uri; } } string lat = string.Empty; string @long = string.Empty; if (NavigationContext.QueryString.TryGetValue("lat", out lat) && NavigationContext.QueryString.TryGetValue("long", out @long)) { var geoCoordinate = new System.Device.Location.GeoCoordinate(double.Parse(lat, CultureInfo.InvariantCulture), double.Parse(@long, CultureInfo.InvariantCulture)); _itemLocation = geoCoordinate; double zoomLevel = 14; // Default. // Try to get a zoom level so that we can show the user their // current location plus the place they are looking for. var point = LocationAssistant.Instance.LastKnownLiveLocation; if (point != null) { zoomLevel = BingMapsHelper.GetZoomLevelShowingPoints( geoCoordinate, LocationAssistant.Instance.LastKnownLiveLocation.AsGeoCoordinate(), 210 /* pixels */); } _map.SetView(geoCoordinate, zoomLevel); if (_placePushpin != null && _layer.Children.Contains(_placePushpin)) { _layer.Children.Remove(_placePushpin); _placePushpin = null; } _placePushpin = new Pushpin(); _placePushpin.Location = geoCoordinate; _placePushpin.Content = new MapPlaceInformation(_placeName, _placeAddress, _placeLocalUri); _placePushpin.ContentTemplate = LayoutRoot.Resources["PlaceInformationDataTemplate"] as DataTemplate; if (_gpsPushpin == null) { _gpsPushpin = new Pushpin(); _gpsPushpin.Location = LocationAssistant.Instance.LastKnownLocation.AsGeoCoordinate(); var cs = LayoutRoot.Resources["MePushpinStyle"] as Style; _gpsPushpin.Style = cs; _layer.Children.Add(_gpsPushpin); } _layer.Children.Add(_placePushpin); } if (State.ContainsKey(MapModeTombstoneKey)) { _isSatelliteViewOn = (bool)State[MapModeTombstoneKey]; } //SetupAppBar(); UpdateMode(); if (Environment.OSVersion.Version.Minor >= 1) { // mango hack var st = typeof(SystemTray); var opacity = st.GetProperty("Opacity"); if (opacity != null) { opacity.SetValue(null, 0.65, null); SystemTray.IsVisible = true; } } }
/// <summary> /// Converts the <see cref="GeoCoordinate"/> to a properly formatted WGS84 string. /// </summary> /// <param name="coordinate"> /// The GeoCoordinate to convert. /// </param> /// <returns> /// The WGS84 string. /// </returns> static public string ToWGS84String(this Location coordinate) { return(string.Format("{0}, {1}", coordinate.Latitude, coordinate.Longitude)); }