/// <summary> /// Draw the polyline from the PolylineCoordinates. /// </summary> private void UpdatePolyLine() { if (customMap != null && nativeMap != null) { if (customMap.PolylineCoordinates != null && customMap.PolylineCoordinates.Count > 0) { List <BasicGeoposition> coordinates = new List <BasicGeoposition>(); foreach (var position in customMap.PolylineCoordinates) { coordinates.Add(new BasicGeoposition() { Latitude = position.Latitude, Longitude = position.Longitude }); } Geopath path = new Geopath(coordinates); MapPolyline polyline = new MapPolyline(); polyline.StrokeColor = new Color() { A = (byte)(customMap.PolylineColor.A * 255), R = (byte)(customMap.PolylineColor.R * 255), G = (byte)(customMap.PolylineColor.G * 255), B = (byte)(customMap.PolylineColor.B * 255) }; polyline.StrokeThickness = customMap.PolylineThickness; polyline.Path = path; nativeMap.MapElements.Add(polyline); nativeMap.UpdateLayout(); } } }
/// <summary> /// Handles MVVM Message for Map path. /// </summary> /// <param name="path">The path.</param> private void HandleMapPath(Geopath path) { // Remove previous paths from MapControl mapActivity.MapElements.Clear(); // Validate input path if (path != null && path.Positions.Any()) { // Configure path to draw with polyline and assign path to MapControl MapPolyline loMapPolyline = new MapPolyline(); loMapPolyline.Path = path; loMapPolyline.StrokeColor = (Color)Resources["SystemAccentColor"]; loMapPolyline.StrokeThickness = 3; mapActivity.MapElements.Add(loMapPolyline); // Configure start position icon and assign path to MapControl BasicGeoposition loStartPosition = path.Positions[0]; MapIcon loStartIcon = new MapIcon(); loStartIcon.Location = new Geopoint(loStartPosition); loStartIcon.NormalizedAnchorPoint = new Point(0.5, 1.0); loStartIcon.Title = XportBand.Resources.Strings.MapPositionStartText; loStartIcon.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/LocationDarkGreen.png")); mapActivity.MapElements.Add(loStartIcon); // Configure end position icon and assign path to MapControl BasicGeoposition loEndPosition = path.Positions[path.Positions.Count - 1]; MapIcon loEndIcon = new MapIcon(); loEndIcon.Location = new Geopoint(loEndPosition); loEndIcon.NormalizedAnchorPoint = new Point(0.5, 1.0); loEndIcon.Title = XportBand.Resources.Strings.MapPositionEndText; loEndIcon.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/LocationDarkRed.png")); mapActivity.MapElements.Add(loEndIcon); // Center map to start position and assign default zoom level to 15 (TODO: auto-zoom) mapActivity.Center = new Geopoint(loStartPosition); mapActivity.ZoomLevel = 15; } }
protected override void DrawSearchAreaPolygon(Models.Geoposition[] polygonData) { if (_searchAreaPolygon != null) { _nativeMap.MapElements.Remove(_searchAreaPolygon); } IEnumerable <BasicGeoposition> positions = polygonData.Select(pos => new BasicGeoposition { Latitude = pos.Latitude, Longitude = pos.Longitude }); Geopath polygonPath = new Geopath(positions); _searchAreaPolygon = new MapPolygon { Path = polygonPath, ZIndex = 1, FillColor = FormsMap.SearchPolygonColor.ToMediaColor(), StrokeThickness = 0 }; _nativeMap.MapElements.Add(_searchAreaPolygon); }
protected override MapPolyline CreateNativeItem(Polyline outerItem) { Color color = outerItem.StrokeColor; Geopath geopath = new Geopath(outerItem.Positions.Select(position => new BasicGeoposition { Latitude = position.Latitude, Longitude = position.Longitude })); MapPolyline polyline = new MapPolyline { StrokeColor = Windows.UI.Color.FromArgb( (byte)(color.A * 255), (byte)(color.R * 255), (byte)(color.G * 255), (byte)(color.B * 255)), StrokeThickness = outerItem.StrokeWidth, ZIndex = outerItem.ZIndex, Path = geopath }; NativeMap.MapElements.Add(polyline); outerItem.NativeObject = polyline; return(polyline); }
// Credit // http://csharphelper.com/blog/2014/07/determine-whether-a-point-is-inside-a-polygon-in-c/ // Return True if the point is in the polygon. public static bool PointInPolygon(BasicGeoposition point, Geopath polygon) { double X = point.Longitude; double Y = point.Latitude; List <BasicGeoposition> points = new List <BasicGeoposition>(polygon.Positions); // Get the angle between the point and the // first and last vertices. double total_angle = GetAngle( points[3].Longitude, points[3].Latitude, X, Y, points[0].Longitude, points[0].Latitude); // Add the angles from the point // to each other pair of vertices. for (int i = 0; i < 3; i++) { total_angle += GetAngle( points[i].Longitude, points[i].Latitude, X, Y, points[i + 1].Longitude, points[i + 1].Latitude); } // The total angle should be 2 * PI or -2 * PI if // the point is in the polygon and close to zero // if the point is outside the polygon. // The following statement was changed. See the comments. //return (Math.Abs(total_angle) > 0.000001); return(Math.Abs(total_angle) > 1); }
protected override MapPolygon CreateNativeItem(Circle outerItem) { Color color = outerItem.StrokeColor; Color fillcolor = outerItem.FillColor; Geopath geopath = GenerateCircleGeopath(outerItem.Center, outerItem.Radius.Meters); MapPolygon polygon = new MapPolygon { FillColor = Windows.UI.Color.FromArgb( (byte)(fillcolor.A * 255), (byte)(fillcolor.R * 255), (byte)(fillcolor.G * 255), (byte)(fillcolor.B * 255)), StrokeColor = Windows.UI.Color.FromArgb( (byte)(color.A * 255), (byte)(color.R * 255), (byte)(color.G * 255), (byte)(color.B * 255)), StrokeThickness = outerItem.StrokeWidth, ZIndex = outerItem.ZIndex, Path = geopath }; NativeMap.MapElements.Add(polygon); outerItem.NativeObject = polygon; return(polygon); }
//draws route lines using Great Circle Navigation math //https://en.wikipedia.org/wiki/Great-circle_navigation private void DrawLinesOnMap() { if (_waypoints.Count > 1) { //****************************************************************** //call into the method that does the heavy lifting for calculations. //****************************************************************** List <BasicGeoposition> geopositions = GetGeopositions(); //probably unnecessary, but we'll check anyway if (geopositions.Count == 0) { return; } //define the lines (which is actually 1 or more line segments) var path = new Geopath(geopositions); var line = new MapPolyline(); line.StrokeThickness = 5; line.StrokeColor = Colors.CornflowerBlue; line.Path = path; //and put them on the map. Map.MapElements.Add(line); } }
private async void UpdatePolyLine() { if (formsMap != null && formsMap.RouteCoordinates.Count > 0) { List <BasicGeoposition> coordinates = new List <BasicGeoposition>(); foreach (var position in formsMap.RouteCoordinates) { coordinates.Add(new BasicGeoposition() { Latitude = position.Latitude, Longitude = position.Longitude }); } // // o desenho do percurso no mapa deve ser feito pelo Thread UI // Device.BeginInvokeOnMainThread(() => { Geopath path = new Geopath(coordinates); MapPolyline polyline = new MapPolyline { StrokeColor = Windows.UI.Color.FromArgb(128, 255, 0, 0), StrokeThickness = 5, Path = path }; nativeMap.MapElements.Add(polyline); } ); } else { nativeMap.MapElements.Clear(); } }
/// <summary> /// Plot polyline on MapControls for selected route directions /// </summary> private async void PlotRouteDirectionsAsyc(RouteData routeData) { MyMap.MapElements.Clear(); if (routeData == null) { return; } int legcount = 0; List <BasicGeoposition> positions = new List <BasicGeoposition>(); foreach (var leg in routeData.Route.legs) { List <BasicGeoposition> pts = new List <BasicGeoposition>(); foreach (var point in leg.points) { BasicGeoposition pt = new BasicGeoposition() { Latitude = point.latitude, Longitude = point.longitude, Altitude = 50 }; pts.Add(pt); } positions.AddRange(pts); Color color = Color.FromArgb(255, 0, 88, 161); switch (legcount) { case 0: color = Color.FromArgb(255, 0, 88, 161); break; case 1: color = Color.FromArgb(255, 30, 116, 189); break; case 2: color = Color.FromArgb(255, 11, 171, 209); break; default: color = Color.FromArgb(255, 11, 171, 209); break; } legcount++; Geopath path = new Geopath(pts); MapPolyline polyline = new MapPolyline() { Path = path, StrokeThickness = 5, StrokeColor = color }; MyMap.MapElements.Add(polyline); } bool isSuccessful = await SetViewBoundsAsync(positions); }
public InvertMaskMapTileSource(Geopath path, Color colorIn, Color colorOut) : base() { Path = path; ColorIn = colorIn; ColorOut = colorOut; var dataSource = new CustomMapTileDataSource(); dataSource.BitmapRequested += BitmapRequested; DataSource = dataSource; }
public PolygonContainsPoint(Geopath path) { polySides = path.Positions.Count; foreach (BasicGeoposition point in path.Positions) { polyX.Add(point.Longitude); polyY.Add(point.Latitude); } precalc_values(); }
public void AddPoint(Coords coordinate) { positions.Add(new Position(coordinate.DegLatitude, coordinate.DegLongitude)); Geopath.Clear(); foreach (var p in positions) { Geopath.Add(p); } ; }
/// <summary> /// adds a polyline on the map /// </summary> private async void AddLine() { var size = ViewModel.DestinationsList.Count; if (CurrentLine != null) { Map.Layers.Remove(CurrentLine); } if (size <= 1) { return; } var destArray = ViewModel.GetDestinationsAsArray(); var coords = new List <BasicGeoposition>(); DrawPoints(destArray); for (var i = 0; i < destArray.Length; i++) { var dest = destArray[i]; BasicGeoposition point = new BasicGeoposition() { Latitude = dest.Latitude, Longitude = dest.Longitude }; coords.Add(point); } Geopath path = new Geopath(coords); MapPolyline polygon = new MapPolyline(); polygon.StrokeColor = Colors.Blue; polygon.StrokeThickness = 5; polygon.Path = path; polygon.StrokeDashed = true; var MyLines = new List <MapElement>(); MyLines.Add(polygon); var LinesLayer = new MapElementsLayer { ZIndex = 1, MapElements = MyLines }; if (CurrentLine != null) { Map.Layers.Remove(CurrentLine); } Map.Layers.Add(LinesLayer); this.CurrentLine = LinesLayer; await Map.TrySetViewBoundsAsync(GeoboundingBox.TryCompute(coords), null, MapAnimationKind.None); //Map.ZoomLevel = bingMap.ZoomLevel * 0.85 }
/// <summary> /// Converts a Geopath into a CoordinateCollection object. /// </summary> /// <param name="locations">A Geopath object</param> /// <returns>A CoordinateCollection representation of the Geopath object</returns> public static CoordinateCollection ToGeometry(this Geopath locations) { CoordinateCollection coords = new CoordinateCollection(); for (int i = 0; i < locations.Positions.Count; i++) { coords.Add(locations.Positions[i].ToGeometry()); } return(coords); }
public void GenerateGeoPath() { if (Geopath.Any()) { return; } foreach (var position in Positions) { Geopath.Add(new Position(position.Latitude, position.Longitude)); } }
private void myMap_MapElementClick(MapControl sender, MapElementClickEventArgs args) { this.addNewElementLock = true; if (args.MapElements[0] is MapPolyline) { MapPolyline polyLine = args.MapElements[0] as MapPolyline; Geopath path = polyLine.Path; Geopoint end = new Geopoint(path.Positions.LastOrDefault()); Waypoint wp = this.waypointManager.GetWayPointByPosition(end); if (wp != null) { this.rootPage.NotifyUser(wp.DistanceToPreviousWayPoint, NotifyType.StatusMessage); } } }
public Line(List <Coords> points) : base() { StrokeWidth = 8; StrokeColor = Color.Black; positions = new List <Position>(); foreach (var p in points) { positions.Add(new Position(p.DegLatitude, p.DegLongitude)); } foreach (var p in positions) { Geopath.Add(p); } ; }
public override MapElement CreateShape(object viewModel, Geopath path) { var icon = new MapIcon { Location = new Geopoint(path.Positions[0]), NormalizedAnchorPoint = new Point(AnchorX,AnchorY), ZIndex = ZIndex}; if (!string.IsNullOrWhiteSpace(Title)) { icon.Title = Title; } if (!string.IsNullOrWhiteSpace(ImageUri)) { icon.Image = RandomAccessStreamReference.CreateFromUri(new Uri(ImageUri)); } return icon; }
public GeoboundingBox GetMapViewBoundingBox() { //Only available in AU and later if (ApiInformation.IsMethodPresent("Windows.UI.Xaml.Controls.Maps.MapControl", "GetVisibleRegion")) { Geopath geopath = DigiTransitMapControl.GetVisibleRegion(MapVisibleRegionKind.Full); if (geopath == null) { return(null); } return(GetCoordinateGeoboundingBox(geopath.Positions)); } else //pre-AU { return(GetBounds()); } }
private List <PointOfInterest> GetVisibleItems(Geopath visible) { if (PokeMap.ZoomLevel < 15) { return(null); } var visibleItems = new List <PointOfInterest>(); foreach (var p in portals) { if (PointInPolygon(p.Location.Position, visible)) { visibleItems.Add(p); } } return(visibleItems); }
public override MapElement CreateShape(object viewModel, Geopath path) { var icon = new MapIcon { Location = new Geopoint(path.Positions[0]), NormalizedAnchorPoint = new Point(AnchorX, AnchorY), ZIndex = ZIndex }; if (!string.IsNullOrWhiteSpace(Title)) { icon.Title = Title; } if (!string.IsNullOrWhiteSpace(ImageUri)) { icon.Image = RandomAccessStreamReference.CreateFromUri(new Uri(ImageUri)); } return(icon); }
private void UpdateUserLocation(Geoposition geoposition) { if (_mapPolyline == null) { _mapPolyline = new MapPolyline { Path = new Geopath(new List <BasicGeoposition> { geoposition.Coordinate.Point.Position }), StrokeColor = Colors.Green, StrokeThickness = 3, StrokeDashed = true }; Map.MapElements.Add(_mapPolyline); } else { var geopath = new Geopath(new List <BasicGeoposition>(_mapPolyline.Path.Positions) { geoposition.Coordinate.Point.Position }); _mapPolyline.Path = geopath; } if (_userIcon == null) { _userIcon = new MapIcon { Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/guy.png")), Title = Settings.Language == VVVOnTheWay.Language.ENGLISH ? "Your Location" : "Uw locatie", Location = geoposition.Coordinate.Point, NormalizedAnchorPoint = new Windows.Foundation.Point(0.5, 1.0) }; Map.MapElements.Add(_userIcon); } else { _userIcon.Location = geoposition.Coordinate.Point; } }
protected override MapPolygon CreateNativeItem(Polygon outerItem) { Color color = outerItem.StrokeColor; Color fillcolor = outerItem.FillColor; Geopath geopath = new Geopath(outerItem.Positions.Select(position => new BasicGeoposition { Latitude = position.Latitude, Longitude = position.Longitude })); MapPolygon nativePolygon = new MapPolygon { FillColor = Windows.UI.Color.FromArgb( (byte)(fillcolor.A * 255), (byte)(fillcolor.R * 255), (byte)(fillcolor.G * 255), (byte)(fillcolor.B * 255)), StrokeColor = Windows.UI.Color.FromArgb( (byte)(color.A * 255), (byte)(color.R * 255), (byte)(color.G * 255), (byte)(color.B * 255)), StrokeThickness = outerItem.StrokeWidth, ZIndex = outerItem.ZIndex, }; nativePolygon.Paths.Add(geopath); foreach (var hole in outerItem.Holes) { nativePolygon.Paths.Add(new Geopath(hole.Select(position => new BasicGeoposition { Latitude = position.Latitude, Longitude = position.Longitude }))); } NativeMap.MapElements.Add(nativePolygon); outerItem.NativeObject = nativePolygon; return(nativePolygon); }
private MapPolyline MakePolyline(Trk trk) { if (trk == null) return null; MapPolyline polyline = new MapPolyline(); polyline.StrokeColor = Colors.Red; polyline.StrokeThickness = 2; List<BasicGeoposition> pos = new List<BasicGeoposition>(); BasicGeoposition bpos; foreach (TrkPt pt in trk.TrkPts) { bpos = new BasicGeoposition(); bpos.Latitude = pt.Latitude; bpos.Longitude = pt.Longitude; pos.Add(bpos); } Geopath p = new Geopath(pos); polyline.Path = p; return polyline; }
public void LoadMapElements(List <List <Polygon> > poligonslist, List <FieldLocationData[]> fieldPois) { MapControlViewElement.MapElements.Clear(); foreach (var poligons in poligonslist) { var a = poligons.Select(i => new BasicGeoposition { Latitude = i.lat, Longitude = i.lon }).ToList(); var path = new Geopath(poligons.Select(i => new BasicGeoposition { Latitude = i.lat, Longitude = i.lon }).ToList()); var line = new MapPolygon { Path = path, StrokeColor = Colors.Green, FillColor = Colors.Teal, StrokeThickness = 2, }; MapControlViewElement.MapElements.Add(line); } //SetCenter(46.595600128173828, 20.308347702026367); foreach (var pois in fieldPois) { foreach (var poi in pois) { MapControlViewElement.MapElements.Add(new MapIcon() { Location = new Geopoint(new BasicGeoposition() { Latitude = poi.lat, Longitude = poi.lon }) }); } } }
protected override void CreateHeatMapIfNeeded() { if (_heatMapLayer == null) { IEnumerable <BasicGeoposition> positions = FormsMap.Locations?.Select(pos => new BasicGeoposition { Latitude = pos.Latitude, Longitude = pos.Longitude }); Geopath polygonPath = new Geopath(positions); _heatMapLayer = new HeatMapLayer(FormsMap) { ParentMap = _nativeMap, Locations = polygonPath, Radius = FormsMap.Radius, Intensity = FormsMap.Intensity, Visibility = Visibility.Collapsed }; _nativeMap.Children.Add(_heatMapLayer); } }
public PathAnimation(Geopath path, IntervalCallback intervalCallback, bool isGeodesic, int?duration) { _path = path; _isGeodesic = isGeodesic; _duration = duration; PreCalculate(); _timerId = new DispatcherTimer(); _timerId.Interval = new TimeSpan(0, 0, 0, 0, _delay); _timerId.Tick += (s, a) => { if (!_isPaused) { double progress = (double)(_frameIdx * _delay) / (double)_duration.Value; if (progress > 1) { progress = 1; } if (intervalCallback != null) { intervalCallback(_intervalLocs[_frameIdx], _intervalIdx[_frameIdx], _frameIdx); } if (progress == 1) { _timerId.Stop(); } _frameIdx++; } }; }
public abstract MapElement CreateShape(object viewModel, Geopath path);
public override MapElement CreateShape(object viewModel, Geopath path) { return new MapPolyline { Path = path, StrokeThickness = Width, StrokeColor = Color, StrokeDashed = StrokeDashed, ZIndex = ZIndex}; }
private async void button_Click_1(object sender, RoutedEventArgs e) { MapPolyline mapPolyline = new MapPolyline(); mapPolyline.StrokeColor = Colors.Indigo; mapPolyline.StrokeThickness = 5; List <BasicGeoposition> positions = new List <BasicGeoposition>(); SQLiteConnection connection = new SQLiteConnection("localstore.db"); if (Calendar.Date != null) { DateTime selectedDate = Calendar.Date.Value.DateTime; string newDate = selectedDate.ToString("dd-MM-yyyy"); var selec = listBox.SelectedItem; if (selec != null) { using (var statement = connection.Prepare($"SELECT Longitude, Latitude FROM Data Where DeviceId = {selec} and substr(TIMESTAMP,1,10) = '{newDate}'")) { while (statement.Step() == SQLiteResult.ROW) { positions.Add(new BasicGeoposition() { Latitude = (double)statement[1], Longitude = (double)statement[0] }); } } } else { var dialog = new MessageDialog("Выберите устройство!"); await dialog.ShowAsync(); return; } try { Geopath path = new Geopath(positions); mapPolyline.Path = path; MyMap.MapElements.Add(mapPolyline); } catch (Exception) { var dialog = new MessageDialog("Нет данных за этот период!"); await dialog.ShowAsync(); return; } using (var statement = connection.Prepare($"SELECT min(Timestamp) FROM Data Where DeviceId = {selec} and substr(TIMESTAMP,1,10) = '{newDate}'")) { while (statement.Step() == SQLiteResult.ROW) { textBox1.Text = "Начало движения" + Environment.NewLine + (string)statement[0]; } } using (var statement = connection.Prepare($"SELECT max(Timestamp) FROM Data Where DeviceId = {selec} and substr(TIMESTAMP,1,10) = '{newDate}'")) { while (statement.Step() == SQLiteResult.ROW) { textBox.Text = "Конец движения" + Environment.NewLine + (string)statement[0]; } } using (var statement = connection.Prepare($"SELECT max(Speed) FROM Data Where DeviceId = {selec} and substr(TIMESTAMP,1,10) = '{newDate}'")) { while (statement.Step() == SQLiteResult.ROW) { textBox2.Text = "Максимальная скорость" + Environment.NewLine + Math.Round(((double)statement[0] * 3.6), 2) + " км/ч"; } } using (var statement = connection.Prepare($"SELECT avg(Speed) FROM Data Where DeviceId = {selec} and substr(TIMESTAMP,1,10) = '{newDate}'")) { while (statement.Step() == SQLiteResult.ROW) { textBox3.Text = "Средняя скорость" + Environment.NewLine + Math.Round(((double)statement[0] * 3.6), 2) + " км/ч"; } } using (var statement = connection.Prepare($"SELECT max(Timestamp),min(Timestamp) FROM Data Where DeviceId = {selec} and substr(TIMESTAMP,1,10) = '{newDate}'")) { while (statement.Step() == SQLiteResult.ROW) { textBox4.Text = "Время в пути" + Environment.NewLine + (DateTime.Parse((string)statement[0]) - DateTime.Parse((string)statement[1])).ToString(); } } using (var statement = connection.Prepare($"SELECT max(Timestamp),min(Timestamp),avg(Speed) FROM Data Where DeviceId = {selec} and substr(TIMESTAMP,1,10) = '{newDate}'")) { while (statement.Step() == SQLiteResult.ROW) { double a = ((double)statement[2]); TimeSpan b = DateTime.Parse((string)statement[0]) - DateTime.Parse((string)statement[1]); double res = (b.TotalSeconds * a) / 1000; textBox5.Text = "Пройденный путь" + Environment.NewLine + Math.Round(res, 3).ToString() + " км"; } } using (var statement = connection.Prepare($"SELECT Timestamp, Longitude, Latitude FROM Data WHERE rowid % 25 = 0 and DeviceId = {selec} and substr(TIMESTAMP,1,10) = '{newDate}'")) { while (statement.Step() == SQLiteResult.ROW) { BasicGeoposition snPosition = new BasicGeoposition() { Latitude = (double)statement[2], Longitude = (double)statement[1] }; // Specify a known location. Geopoint snPoint = new Geopoint(snPosition); // Create a MapIcon. MapIcon mapIcon1 = new MapIcon(); mapIcon1.Location = snPoint; mapIcon1.NormalizedAnchorPoint = new Point(0.5, 1.0); mapIcon1.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/2.png")); mapIcon1.Title = "Я был тут" + Environment.NewLine + (string)statement[0]; mapIcon1.ZIndex = 0; // Add the MapIcon to the map. MyMap.MapElements.Add(mapIcon1); } } } else { var dialog = new MessageDialog("Выберите дату!"); await dialog.ShowAsync(); } }
private async Task GetSampleDataAsync() { if (this._groups.Count != 0) { return; } Uri dataUri = new Uri("ms-appx:///DataModel/SampleData.json"); StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri); string jsonText = await FileIO.ReadTextAsync(file); JsonObject jsonObject = JsonObject.Parse(jsonText); JsonArray jsonArray = jsonObject["PointsOfInterest"].GetArray(); foreach (JsonValue groupValue in jsonArray) { JsonObject groupObject = groupValue.GetObject(); IJsonValue shapeValue; List <BasicGeoposition> shapeList; Geopath shapePath = null; if (groupObject.TryGetValue("Shape", out shapeValue)) { //JsonObject shapeObject = shapeValue.GetObject(); string shape = shapeValue.GetString(); if (PathParser.TryParseEncodedValue(shape, out shapeList)) { shapePath = new Geopath(shapeList); } } IJsonValue bestMapViewBoxValue; List <BasicGeoposition> bestMapViewBoxList = new List <BasicGeoposition>(); GeoboundingBox bestMapViewBox = null; if (groupObject.TryGetValue("BestMapViewBox", out bestMapViewBoxValue)) { foreach (JsonValue itemValue in bestMapViewBoxValue.GetArray()) { JsonObject itemObject = itemValue.GetObject(); IJsonValue locationValue = itemObject["location"]; JsonObject locationObject = locationValue.GetObject(); BasicGeoposition location = new BasicGeoposition { Latitude = locationObject["lat"].GetNumber(), Longitude = locationObject["lng"].GetNumber() }; bestMapViewBoxList.Add(location); } bestMapViewBox = GeoboundingBox.TryCompute(bestMapViewBoxList); } SampleDataGroup group = new SampleDataGroup(groupObject["UniqueId"].GetString(), groupObject["Title"].GetString(), groupObject["Subtitle"].GetString(), groupObject["ImagePath"].GetString(), groupObject["Description"].GetString(), bestMapViewBox, shapePath); foreach (JsonValue itemValue in groupObject["Items"].GetArray()) { JsonObject itemObject = itemValue.GetObject(); IJsonValue geometryValue; Geopoint location = null; string address = null; if (itemObject.TryGetValue("geometry", out geometryValue)) { JsonObject geometryObject = geometryValue.GetObject(); IJsonValue locationValue = geometryObject["location"]; JsonObject locationObject = locationValue.GetObject(); location = new Geopoint(new BasicGeoposition { Latitude = locationObject["lat"].GetNumber(), Longitude = locationObject["lng"].GetNumber() }); } IJsonValue addressValue = null; if (itemObject.TryGetValue("formatted_address", out addressValue)) { address = addressValue.GetString(); } group.Items.Add(new SampleDataItem(itemObject["UniqueId"].GetString(), itemObject["Title"].GetString(), itemObject["Subtitle"].GetString(), itemObject["ImagePath"].GetString(), itemObject["Description"].GetString(), itemObject["Content"].GetString(), location, address)); } this.Groups.Add(group); } }
protected virtual MapElement CreateDrawable(object viewModel, Geopath path) { var newShape = ShapeDrawer.CreateShape(viewModel, path); return(newShape); }
public SampleDataGroup(String uniqueId, String title, String subtitle, String imagePath, String description, GeoboundingBox bestMapViewBoxList, Geopath shapePath) { this.UniqueId = uniqueId; this.Title = title; this.Subtitle = subtitle; this.Description = description; this.ImagePath = imagePath; this.BestMapViewBoxList = bestMapViewBoxList; this.ShapePath = shapePath; this.Items = new ObservableCollection <SampleDataItem>(); }
/// <summary> /// Handler for <see cref="Page.OnNavigatedTo(Windows.UI.Xaml.Navigation.NavigationEventArgs)" />. /// </summary> /// <param name="parameter"><see cref="Windows.UI.Xaml.Navigation.NavigationEventArgs.Parameter" />.</param> public async void Activate(object parameter) { string lsActivityID = parameter as string; MSHealthActivities loActivities = null; MSHealthSplitDistanceType loDistanceType = MSHealthSplitDistanceType.None; MSHealthActivityInclude loInclude = MSHealthActivityInclude.Details | MSHealthActivityInclude.MapPoints; IsLoaded = false; Activity = null; TotalDistance = null; DistanceUnitShort = null; Pace = null; Splits = null; HeartRateZones = null; MapPath = null; ElevationGain = null; ElevationLoss = null; MaxElevation = null; MinElevation = null; IsElevationAvailable = false; IsHeartRateZonesAvailable = false; IsNikePlusAvailable = false; List<HeartRateZoneItem> loHeartRateZones = null; // Set back button visible (for Windows app) SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible; // Check parameter (Activity ID) if (!string.IsNullOrEmpty(lsActivityID)) { IsRunningRequest = true; // Determine Distance Unit switch (Settings.MSHealthFilterDistance) { case DistanceUnit.DISTANCE_MILE: loDistanceType = MSHealthSplitDistanceType.Mile; DistanceUnitShort = Resources.Strings.TextDistanceUnitShortMileText; break; case DistanceUnit.DISTANCE_KILOMETER: loDistanceType = MSHealthSplitDistanceType.Kilometer; DistanceUnitShort = Resources.Strings.TextDistanceUnitShortKilometerText; break; } try { // Get Activity details loActivities = await moMSHealthClient.ListActivities(ids: lsActivityID, include: loInclude, splitDistanceType: loDistanceType); // Check Activity details returned if (loActivities.ItemCount > 0) { // Map from derivated activities to single instance activity if (loActivities.FreePlayActivities != null && loActivities.FreePlayActivities.Any()) Activity = loActivities.FreePlayActivities.FirstOrDefault(); else if (loActivities.RunActivities != null && loActivities.RunActivities.Any()) Activity = loActivities.RunActivities.FirstOrDefault(); else if (loActivities.BikeActivities != null && loActivities.BikeActivities.Any()) Activity = loActivities.BikeActivities.FirstOrDefault(); else if (loActivities.GolfActivities != null && loActivities.GolfActivities.Any()) Activity = loActivities.GolfActivities.FirstOrDefault(); else if (loActivities.GuidedWorkoutActivities != null && loActivities.GuidedWorkoutActivities.Any()) Activity = loActivities.GuidedWorkoutActivities.FirstOrDefault(); else if (loActivities.SleepActivities != null && loActivities.SleepActivities.Any()) Activity = loActivities.SleepActivities.FirstOrDefault(); else if (loActivities.HikeActivities != null && loActivities.HikeActivities.Any()) Activity = loActivities.HikeActivities.FirstOrDefault(); } // Check current activity instance if (Activity != null) { // Calculate Total Distance if (Activity.SplitDistance != null && Activity.SplitDistance.HasValue && Activity.SplitDistance.Value > 0 && Activity.DistanceSummary != null && Activity.DistanceSummary.TotalDistance != null && Activity.DistanceSummary.TotalDistance.HasValue) { TotalDistance = (decimal)Activity.DistanceSummary.TotalDistance / (decimal)Activity.SplitDistance; } // Calculate Pace if (Activity.DistanceSummary != null && Activity.DistanceSummary.Pace != null && Activity.DistanceSummary.Pace.HasValue) { Pace = TimeSpan.FromMilliseconds((double)Activity.DistanceSummary.Pace); } // Calculate Elevation if (Activity.DistanceSummary != null) { // Elevation Gain if (Activity.DistanceSummary.ElevationGain != null) { ElevationGain = (double)Activity.DistanceSummary.ElevationGain / MSHealthDistanceSummary.ELEVATION_FACTOR; IsElevationAvailable = true; } // Elevation Loss if (Activity.DistanceSummary.ElevationLoss != null) { ElevationLoss = (double)Activity.DistanceSummary.ElevationLoss / MSHealthDistanceSummary.ELEVATION_FACTOR; IsElevationAvailable = true; } // Max Elevation if (Activity.DistanceSummary.MaxElevation != null) { MaxElevation = (double)Activity.DistanceSummary.MaxElevation / MSHealthDistanceSummary.ELEVATION_FACTOR; IsElevationAvailable = true; } // Min Elevation if (Activity.DistanceSummary.MinElevation != null) { MinElevation = (double)Activity.DistanceSummary.MinElevation / MSHealthDistanceSummary.ELEVATION_FACTOR; IsElevationAvailable = true; } } // Heart Rate Zones if (Activity.PerformanceSummary != null && Activity.PerformanceSummary.HeartRateZones != null) { loHeartRateZones = new List<HeartRateZoneItem>(); // Underhealthy loHeartRateZones.Add(new HeartRateZoneItem() { Key = HeartRateZoneItem.HRZONE_UNDER_HEALTHY, Name = Resources.Strings.TextHeartRateZoneUnderHealthyText, Value = Activity.PerformanceSummary.HeartRateZones.UnderHealthyHeart ?? 0, }); // Healthy loHeartRateZones.Add(new HeartRateZoneItem() { Key = HeartRateZoneItem.HRZONE_HEALTHY, Name = Resources.Strings.TextHeartRateZoneHealthyText, Value = Activity.PerformanceSummary.HeartRateZones.HealthyHeart ?? 0, }); // Fitness loHeartRateZones.Add(new HeartRateZoneItem() { Key = HeartRateZoneItem.HRZONE_FITNESS, Name = Resources.Strings.TextHeartRateZoneFitnessText, Value = Activity.PerformanceSummary.HeartRateZones.FitnessZone ?? 0, }); // Aerobic loHeartRateZones.Add(new HeartRateZoneItem() { Key = HeartRateZoneItem.HRZONE_AEROBIC, Name = Resources.Strings.TextHeartRateZoneAerobicText, Value = Activity.PerformanceSummary.HeartRateZones.Aerobic ?? 0, }); // Anaerobic loHeartRateZones.Add(new HeartRateZoneItem() { Key = HeartRateZoneItem.HRZONE_ANAEROBIC, Name = Resources.Strings.TextHeartRateZoneAnaerobicText, Value = Activity.PerformanceSummary.HeartRateZones.Anaerobic ?? 0, }); // Redline loHeartRateZones.Add(new HeartRateZoneItem() { Key = HeartRateZoneItem.HRZONE_REDLINE, Name = Resources.Strings.TextHeartRateZoneRedlineText, Value = Activity.PerformanceSummary.HeartRateZones.Redline ?? 0, }); // OverRedline loHeartRateZones.Add(new HeartRateZoneItem() { Key = HeartRateZoneItem.HRZONE_OVER_REDLINE, Name = Resources.Strings.TextHeartRateZoneOverRedlineText, Value = Activity.PerformanceSummary.HeartRateZones.OverRedline ?? 0, }); HeartRateZones = new ObservableCollection<HeartRateZoneItem>(loHeartRateZones); IsHeartRateZonesAvailable = true; } // Segments (splits) if (Activity.ActivitySegments != null && Activity.ActivitySegments.Any() && TotalDistance != null) { // ActivitySegment to Split double ldSplitValue = 0; List<SplitItem> loSplits = new List<SplitItem>(); foreach (MSHealthActivitySegment loSegment in Activity.ActivitySegments.OrderBy(loSeg => loSeg.StartTime)) { ldSplitValue++; loSplits.Add(new SplitItem() { Value = ldSplitValue > (double)TotalDistance.Value ? (double)TotalDistance.Value : ldSplitValue, Duration = loSegment.Duration.Value, AvgHeartRate = loSegment.HeartRateSummary != null ? loSegment.HeartRateSummary.AverageHeartRate.Value : 0, }); } // Get Max/Min Duration/HR, for complete splits only try { loSplits.Where(loSplit => (loSplit.Value % 1) == 0).OrderBy(loSplit => loSplit.Duration).First().DurationMark = "↓"; loSplits.Where(loSplit => (loSplit.Value % 1) == 0).OrderByDescending(loSplit => loSplit.Duration).First().DurationMark = "↑"; loSplits.Where(loSplit => (loSplit.Value % 1) == 0).OrderBy(loSplit => loSplit.AvgHeartRate).First().HRMark = "↓"; loSplits.Where(loSplit => (loSplit.Value % 1) == 0).OrderByDescending(loSplit => loSplit.AvgHeartRate).First().HRMark = "↑"; } catch { /* Do nothing */ } // Sort by value and assign to instance loSplits = loSplits.OrderBy(loSplit => loSplit.Value).ToList(); Splits = new ObservableCollection<SplitItem>(loSplits); } // MapPoints to MapPath if (Activity.MapPoints != null && Activity.MapPoints.Any()) { List<BasicGeoposition> loGeopositions = new List<BasicGeoposition>(); loGeopositions = (from loMapPoint in Activity.MapPoints .Where(loPoint => loPoint.Location != null && loPoint.Location.Latitude != null && loPoint.Location.Longitude != null) .OrderBy(loPoint => loPoint.Ordinal) select new BasicGeoposition() { Latitude = (double)loMapPoint.Location.Latitude / MSHealthGPSPoint.LATITUDE_FACTOR, Longitude = (double)loMapPoint.Location.Longitude / MSHealthGPSPoint.LONGITUDE_FACTOR, Altitude = loMapPoint.Location.ElevationFromMeanSeaLevel != null ? ((double)loMapPoint.Location.ElevationFromMeanSeaLevel / MSHealthGPSPoint.ELEVATION_FACTOR) : 0d, }).ToList(); //foreach (var loMapPoint in Activity.MapPoints) //{ // if (loMapPoint.Location != null && // loMapPoint.Location.Latitude != null && // loMapPoint.Location.Longitude != null) // { // loGeopositions.Add(new BasicGeoposition() // { // Latitude = (double)loMapPoint.Location.Latitude / 10000000d, // Longitude = (double)loMapPoint.Location.Longitude / 10000000d, // }); // } //} if (loGeopositions.Any()) { MapPath = new Geopath(loGeopositions); } } } } catch (Exception loException) { // Handle exceptions (just for debugging purposes) if (System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debug.WriteLine(loException.StackTrace); await moDialogService.ShowError(Resources.Strings.MessageContentErrorOperation, Resources.Strings.MessageTitleError, Resources.Strings.MessageButtonOK, null); // Return to main page moNavigationService.GoBack(); } finally { Messenger.Default.Send<Geopath>(MapPath); IsRunningRequest = false; } // Check for Nike+ Credentials if (Settings.NikePlusCredential != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(Settings.NikePlusCredential.Password, "[\"&`'<>]")) { try { // Check for GPS data if (Activity.MapPoints == null || !Activity.MapPoints.Any()) { // Get Minute Summaries loActivities = await moMSHealthClient.ListActivities(ids: lsActivityID, include: MSHealthActivityInclude.MinuteSummaries, splitDistanceType: loDistanceType); // Check Activity details returned if (loActivities.ItemCount > 0) { // Map from derivated activities to single instance activity if (loActivities.FreePlayActivities != null && loActivities.FreePlayActivities.Any()) Activity.MinuteSummaries = loActivities.FreePlayActivities.FirstOrDefault().MinuteSummaries; else if (loActivities.RunActivities != null && loActivities.RunActivities.Any()) Activity.MinuteSummaries = loActivities.RunActivities.FirstOrDefault().MinuteSummaries; else if (loActivities.BikeActivities != null && loActivities.BikeActivities.Any()) Activity.MinuteSummaries = loActivities.BikeActivities.FirstOrDefault().MinuteSummaries; else if (loActivities.GolfActivities != null && loActivities.GolfActivities.Any()) Activity.MinuteSummaries = loActivities.GolfActivities.FirstOrDefault().MinuteSummaries; else if (loActivities.GuidedWorkoutActivities != null && loActivities.GuidedWorkoutActivities.Any()) Activity.MinuteSummaries = loActivities.GuidedWorkoutActivities.FirstOrDefault().MinuteSummaries; else if (loActivities.SleepActivities != null && loActivities.SleepActivities.Any()) Activity.MinuteSummaries = loActivities.SleepActivities.FirstOrDefault().MinuteSummaries; } } } catch (Exception loException) { // Handle exceptions (just for debugging purposes) if (System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debug.WriteLine(loException.StackTrace); } // Ensure Activity either has GPS or MinuteSummaries data if ((Activity.MapPoints != null && Activity.MapPoints.Any()) || (Activity.MinuteSummaries != null && Activity.MinuteSummaries.Any())) { moNikePlusClient.SetCredentials(Settings.NikePlusCredential.UserName, Settings.NikePlusCredential.Password); IsNikePlusAvailable = true; } } } IsLoaded = true; } }
public override MapElement CreateShape(object viewModel, Geopath path) { return(new MapPolyline { Path = path, StrokeThickness = Width, StrokeColor = Color, StrokeDashed = StrokeDashed, ZIndex = ZIndex }); }