Exemplo n.º 1
0
 //Initialize the route line indicator. 
 private void InitializeLine()
 {
     _line = new MapPolyline();
     _line.StrokeColor = Colors.Red;
     _line.StrokeThickness = 5;
     Map.MapElements.Add(_line);
 }
Exemplo n.º 2
0
        public WorkoutMapStatisticsPage()
        {
            InitializeComponent();
            routeLine = new MapPolyline();
            routeLine.Locations = selectedWorkout.routeLine.Locations; // Where the magic happens: Note: ALL routes MUST have a polyline, otherwise the application WILL ofcourse, CRASH!
            routeLine.Stroke = new SolidColorBrush(Colors.Blue);
            routeLine.StrokeThickness = 5;
            Pushpin pStart = new Pushpin();
            pStart.Content = "Start";
            pStart.Background = new SolidColorBrush(Colors.Green);
            Pushpin pFinish = new Pushpin();
            pFinish.Content = "Finish";
            pFinish.Background = new SolidColorBrush(Colors.Red);
            layer.AddChild(pStart, new GeoCoordinate(routeLine.Locations.First().Latitude, routeLine.Locations.First().Longitude));
            layer.AddChild(pFinish, new GeoCoordinate(routeLine.Locations.Last().Latitude, routeLine.Locations.Last().Longitude));
            map2.Children.Add(routeLine);
            map2.Children.Add(layer);
            textBlock5.Text = selectedWorkout.workoutName;
            textBlock6.Text = selectedWorkout.startTime;
            textBlock7.Text = String.Format("{0:F2}", selectedWorkout.distanceRan);
            textBlock8.Text = string.Format("{0:00}:{1:00}:{2:00}",
               selectedWorkout.elapsedTimeTS.Hours,
                selectedWorkout.elapsedTimeTS.Minutes,
                selectedWorkout.elapsedTimeTS.Seconds); ;

            double latitude;
            double longitude;
            getWorkoutRouteLocation(out latitude, out longitude);

            map2.Center = new GeoCoordinate(latitude, longitude);
            map2.ZoomLevel = 16;
        }
Exemplo n.º 3
0
        void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            var rootObject = JsonConvert.DeserializeObject<Rootobject>(e.Result);
            double lat, longitude;
            MapPolyline line = new MapPolyline();
            line.StrokeColor = Colors.Green;
            line.StrokeThickness = 2;

            double[] coord = new double[2 * rootObject.direction[0].stop.Length];
            for (int i = 0; i < rootObject.direction[0].stop.Length; i++)
            {
                lat = Convert.ToDouble(rootObject.direction[0].stop[i].stop_lat);
                longitude = Convert.ToDouble(rootObject.direction[0].stop[i].stop_lon);

                line.Path.Add(new GeoCoordinate(lat, longitude));

                Ellipse myCircle = new Ellipse();
                myCircle.Fill = new SolidColorBrush(Colors.Green);
                myCircle.Height = 15;
                myCircle.Width = 15;
                myCircle.Opacity = 60;
                MapOverlay myLocationOverlay = new MapOverlay();
                myLocationOverlay.Content = myCircle;
                myLocationOverlay.PositionOrigin = new Point(0.5, 0.5);
                myLocationOverlay.GeoCoordinate = new GeoCoordinate(lat, longitude, 200);
                MapLayer myLocationLayer = new MapLayer();
                myLocationLayer.Add(myLocationOverlay);
                map.Layers.Add(myLocationLayer);
            }
            map.MapElements.Add(line);
        }
Exemplo n.º 4
0
        public MainPage()
        {
            InitializeComponent();
            mainDatabase = new WorkoutDatabase();
            lastGPSlocation = null;
            joggingPolyLine = new MapPolyline();
            joggingPolyLine.Stroke = new SolidColorBrush(Colors.Blue);
            joggingPolyLine.StrokeThickness = 5;
            joggingPolyLine.Opacity = 0.7;
            joggingPolyLine.Locations = new LocationCollection();
            map1.Children.Add(joggingPolyLine);
            string deviceName = Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("DeviceName").ToString();

            if (deviceName == "XDeviceEmulator")                                                                    // Checks for device name in order to determine whether to simulate a jogger or not
            {
                //Note: The following coordinates is just a Test coordinate for when running the GeoCoordinate simulator
               geowatcher = new GeoCoordinateSimulator(51.5941116666667, 4.77941666666667);

            }
            else
            {
                geowatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
            }
            geowatcher.PositionChanged += watcher_PositionChanged;
            //The next line is responsible for loading the database from Isolated Storage. The loading and saving implementation works HOWEVER, It is NOT loaded properly and the previous workoutlist does not display previously saved workouts.
               // mainDatabase = dataSave.loadDatabaseFromIsolatedStorage("WorkoutDatabase");

               // checkIfFileExists();
        }
Exemplo n.º 5
0
        private async Task DrawPolyline(List<BasicGeoposition> geopositions)
        {
            ActivityMap.MapElements.Clear();

            if (geopositions.Any())
            {
                var polyLine = new MapPolyline { Path = new Geopath(geopositions), StrokeThickness = 4, StrokeColor = (Color)App.Current.Resources["StravaRedColor"] };
                ActivityMap.MapElements.Add(polyLine);

                MapIcon startMapIcon = new MapIcon();
                startMapIcon.Location = new Geopoint(geopositions.First());
                startMapIcon.NormalizedAnchorPoint = new Point(0.5, 0.5);
                startMapIcon.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/Start.png"));
                ActivityMap.MapElements.Add(startMapIcon);

                MapIcon endMapIcon = new MapIcon();
                endMapIcon.Location = new Geopoint(geopositions.Last());
                endMapIcon.NormalizedAnchorPoint = new Point(0.5, 0.5);
                endMapIcon.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/End.png"));
                ActivityMap.MapElements.Add(endMapIcon);

                var zoomed = false;
                while (!zoomed)
                    zoomed = await ActivityMap.TrySetViewBoundsAsync(GeoboundingBox.TryCompute(geopositions), null, MapAnimationKind.None);
            }
        }
Exemplo n.º 6
0
        private void Map_Loaded(object sender, RoutedEventArgs e)
        {
            Ellipse myCircle = new Ellipse();
            MapPolyline line = new MapPolyline();

            WebClient blue = new WebClient();
            line.StrokeColor = Colors.Blue;
            myCircle.Fill = new SolidColorBrush(Colors.Blue);
            blue.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
            blue.DownloadStringAsync(new Uri(blue946));
            WebClient green1 = new WebClient();
            line.StrokeColor = Colors.Green;
            myCircle.Fill = new SolidColorBrush(Colors.Green);
            green1.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
            green1.DownloadStringAsync(new Uri(green810));
            WebClient green2 = new WebClient();
            line.StrokeColor = Colors.Green;
            green2.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
            green2.DownloadStringAsync(new Uri(green830));
                    line.StrokeColor = Colors.Green;;
            WebClient green3 = new WebClient();
            green3.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
            green3.DownloadStringAsync(new Uri(green852));
                    line.StrokeColor = Colors.Green;
            WebClient orange = new WebClient();
            line.StrokeColor = Colors.Orange;
            myCircle.Fill = new SolidColorBrush(Colors.Orange);
            orange.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
            orange.DownloadStringAsync(new Uri(orange903));
            WebClient red = new WebClient();
            myCircle.Fill = new SolidColorBrush(Colors.Red);
            line.StrokeColor = Colors.Red;
            red.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
            red.DownloadStringAsync(new Uri(red931));
        }
Exemplo n.º 7
0
        protected override void OnElementChanged(ElementChangedEventArgs<Map> e)
        {
            base.OnElementChanged(e);

            if (e.OldElement != null)
            {
                // Unsubscribe
            }

            if (e.NewElement != null)
            {
                var formsMap = (CustomMap)e.NewElement;
                var nativeMap = Control as MapControl;

                var coordinates = new List<BasicGeoposition>();
                foreach (var position in formsMap.RouteCoordinates)
                {
                    coordinates.Add(new BasicGeoposition() { Latitude = position.Latitude, Longitude = position.Longitude });
                }

                var polyline = new MapPolyline();
                polyline.StrokeColor = Windows.UI.Color.FromArgb(128, 255, 0, 0);
                polyline.StrokeThickness = 5;
                polyline.Path = new Geopath(coordinates);
                nativeMap.MapElements.Add(polyline);
            }
        }
Exemplo n.º 8
0
    private void DrawLines(object sender, RoutedEventArgs e)
    {
        if (!DeleteShapesFromLevel(4))
        {
            var strokeColor = Colors.Green;

            //Drawing lines, notice the use of Geopath. Consists out of BasicGeopositions
            foreach (var dataObject in PointList.GetLines())
            {
                ///////////////////////////////////////////////////
                // Creating the a MapPolyLine 
                //   (stroke, path (list of BasicGeopositions)
                var shape = new MapPolyline
                {
                    StrokeThickness = 9,
                    StrokeColor = strokeColor,
                    StrokeDashed = false,
                    ZIndex = 4,
                    Path = new Geopath(dataObject.Points.Select(p => p.Position))
                };
                shape.AddData(dataObject);

                MyMap.MapElements.Add(shape);
            }
        }
    }
 /// <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;
     }
 }
Exemplo n.º 10
0
        public Route()
        {
            // default settings
            route = new MapPolyline();
            route.Stroke = new SolidColorBrush(Colors.Blue);
            route.StrokeThickness = 5;
            route.Opacity = 0.7;

            route.Locations = RouteFromLocations();
        }
Exemplo n.º 11
0
        void map1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Debug.WriteLine("map_MouseLeftButtonUp " + markerSelected + ", addPoint: " + addPoint);

            if (addPoint)
            {

                if (markerLayer == null) // create layer if it does not exists yet
                {
                    markerLayer = new MapLayer();
                    map1.Layers.Add(markerLayer);
                }


                MarkerCounter++;

                MapOverlay oneMarker = new MapOverlay();
                oneMarker.GeoCoordinate = map1.ConvertViewportPointToGeoCoordinate(e.GetPosition(map1));

                Ellipse Circhegraphic = new Ellipse();
                Circhegraphic.Fill = new SolidColorBrush(Colors.Yellow);
                Circhegraphic.Stroke = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Red);
                Circhegraphic.StrokeThickness = 10;
                Circhegraphic.Opacity = 0.8;
                Circhegraphic.Height = 30;
                Circhegraphic.Width = 30;

                oneMarker.Content = Circhegraphic;

                oneMarker.PositionOrigin = new Point(0.5, 0.5);
                Circhegraphic.MouseLeftButtonDown += Circhegraphic_MouseLeftButtonDown;
                Circhegraphic.MouseLeftButtonUp += Circhegraphic_MouseLeftButtonUp;

                markerLayer.Add(oneMarker);

                if (dynamicPolyline == null) // create polyline if it does not exists yet
                {
                    dynamicPolyline = new MapPolyline();
                    dynamicPolyline.StrokeColor = Color.FromArgb(0x80, 0xFF, 0x00, 0x00);
                    dynamicPolyline.StrokeThickness = 5;

                    dynamicPolyline.Path = new GeoCoordinateCollection() { 
                            map1.ConvertViewportPointToGeoCoordinate(e.GetPosition(map1))
                        };

                    map1.MapElements.Add(dynamicPolyline);
                }
                else // just add points to polyline here
                {
                    dynamicPolyline.Path.Add(map1.ConvertViewportPointToGeoCoordinate(e.GetPosition(map1)));
                }
            }
            addPoint = false;
            markerSelected = false;
        }
Exemplo n.º 12
0
        public Favorites()
        {
            InitializeComponent();
            LoadWatcher();
            map1.LogoVisibility = Visibility.Collapsed;
            map1.CopyrightVisibility = Visibility.Collapsed;
            map1.Mode = new AerialMode();
            map1.ZoomLevel = 5;
            map1.ZoomBarVisibility = System.Windows.Visibility.Visible;

            var settings = IsolatedStorageSettings.ApplicationSettings;
            if (settings.Contains("favorites"))
            {
                var location = settings["favorites"].ToString();
                latitude = double.Parse(location.Substring(0, location.IndexOf(",") - 1));
                longtitude =  double.Parse(location.Substring(location.IndexOf(",") + 1));
                var locationsList = new LocationCollection();
                //locationsList.Add(new GeoCoordinate(56.5845698,40.5489514));
                //locationsList.Add(new GeoCoordinate(60.4885213, 80.785426));
                locationsList.Add(new GeoCoordinate(latitude,longtitude));
                locationsList.Add(new GeoCoordinate(latitude+0.85412, longtitude+0.12564));
                MapPolyline polyline = new MapPolyline();
                polyline.Stroke = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Black);
                polyline.StrokeThickness = 5;
                polyline.Opacity = 0.8;
                polyline.Locations = locationsList;

                //Pushpin pin = new Pushpin();

                //MessageBox.Show(location.Substring(0, location.IndexOf(",") - 1) + " \n  " + location.Substring(location.IndexOf(",") + 1));
                ////---set the location for the pushpin---
                //pin.Location = new GeoCoordinate(double.Parse(location.Substring(0, location.IndexOf(",") - 1)), double.Parse(location.Substring(location.IndexOf(",") + 1)));
                //pin.Name = "tmp";

                ////---add the pushpin to the map---

                //pin.Content = new Ellipse()
                //{
                //    //Fill = image,

                //    StrokeThickness = 10,
                //    Height = 100,
                //    Width = 100
                //};
                //pin.MouseLeftButtonUp += new MouseButtonEventHandler(Pushpin_MouseLeftButtonUp);

                //---add the pushpin to the map---
                map1.Children.Add(polyline);

                MessageBox.Show(location.ToString());
            }

            // settings["myemail"] = "*****@*****.**";
        }
Exemplo n.º 13
0
    private void InitializePolyLineOnMap()
    {
      _polyline = new MapPolyline
      {
        Path = new GeoCoordinateCollection(),
        StrokeColor = Colors.Red,
        StrokeThickness = 3
      };

      Map.MapElements.Add(_polyline);
    }
Exemplo n.º 14
0
        private void BuildPoints(MapPolyline polyline)
        {
            for (int i = 0; i < polyline.Points.Count; i++)
            {
                MapPinPoint pinPoint = new MapPinPoint();
                pinPoint.ImageSource = new BitmapImage(new Uri(@"/Resources/point_small.png", UriKind.RelativeOrAbsolute));
                MapLayer.SetLocation(pinPoint, polyline.Points[i]);
                this.pointLayer.Items.Add(pinPoint);
                this.AttachMouseEvents(pinPoint);

            }
        }
Exemplo n.º 15
0
        public NewActivityPage()
        {
            InitializeComponent();

            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += Timer_Tick;

            line = new MapPolyline();
            line.StrokeColor = Colors.Red;
            line.StrokeThickness = 5;
            map.MapElements.Add(line);

        }
Exemplo n.º 16
0
        public void drawPath()
        {
            MapPolyline _joggingPolyLine = new MapPolyline();
            _joggingPolyLine.Stroke = new SolidColorBrush(Colors.Blue);
            _joggingPolyLine.StrokeThickness = 15;
            _joggingPolyLine.Opacity = 0.7;

            _joggingPolyLine.Locations = new LocationCollection();
            for (int i=1; i<Globals.history.Count; i++)
                _joggingPolyLine.Locations.Add(Globals.history[i]);

            map1.Children.Add(_joggingPolyLine);
        }
Exemplo n.º 17
0
        public RouteDrawing()
        {
            InitializeComponent();

            List<GeoCoordinate> locations = new List<GeoCoordinate>();

            RouteServiceClient routeService = new RouteServiceClient("BasicHttpBinding_IRouteService");

            routeService.CalculateRouteCompleted += (sender, e) =>
            {
                var points = e.Result.Result.RoutePath.Points;
                var coordinates = points.Select(x => new GeoCoordinate(x.Latitude, x.Longitude));

                var routeColor = Colors.Blue;
                var routeBrush = new SolidColorBrush(routeColor);

                var routeLine = new MapPolyline()
                {
                    Locations = new LocationCollection(),
                    Stroke = routeBrush,
                    Opacity = 0.65,
                    StrokeThickness = 5.0,
                };

                foreach (var location in points)
                {
                    routeLine.Locations.Add(new GeoCoordinate(location.Latitude, location.Longitude));
                }

                RouteLayer.Children.Add(routeLine);
            };

            RouteBingMap.SetView(LocationRect.CreateLocationRect(locations));

            routeService.CalculateRouteAsync(new RouteRequest()
            {
                Credentials = new Credentials()
                {
                    ApplicationId = "Ak-j1fNexs-uNWG_YoP2WZlthezPoUWsRvSexDLTGfjQ1XqKgnfR1nqeC2YbZZSn"
                },
                Options = new RouteOptions()
                {
                    RoutePathType = RoutePathType.Points
                },
                Waypoints = new ObservableCollection<Waypoint>(
                    locations.Select(x => new Waypoint()
                    {
                        Location = x.Location
                    }))
            });
        }
Exemplo n.º 18
0
        private MapShapeLayer CreateMapShapeLayer(Location startLocation, Location endLocation)
        {
            MapShapeLayer shapeLayer = new MapShapeLayer();
            MapPolyline polyline = new MapPolyline();

            polyline.Locations = new LocationCollection { startLocation, endLocation };
            polyline.Color = Color.FromArgb(255,255,120,56);
            polyline.Width = 10;

            shapeLayer.Shapes.Add(polyline);
            mainMap.ShapeLayers.Add(shapeLayer);

            return shapeLayer;
        }
Exemplo n.º 19
0
        public void AddPathsToMap(Map map)
        {
            MapPolyline line;

            foreach (var path in this.Paths)
            {
                line = new MapPolyline();
                line.Stroke = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Blue);
                line.StrokeThickness = 5;
                line.Locations = path;

                map.Children.Add(line);
            }
        }
        public PrevRun()
        {
            InitializeComponent();
            Map.MapElements.Clear();
            _line = new MapPolyline();
            _line.StrokeColor = Colors.Blue;
            _line.StrokeThickness = 10;
            _line.StrokeDashed = true;
            Map.MapElements.Add(_line);
            sldZoomLevel.Value = Map.ZoomLevel = 16;
            sldZoomLevel.ValueChanged += sldZoomLevel_ValueChanged;
            AppName.Text = AppResources.YourRuns;

        }
Exemplo n.º 21
0
        public static MapPolyline DrawRoad(TravelData data)
        {
            MapPolyline polyline = new MapPolyline();
            Color color = new Color();
            color.A = 255;
            color.R = (byte)rng.Next(1, 254);
            color.G = (byte)rng.Next(1, 254);
            color.B = (byte)rng.Next(1, 254);

            polyline.Stroke = new System.Windows.Media.SolidColorBrush(color);
            polyline.StrokeThickness = 5;
            polyline.Opacity = 0.7;
            polyline.Locations = data.Locations;
            return polyline;
        }
        private void mapPolylineAddButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            double centerLatitude = myMap.Center.Position.Latitude;
            double centerLongitude = myMap.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 },
            });

            mapPolyline.StrokeColor = Colors.Black;
            mapPolyline.StrokeThickness = 3;
            mapPolyline.StrokeDashed = true;
            myMap.MapElements.Add(mapPolyline);
        }
Exemplo n.º 23
0
        private void BuildPolyline()
        {
            LocationCollection points = new LocationCollection();
            points.Add(new Location(40, -100));
            points.Add(new Location(41, -101));
            points.Add(new Location(40, -102));
            points.Add(new Location(43, -103));
            points.Add(new Location(45, -97));

            MapPolyline polyline = new MapPolyline();
            polyline.Points = points;

            this.polylineLayer.Items.Add(polyline);
            this.BuildPoints(polyline);
        }
Exemplo n.º 24
0
 /// <summary>
 /// Direction Route completed
 /// add cross points to polyline
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void routeQuery_QueryCompleted(object sender, QueryCompletedEventArgs<Route> e)
 {
     LocationCollection loCollect = new LocationCollection();
     for (int i = 0; i < e.Result.Geometry.Count; i++)
     {
         loCollect.Add(e.Result.Geometry[i]);
     }
     MapPolyline routeline = new MapPolyline()
     {
         StrokeThickness=8,
         Locations=loCollect,
         Stroke=new SolidColorBrush(Colors.Red)
     };
     OnRouteChanged("RouteChanged", routeline);
 }
Exemplo n.º 25
0
        public MainPage()
        {
            InitializeComponent();

              // create a line which illustrates the run
              _line = new MapPolyline();
              _line.StrokeColor = Colors.Red;
              _line.StrokeThickness = 5;
              Map.MapElements.Add(_line);

              _watcher.PositionChanged += Watcher_PositionChanged;

              _timer.Interval = TimeSpan.FromSeconds(1);
              _timer.Tick += Timer_Tick;
        }
Exemplo n.º 26
0
        /*==========================================================*/    

        public Page2()
        {
            //Initialize the phone app, prompt the map to show and set the zoom level
            InitializeComponent();
            this.mapWithMyLocation.ZoomLevel = 13;
            firstPoint = true;
            ShowMyLocationOnTheMap();
            geolocator = new Geolocator();

            // create a line which illustrates the run
            pathLine = new MapPolyline();
            pathLine.StrokeColor = Colors.Red;
            pathLine.StrokeThickness = 5;
            mapWithMyLocation.MapElements.Add(pathLine);
        }
Exemplo n.º 27
0
 private void routeProvider_RoutingCompleted(object sender, RoutingCompletedEventArgs e)
 {
     RouteResponse response = e.Response as RouteResponse;
     if (response != null)
     {
         if (response.Result.RoutePath != null)
         {
             MapPolyline route = new MapPolyline();
             route.Points = response.Result.RoutePath.Points;
             route.Stroke = new SolidColorBrush(Colors.Red);
             route.StrokeThickness = 3;
             this.informationLayer.Items.Add(route);
         }
     }
 }
Exemplo n.º 28
0
        internal void addPolyline(IMapPolyline polylineSource, Color color, double width)
        {
            // Does it already exist?
            if (polylines.ContainsKey(polylineSource))
                return;

            LocationCollection lc = new LocationCollection();
            foreach (Location loc in polylineSource.Locations)
                lc.Add(loc);

            // Add to the UI
            MapPolyline pl = new MapPolyline() { Locations = lc, Color = color, Width = width };
            polylinesLayer.Shapes.Add(pl);
            // And add to our location collection
            polylines.Add(polylineSource, pl);
        }
Exemplo n.º 29
0
    public MainPage()
    {
      InitializeComponent();
            Loaded += MainPage_Loaded; // fixes the map ID issue (when you implement a map, it requires an id no and token)

      // create a line which illustrates the run
      _line = new MapPolyline();
      _line.StrokeColor = Colors.Red;
      _line.StrokeThickness = 5;
      Map.MapElements.Add(_line);

      _watcher.PositionChanged += Watcher_PositionChanged;

      _timer.Interval = TimeSpan.FromSeconds(1);
      _timer.Tick += Timer_Tick;
    }
Exemplo n.º 30
0
        public static List <MapPolyline> ReadPolylineData(string stringData, string LayerName)
        {
            List <MapPolyline> Polylines = new List <MapPolyline>();
            string             aLine     = null;
            int    polyIterator          = 0;
            var    polydata = new { AttributeData = "", XData = "", YData = "" }; // sample
            var    polyList = ListFactory.MakeList(polydata);
            string attrDat = null; string xDat = null; string yDat = null;


            StringReader strReader = new StringReader(stringData);

            while (true)
            {
                aLine = strReader.ReadLine();
                if (aLine != null)
                {
                    polyIterator++;
                    polyIterator = polyIterator > 3 ? 1 : polyIterator;
                    switch (polyIterator)
                    {
                    case 1:
                        attrDat = aLine;
                        break;

                    case 2:
                        xDat = aLine;
                        break;

                    case 3:
                        yDat = aLine;
                        polyList.Add(new { AttributeData = attrDat, XData = xDat, YData = yDat });
                        attrDat = null; xDat = null; yDat = null;
                        break;
                    }
                }
                else
                {
                    //process all the data
                    if (polyList.Count > 1)
                    {
                        foreach (var polyDatElem in polyList)
                        {
                            MapPolyline polyline = new MapPolyline();
                            polyline.Locations = new LocationCollection();

                            string[] attVals = polyDatElem.AttributeData.Split(','); // not used for now, use later for lineweight an annotation
                            string[] xVals   = polyDatElem.XData.Split(',');
                            string[] yVals   = polyDatElem.YData.Split(',');
                            if (xVals.Length == yVals.Length)
                            {
                                for (int i = 0; i < xVals.Length; i++)
                                {
                                    double x;
                                    double y;
                                    if (Double.TryParse(xVals[i], out x) && Double.TryParse(yVals[i], out y)) // if done, then is a number
                                    {
                                        Location thisLoc = new Location(x, y);
                                        polyline.Locations.Add(thisLoc);
                                    }
                                }
                                Polylines.Add(polyline);
                            }
                            else
                            {
                                throw new Exception("Number of X coordinates and Y coordinates in data does not match");
                            }
                        }
                    }
                    break;
                }
            }
            return(Polylines);
        }
Exemplo n.º 31
0
 /// <summary>
 /// Converts a MapPolyline into a LineString object.
 /// </summary>
 /// <param name="polyline">A Bing Maps MapPolyline object</param>
 /// <returns>A LineString representation of the MapPolyline object</returns>
 public static LineString ToGeometry(this MapPolyline polyline)
 {
     return(new LineString(polyline.Locations.ToGeometry()));
 }
Exemplo n.º 32
0
        /// <summary>
        /// Calculates and adds the route to the map
        /// </summary>
        /// <param name="route">The route to add</param>
        private async void AddRoute(TKRoute route)
        {
            if (route == null)
            {
                return;
            }

            _tempRouteList.Add(route);

            route.PropertyChanged += OnRoutePropertyChanged;

            MapRouteFinderResult routeData;
            string errorMessage = null;

            switch (route.TravelMode)
            {
            case TKRouteTravelMode.Walking:
                routeData = await MapRouteFinder.GetWalkingRouteAsync(
                    route.Source.ToLocationCoordinate(), route.Destination.ToLocationCoordinate());

                break;

            default:
                routeData = await MapRouteFinder.GetDrivingRouteAsync(
                    route.Source.ToLocationCoordinate(), route.Destination.ToLocationCoordinate(),
                    MapRouteOptimization.Time, MapRouteRestrictions.None);

                break;
            }

            if (FormsMap == null || Map == null || !_tempRouteList.Contains(route))
            {
                return;
            }

            if (routeData != null && routeData.Route != null)
            {
                if (routeData.Status == MapRouteFinderStatus.Success)
                {
                    var r = routeData.Route;
                    if (r != null && r.Path.Positions != null && r.Path.Positions.Any())
                    {
                        SetRouteData(route, r);

                        var polyline = new MapPolyline();

                        if (route.Color != Color.Default)
                        {
                            polyline.StrokeColor = route.Color.ToUWPColor();
                        }
                        if (route.LineWidth > 0)
                        {
                            polyline.StrokeThickness = route.LineWidth;
                        }

                        if (r.Path != null)
                        {
                            polyline.Path = new Geopath(r.Path.Positions.Select(i => new BasicGeoposition
                            {
                                Latitude  = i.Latitude,
                                Longitude = i.Longitude
                            }));
                        }

                        Map.MapElements.Add(polyline);
                        _routes.Add(route, polyline);

                        MapFunctions.RaiseRouteCalculationFinished(route);
                    }
                    else
                    {
                        errorMessage = "Unexpected result";
                    }
                }
                else
                {
                    errorMessage = routeData.Status.ToString();
                }
            }
            else
            {
                errorMessage = "Could not connect to api";
            }
            if (!string.IsNullOrEmpty(errorMessage))
            {
                var routeCalculationError = new TKRouteCalculationError(route, errorMessage);

                MapFunctions.RaiseRouteCalculationFailed(routeCalculationError);
            }
        }
Exemplo n.º 33
0
        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();
            }
        }
        // creates a route between two points
        private async Task <Boolean> getRoute(RouteRequest routeRequest)
        {
            // result from Route Request is contained in BingMapsRESTToolkit.Route
            var routeResult = await getBingRESTResponseRequest <BingMapsRESTToolkit.Route>(routeRequest);

            if (routeResult != null)
            {
                // the route path contains the coordinates to construct a route on the map
                if (routeResult.RoutePath != null && routeResult.RoutePath.Line != null && routeResult.RoutePath.Line.Coordinates != null)
                {
                    double[][] routePath = routeResult.RoutePath.Line.Coordinates;

                    LocationCollection locs = new LocationCollection();

                    for (int i = 0; i < routePath.Length; i++)
                    {
                        if (routePath[i].Length >= 2)
                        {
                            locs.Add(new Microsoft.Maps.MapControl.WPF.Location(routePath[i][0], routePath[i][1]));
                        }
                    }
                    Dispatcher.Invoke(() =>
                    {
                        MapPolyline routeLine = new MapPolyline()
                        {
                            Locations       = locs,
                            Stroke          = new SolidColorBrush(StaticVariables.routePathColor),
                            StrokeThickness = 5
                        };
                        // adding the route to the map on UI Thread

                        myMap.Children.Add(routeLine);
                        myMap.SetView(locs, new Thickness(5), 0);
                    });
                    return(true);
                }
                else
                {
                    if (RouteParameters.INSTANCE.isAddressAvailable())
                    {
                        setSystemWarningMessagesToSpeechLabel(string.Format(SystemMessages.NOROUTE_MESSAGE, RouteParameters.INSTANCE.fromLocation, RouteParameters.INSTANCE.toLocation));
                    }
                    else
                    {
                        setSystemWarningMessagesToSpeechLabel(string.Format(SystemMessages.NOROUTE_MESSAGE, RouteParameters.INSTANCE.fromCLocation.Latitude + ", " + RouteParameters.INSTANCE.fromCLocation.Longitude, RouteParameters.INSTANCE.toCLocation.Latitude + ", " + RouteParameters.INSTANCE.toCLocation.Longitude));
                    }
                    return(false);
                }
            }
            else
            {
                if (RouteParameters.INSTANCE.isAddressAvailable())
                {
                    setSystemWarningMessagesToSpeechLabel(string.Format(SystemMessages.NOROUTE_MESSAGE, RouteParameters.INSTANCE.fromLocation, RouteParameters.INSTANCE.toLocation));
                }
                else
                {
                    setSystemWarningMessagesToSpeechLabel(string.Format(SystemMessages.NOROUTE_MESSAGE, RouteParameters.INSTANCE.fromCLocation.Latitude + ", " + RouteParameters.INSTANCE.fromCLocation.Longitude, RouteParameters.INSTANCE.toCLocation.Latitude + ", " + RouteParameters.INSTANCE.toCLocation.Longitude));
                }

                return(false);
            }
        }
Exemplo n.º 35
0
        private void MapButton_Click(object sender, EventArgs e)
        {
            // Remove all pins on the map
            mapTest.userControl11.map.Children.Clear();

            //List<double> userLocation = queryEngine.GetUserLocation(currUserId);
            List <string> selectedBusinesses = new List <string> ();

            Microsoft.Maps.MapControl.WPF.Location userCoord = null;
            Microsoft.Maps.MapControl.WPF.Location busCoord  = null;

            // Resets the map each time the button is clicked, even if it is already open
            if (this.mapTest.Visible)
            {
                mapTest.Close();
            }

            if (currUserId != string.Empty)
            {
                //MessageBox.Show("Log in to a user to view business on map");
                //return;
                List <double> userLocation = queryEngine.GetUserLocation(currUserId);

                // Only set the map view to the user's position if the user has both a lat and long value entered
                if (userLocation.Count == 2)
                {
                    userCoord = new Microsoft.Maps.MapControl.WPF.Location(userLocation[0], userLocation[1]);
                    Pushpin pin = new Pushpin();
                    pin.Background = new SolidColorBrush(Color.FromArgb(200, 0, 100, 100));
                    pin.Location   = userCoord;
                    mapTest.userControl11.map.Children.Add(pin);
                }
            }

            // Add pins for all of the businesses in the grid
            // Instead of requerying the businesses, just pulling from the datagrid view the business names,
            // then I will query the locations for the businesses
            foreach (DataGridViewRow row in businessGrid.Rows)
            {
                selectedBusinesses.Add(row.Cells[9].Value.ToString());
            }

            // Need to protect against case where no businesses are present in the grid
            foreach (List <double> locations in queryEngine.GetBusinessLocations(selectedBusinesses))
            {
                busCoord = new Microsoft.Maps.MapControl.WPF.Location(locations[0], locations[1]);
                Pushpin pin = new Pushpin();
                pin.Location = busCoord;
                mapTest.userControl11.map.Children.Add(pin);

                mapTest.userControl11.map.SetView(busCoord, 11);
            }

            // Draw line between the user and most recently added business to make map more readable
            if (userCoord != null && busCoord != null)
            {
                MapPolyline polyline = new MapPolyline();
                polyline.Stroke          = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.DarkRed);
                polyline.StrokeThickness = 3;
                polyline.Opacity         = 0.5;
                polyline.Locations       = new LocationCollection()
                {
                    userCoord,
                    busCoord
                };

                mapTest.userControl11.map.Children.Add(polyline);
            }

            this.mapTest.Show();
        }
Exemplo n.º 36
0
        private static void ColoredMapLinesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            DigiTransitMap _this = d as DigiTransitMap;

            if (_this == null)
            {
                return;
            }

            var oldCollection = e.OldValue as INotifyCollectionChanged;
            var newCollection = e.NewValue as INotifyCollectionChanged;

            if (oldCollection != null)
            {
                oldCollection.CollectionChanged -= _this.OnColoredMapLinePointsCollectionChanged;
            }
            if (newCollection != null)
            {
                newCollection.CollectionChanged += _this.OnColoredMapLinePointsCollectionChanged;
            }

            IList <ColoredMapLine> newValue = e.NewValue as IList <ColoredMapLine>;

            if (newValue == null)
            {
                if (_this.DigiTransitMapControl.MapElements.OfType <MapPolyline>().Any())
                {
                    _this.SetMapLines(null);
                }
                return;
            }

            List <MapPolyline>      newPolylines         = new List <MapPolyline>();
            List <BasicGeoposition> currentLinePositions = new List <BasicGeoposition>();

            foreach (ColoredMapLine lineCollection in newValue)
            {
                for (int i = 0; i <= lineCollection.Count() - 2; i++)
                {
                    var startPoint = lineCollection[i];
                    var nextPoint  = lineCollection[i + 1];
                    currentLinePositions.Add(startPoint.Coordinates);

                    Color nextColor = nextPoint.LineColor;
                    if (nextPoint == lineCollection.Last() || startPoint.LineColor != nextColor)
                    {
                        MapPolyline polyline = new MapPolyline();
                        polyline.Path            = new Geopath(currentLinePositions);
                        polyline.StrokeColor     = Color.FromArgb(192, startPoint.LineColor.R, startPoint.LineColor.G, startPoint.LineColor.B);
                        polyline.StrokeDashed    = startPoint.IsLineDashed;
                        polyline.StrokeThickness = 6;
                        if (lineCollection.OptionalId != Guid.Empty)
                        {
                            MapElementExtensions.SetPoiId(polyline, lineCollection.OptionalId);
                        }
                        newPolylines.Add(polyline);

                        currentLinePositions = new List <BasicGeoposition>();
                    }
                }
            }

            _this.SetMapLines(newPolylines);
        }
Exemplo n.º 37
0
        void routeService_CalculateRouteCompleted(object sender, CalculateRouteCompletedEventArgs e)
        {
            RouteResponse response = e.Result;

            if ((response.ResponseSummary.StatusCode == Panda.Phone.Publisher.RouteServiceReference.ResponseStatusCode.Success) && (response.Result.Legs.Count != 0))
            {
                Color color = Colors.Blue;
                // SolidColorBrush brush = new SolidColorBrush(color);
                SolidColorBrush brush = new SolidColorBrush(new Color()
                {
                    R = 6, G = 128, B = 67, A = 255
                });
                MapPolyline line = new MapPolyline();
                line.Locations       = new LocationCollection();
                line.Opacity         = 0.6;
                line.StrokeThickness = 10;
                line.Stroke          = brush;
                //DispatcherTimer timer = new DispatcherTimer();
                //timer.Interval = TimeSpan.FromMilliseconds(200);
                //timer.Tick += new EventHandler(timer_Tick);
                //timer.Start();
                MapLayer layer = new MapLayer();
                layer.Children.Add(line);
                map.Children.Add(layer);
                foreach (Location l in response.Result.RoutePath.Points)
                {
                    line.Locations.Add(l);
                }

                //foreach (GeocodeResult r in Georesults)
                //{
                //    Ellipse ellipse = new Ellipse();
                //    ellipse.Height = 10;
                //    ellipse.Width = 10;
                //    ellipse.Fill = new SolidColorBrush(Colors.Red);
                //    Location location = new Location()
                //    {
                //        Latitude = r.Locations[0].Latitude,
                //        Longitude = r.Locations[0].Longitude
                //    };
                //    layer.AddChild(ellipse, location);
                //}

                foreach (UserModel user in list_User_Choosed)
                {
                    Ellipse ellipse = new Ellipse();
                    ellipse.Height = 10;
                    ellipse.Width  = 10;
                    ellipse.Fill   = new SolidColorBrush(new Color()
                    {
                        A = 0
                    });
                    Location location = new Location()
                    {
                        Latitude  = user.Latitude,
                        Longitude = user.Longitude
                    };
                    layer.AddChild(ellipse, location);
                }
                //GeoCoordinate p = new GeoCoordinate(Georesults[1].Locations[0].Latitude, Georesults[1].Locations[0].Longitude);
                // var routeModel = new RouteModel(e.Result.Result.RoutePath.Points);
                //  LocationRect rect = LocationRect.CreateLocationRect(routeModel.Locations);

                // Set the map view using the rectangle which bounds the rendered route.
                // map.SetView(p, 8);
            }
        }
Exemplo n.º 38
0
        private async void getStopsInfo()
        {
            string errorMessage = null;

            try
            {
                double minLat = 90;
                double maxLat = -90;
                double minLng = 180;
                double maxLng = -180;

                string webresponse = await Network.StopsByService(Service.ServiceId);

                List <Stop> rootObject = JsonConvert.DeserializeObject <List <Stop> >(webresponse);

                foreach (Stop s in rootObject)
                {
                    StopsList.Add(s);
                    Lines.Add(new BasicGeoposition()
                    {
                        Latitude  = s.Location.Lat,
                        Longitude = s.Location.Lng
                    });

                    if (s.Location.Lat > maxLat)
                    {
                        maxLat = s.Location.Lat;
                    }
                    if (s.Location.Lat < minLat)
                    {
                        minLat = s.Location.Lat;
                    }
                    if (s.Location.Lng > maxLng)
                    {
                        maxLng = s.Location.Lng;
                    }
                    if (s.Location.Lng < minLng)
                    {
                        minLng = s.Location.Lng;
                    }
                }

                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    MapPolyline CourseLines     = new MapPolyline();
                    CourseLines.Path            = new Geopath(Lines);
                    CourseLines.StrokeColor     = Colors.DodgerBlue;
                    CourseLines.StrokeThickness = 5;
                    MapControl.MapElements.Add(CourseLines);
                });

                BasicGeoposition nw = new BasicGeoposition()
                {
                    Latitude  = maxLat,
                    Longitude = minLng
                };
                BasicGeoposition se = new BasicGeoposition()
                {
                    Latitude  = minLat,
                    Longitude = maxLng
                };

                GeoboundingBox box = new GeoboundingBox(nw, se);

                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                {
                    await MapControl.TrySetViewBoundsAsync(box, new Thickness(2, 2, 2, 2), MapAnimationKind.Bow);
                });
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
            }

            if (errorMessage != null)
            {
                MessageDialog msg = new MessageDialog("Houve algum problema durante a requisição ao servidor. Por favor, verifique se o aparelho está conectado à internet e tente novamente.", "Você está conectado à internet?");
                await msg.ShowAsync();
            }
        }
Exemplo n.º 39
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //打开图片
            OpenFileDialog openfiledialog = new OpenFileDialog
            {
                Filter = "图像文件|*.jpg;*.png;*.jpeg;*.bmp;*.gif|所有文件|*.*"
            };

            if ((bool)openfiledialog.ShowDialog())
            {
                photo.Source = new BitmapImage(new Uri(openfiledialog.FileName));
            }

            string filename = openfiledialog.FileName;

            exifmessage.Text = filename;
            StringBuilder sb          = new StringBuilder();
            var           directories = ImageMetadataReader.ReadMetadata(filename);
            StringBuilder latitude    = new StringBuilder();
            StringBuilder longgitude  = new StringBuilder();

            //经度输出
            foreach (var directory in directories)
            {
                foreach (var tag in directory.Tags)
                {
                    if ($"{tag.Name}" == "GPS Latitude")
                    {
                        sb.AppendLine($"[{directory.Name}] {tag.Name} = {tag.Description}");
                        latitude.AppendLine($"[{directory.Name}] {tag.Name} = {tag.Description}");
                        exifmessage.Text = sb.ToString();
                    }
                }
            }
            //纬度输出
            foreach (var directory in directories)
            {
                foreach (var tag in directory.Tags)
                {
                    if ($"{tag.Name}" == "GPS Longitude")
                    {
                        sb.AppendLine($"[{directory.Name}] {tag.Name} = {tag.Description}");
                        longgitude.AppendLine($"[{directory.Name}] {tag.Name} = {tag.Description}");
                        exifmessage.Text = sb.ToString();
                    }
                }
            }
            //时间输出
            foreach (var directory in directories)
            {
                foreach (var tag in directory.Tags)
                {
                    if ($"{tag.Name}" == "Date/Time")
                    {
                        sb.AppendLine($"[{directory.Name}] {tag.Name} = {tag.Description}");
                        longgitude.AppendLine($"[{directory.Name}] {tag.Name} = {tag.Description}");
                        exifmessage.Text = sb.ToString();
                    }
                }
            }
            //转换经纬度
            double      newlatitude   = 0;
            double      newlonggitude = 0;
            GCJ02_WGS84 gCJ02_WGS84   = new GCJ02_WGS84();
            ConvertBing convertBing   = new ConvertBing();
            GPSConvert  gPSConvert    = new GPSConvert();

            newlatitude           = gPSConvert.getlatitude(latitude);
            newlonggitude         = gPSConvert.getlonggitude(longgitude);
            convertBing           = GCJ02_WGS84.wgs84_To_Gcj02(newlatitude, newlonggitude);
            latitudemessage.Text  = "经度:" + convertBing.getLatitude().ToString("#0.000");
            longitudemessage.Text = "纬度:" + convertBing.getLongitude().ToString("#0.000");

            //生成图钉
            Pushpin  pushpin  = new Pushpin();
            MapLayer mapLayer = new MapLayer();

            pushpin.MouseRightButtonDown += RemovePushpin;
            pushpin.Location              = new Location(convertBing.getLatitude(), convertBing.getLongitude());
            this.mapLayer.AddChild(pushpin, pushpin.Location);
            bingMap.Center    = new Location(convertBing.getLatitude(), convertBing.getLongitude());
            bingMap.ZoomLevel = 14;

            //图钉标注
            var image = new Image {
                Width = 200, Height = 200, Margin = new Thickness(8)
            };

            image.Source = new BitmapImage(new Uri(openfiledialog.FileName));
            ToolTipService.SetToolTip(pushpin, image);

            //生成轨迹
            if (flag > 0)
            {
                MapPolyline polyline      = new MapPolyline();
                Location    startlocation = new Location(latTag, longTag);
                Location    endlocation   = new Location(convertBing.getLatitude(), convertBing.getLongitude());
                polyline.Locations = new LocationCollection
                {
                    new Location(startlocation),
                    new Location(endlocation)
                };

                polyline.Stroke          = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Red);
                polyline.StrokeThickness = 5;
                polyline.Opacity         = 1;//不透明度
                this.mapLayer.Children.Add(polyline);
                polyline.MouseRightButtonDown += RemovePolyline;
            }
            latTag  = convertBing.getLatitude();
            longTag = convertBing.getLongitude();
            flag++;
        }
Exemplo n.º 40
0
        private void RemovePolyline(object sender, MouseButtonEventArgs e)
        {
            MapPolyline mapPolyline = (MapPolyline)sender;

            this.mapLayer.Children.Remove(mapPolyline);
        }
Exemplo n.º 41
0
        private async void SetRoute(Location startLocation, Location endLocation)
        {
            ClearMap();
            //Create the Request URL for the routing service
            const string request =
                @"http://dev.virtualearth.net/REST/V1/Routes/Driving?o=json&wp.0={0},{1}&wp.1={2},{3}&rpo=Points&key={4}";

            var routeRequest =
                new Uri(string.Format(request, startLocation.Latitude, startLocation.Longitude, endLocation.Latitude,
                                      endLocation.Longitude, _mapTrucks.Credentials));

            //Make a request and get the response
            var r = await GetResponse(routeRequest);

            if (r != null &&
                r.ResourceSets != null &&
                r.ResourceSets.Length > 0 &&
                r.ResourceSets[0].Resources != null &&
                r.ResourceSets[0].Resources.Length > 0)
            {
                var route = r.ResourceSets[0].Resources[0] as Route;
                if (route == null)
                {
                    return;
                }

                //Get the route line data
                var routePath = route.RoutePath.Line.Coordinates;
                var locations = new LocationCollection();

                foreach (var t in routePath)
                {
                    if (t.Length >= 2)
                    {
                        locations.Add(new Location(t[0], t[1]));
                    }
                }

                //Create a MapPolyline of the route and add it to the map
                var routeLine = new MapPolyline
                {
                    Color     = Colors.Blue,
                    Locations = locations,
                    Width     = 5
                };

                _routeLayer.Shapes.Add(routeLine);

                //Add start and end pushpins
                var start = new Pushpin
                {
                    Text       = "S",
                    Background = new SolidColorBrush(Colors.Green)
                };

                _mapTrucks.Children.Add(start);
                MapLayer.SetPosition(start,
                                     new Location(route.RouteLegs[0].ActualStart.Coordinates[0],
                                                  route.RouteLegs[0].ActualStart.Coordinates[1]));

                var end = new Pushpin
                {
                    Text       = "E",
                    Background = new SolidColorBrush(Colors.Red)
                };

                _mapTrucks.Children.Add(end);
                MapLayer.SetPosition(end,
                                     new Location(route.RouteLegs[0].ActualEnd.Coordinates[0],
                                                  route.RouteLegs[0].ActualEnd.Coordinates[1]));

                //Set the map view for the locations
                var locationRect = new LocationRect(locations);
                locationRect.Width  += 0.5;
                locationRect.Height += 0.5;
                _mapTrucks.SetView(locationRect);
            }
        }
Exemplo n.º 42
0
        private void Form1_Load(object sender, System.EventArgs e)
        {
            #region #MapDotExample
            ItemStorage.Items.Add(new MapDot()
            {
                Location = new GeoPoint(-10, 10), Size = 18, Stroke = Color.Blue
            });
            #endregion #MapDotExample

            #region #MapEllipseExample
            ItemStorage.Items.Add(new MapEllipse()
            {
                Location = new GeoPoint(40, 40), Height = 300, Width = 600
            });
            #endregion #MapEllipseExample

            #region #MapLineExample
            ItemStorage.Items.Add(new MapLine {
                Point1 = new GeoPoint(-30, 20), Point2 = new GeoPoint(-35, 25), Stroke = Color.Red, StrokeWidth = 4
            });
            #endregion #MapLineExample

            #region #MapCalloutExample
            ItemStorage.Items.Add(new MapCallout()
            {
                Location = new GeoPoint(10, 10), Text = "This is a MapCallout object"
            });
            #endregion #MapCalloutExample

            #region #MapPathExample
            var path    = new MapPath();
            var segment = new MapPathSegment();
            segment.Points.AddRange(new GeoPoint[] {
                new GeoPoint(20, 20),
                new GeoPoint(20, 30),
                new GeoPoint(30, 30)
            });
            path.Segments.Add(segment);
            segment = new MapPathSegment();
            segment.Points.AddRange(new GeoPoint[] {
                new GeoPoint(30, 32),
                new GeoPoint(20, 32),
                new GeoPoint(20, 42)
            });
            path.Segments.Add(segment);
            ItemStorage.Items.Add(path);
            #endregion #MapPathExample

            #region #MapPolygonExample
            var polygon = new MapPolygon();
            polygon.Points.AddRange(new GeoPoint[] {
                new GeoPoint(70, 80),
                new GeoPoint(75, 90),
                new GeoPoint(75, 130)
            });
            ItemStorage.Items.Add(polygon);
            #endregion #MapPolygonExample

            #region #MapPolylineExample
            var polyline = new MapPolyline()
            {
                StrokeWidth = 4, Stroke = Color.Yellow
            };
            polyline.Points.AddRange(new GeoPoint[] {
                new GeoPoint(-29, 130),
                new GeoPoint(-40, 140),
                new GeoPoint(-20, 150)
            });
            ItemStorage.Items.Add(polyline);
            #endregion #MapPolylineExample

            #region #MapPushpinExample
            ItemStorage.Items.Add(new MapPushpin()
            {
                Location = new GeoPoint(70, -100), Text = "1"
            });
            #endregion #MapPushpinExample

            #region #MapRectangleExample
            ItemStorage.Items.Add(new MapRectangle()
            {
                Location = new GeoPoint(-70, -100), Width = 500, Height = 750
            });
            #endregion #MapRectangleExample

            #region #MapCustomElementExample
            var customElement = new MapCustomElement()
            {
                Location = new GeoPoint(50, 50), Text = "This is a MapCustomElement object"
            };
            var image = new Bitmap(imageFilePath);
            customElement.Image = new Bitmap(image, new Size(40, 40));
            ItemStorage.Items.Add(customElement);
            #endregion #MapCustomElementExample

            #region #MapBubbleExample
            ItemStorage.Items.Add(new MapBubble()
            {
                Location = new GeoPoint(30, 20), Value = 400, Argument = "A", Size = 100
            });
            #endregion #MapBubbleExample

            #region #MapPieExample
            var pie = new MapPie()
            {
                Location = new GeoPoint(-20, -30), Size = 100
            };
            pie.Segments.AddRange(new PieSegment[] {
                new PieSegment()
                {
                    Argument = "A", Value = 2
                },
                new PieSegment()
                {
                    Argument = "B", Value = 3
                },
                new PieSegment()
                {
                    Argument = "C", Value = 4
                }
            });
            ItemStorage.Items.Add(pie);
            #endregion #MapPieExample
        }
Exemplo n.º 43
0
        void rsc_GetRoutingCompleted(object sender, GetRoutingCompletedEventArgs e)
        {
            carloc.Clear();
            cari = 0;
            MapLayer layer = (MapLayer)this.ctlMap.FindName("routing");

            layer.Children.Clear();
            var builder = new StringBuilder();

            if (e.Error == null)
            {
                Color color = Colors.Blue;
                for (int i = 0; i < e.Result.Count; i++)
                {
                    string[] strArray = e.Result[i].Split(new char[] { ';' });


                    builder.Length = 0;
                    int index = 2;
                    while (index < (strArray.Length - 1))
                    {
                        builder.Append(strArray[index] + ": ");
                        index++;
                    }
                    string[] strArray2      = strArray[strArray.Length - 1].Split(new char[] { ',' });
                    string[] strArrayPoints = strArray[strArray.Length - 2].Split(new char[] { ',' });
                    if ((strArray2.Length == 1) && (strArray2[0].Length > 1))
                    {
                        //Ellipse dependencyObject = new Ellipse();
                        //dependencyObject.Width=10.0;
                        //dependencyObject.Height=(10.0);
                        //dependencyObject.Fill=(new SolidColorBrush(color));
                        //dependencyObject.Opacity=(0.65);
                        //Location location = new Location(double.Parse(strArray2[0].Split(new char[] { ' ' })[0]), double.Parse(strArray2[0].Split(new char[] { ' ' })[1]));
                        //MapLayer.SetPosition(dependencyObject, location);
                        //ToolTipService.SetToolTip(dependencyObject, builder.ToString());
                        //layer.Children.Add(dependencyObject);
                    }
                    else
                    {
                        LocationCollection locations;
                        Location           location2;
                        Location           locPoint;
                        if (strArray2[0].Equals(strArray2[strArray2.Length - 1]))
                        {
                            var polygon = new MapPolygon
                            {
                                Stroke          = new SolidColorBrush(color),
                                StrokeThickness = 2.0,
                                Fill            = new SolidColorBrush(color),
                                Opacity         = 0.75
                            };
                            locations = new LocationCollection();
                            index     = 0;
                            while (index < strArray2.Length)
                            {
                                if (strArray2[index].IndexOf(" ") != -1)
                                {
                                    location2 = new Location(double.Parse(strArray2[index].Split(new char[] { ' ' })[0]), double.Parse(strArray2[index].Split(new char[] { ' ' })[1]));
                                    locations.Add(location2);
                                }
                                index++;
                            }
                            polygon.Locations = locations;
                            ToolTipService.SetToolTip(polygon, builder.ToString());
                            layer.Children.Add(polygon);
                        }
                        else
                        {
                            var polyline = new MapPolyline {
                                Stroke = new SolidColorBrush(color), StrokeThickness = 6.0
                            };
                            var doubles = new DoubleCollection {
                                3.0, 3.0
                            };
                            polyline.StrokeDashArray = doubles;
                            locations = new LocationCollection();

                            for (index = strArray2.Length - 1; index >= 0; index--)
                            {
                                location2 = new Location(double.Parse(strArray2[index].Split(new char[] { ' ' })[0]), double.Parse(strArray2[index].Split(new char[] { ' ' })[1]));

                                locations.Add(location2);
                                if (i == 0)
                                {
                                    carloc.Add(location2);
                                }
                            }



                            //添加坐标到小车轨迹
                            if (i > 0)
                            {
                                Location loc1 = new Location(double.Parse(strArrayPoints[0].Split(new char[] { ' ' })[0]), double.Parse(strArrayPoints[0].Split(new char[] { ' ' })[1]));
                                Location loc2 = new Location(double.Parse(strArrayPoints[strArrayPoints.Length - 1].Split(new char[] { ' ' })[0]), double.Parse(strArrayPoints[strArrayPoints.Length - 1].Split(new char[] { ' ' })[1]));
                                if (IsCloset(carloc.ElementAt(carloc.Count - 1), loc1, loc2))
                                {
                                    for (index = strArrayPoints.Length - 1; index >= 0; index--)
                                    {
                                        var tmoloc1 = new Location(double.Parse(strArrayPoints[index].Split(new char[] { ' ' })[0]), double.Parse(strArrayPoints[index].Split(new char[] { ' ' })[1]));

                                        carloc.Add(tmoloc1);
                                    }
                                }
                                else
                                {
                                    for (index = 0; index < strArrayPoints.Length - 1; index++)
                                    {
                                        var tmoloc = new Location(double.Parse(strArrayPoints[index].Split(new char[] { ' ' })[0]), double.Parse(strArrayPoints[index].Split(new char[] { ' ' })[1]));
                                        carloc.Add(tmoloc);
                                    }
                                }
                            }



                            polyline.Locations = locations;
                            ToolTipService.SetToolTip(polyline, builder.ToString());

                            layer.Children.Add(polyline);
                        }
                    }
                }
            }



            CustomPushpin otmpcp = GetCarByMSID("car", carml);

            for (int i = 0; i < carloc.Count; i++)
            {
                var item = carloc.ElementAt(i);
                if (item.Latitude == otmpcp.Location.Latitude && item.Longitude == otmpcp.Location.Longitude)
                {
                    for (int y = 0; y < i + 1; y++)
                    {
                        if (carloc.Count > y + 1)
                        {
                            carloc.RemoveAt(y);
                        }
                    }
                }
            }
            carloc.RemoveAt(0);
            isgetloc = false;

            timer.Begin();
            //RouteLoadingPanel.Stop();
        }
Exemplo n.º 44
0
        /// <summary>
        /// Return result of XAML Service call
        ///     Render MapLayer using XamlReader.Load
        ///     Add styling
        ///     Add Mouse events
        ///     Add attributes as ToolTip
        /// </summary>
        private void XAMLService_GetSQLDataXAMLCompleted(object sender, GetSQLDataXAMLCompletedEventArgs e)
        {
            string layer = e.UserState.ToString();

            if (e.Error == null)
            {
                int resultCnt = e.Result.OutputFields.Count;
                if (resultCnt > 0)
                {
                    if (resultCnt < recordLimit)
                    {
                        totalFeatures += e.Result.OutputFields.Count;
                        totalByteSize += e.Result.XAML.Length;
                        queryTime      = e.Result.QueryTime;
                        totalPoints   += e.Result.totalPoints;
                        renderStart    = DateTime.Now;
                        MapLayer currentLayer = (MapLayer)MainMap.FindName(layer);
                        MapLayer newLayer     = (MapLayer)XamlReader.Load(e.Result.XAML);
                        currentLayer.Children.Add(newLayer);

                        foreach (XAMLServiceReference.XAMLFields shp in e.Result.OutputFields)
                        {
                            UIElement el = (UIElement)newLayer.FindName(shp.ID);
                            if (el != null)
                            {
                                el.MouseEnter += polygon_MouseEnter;
                                el.MouseLeave += polygon_MouseLeave;

                                StringBuilder label = new StringBuilder("ID = " + shp.ID + "\n");
                                foreach (KeyValuePair <string, string> field in shp.Fields)
                                {
                                    label.Append(field.Key + ":" + field.Value + "\n");
                                }

                                ToolTip tt = AddToolTip(label.ToString());
                                ToolTipService.SetToolTip(el, tt);

                                if (el.GetType().Equals(typeof(Pushpin)))
                                {
                                    Pushpin p = (Pushpin)el;
                                    p.Background = new SolidColorBrush(MiscFunctions.ColorFromInt(LayerStyle[layer].fill));
                                    p.Foreground = new SolidColorBrush(Colors.Black);
                                    p.FontSize   = 8;
                                }

                                if (el.GetType().Equals(typeof(MapLayer)))
                                {
                                    MapLayer p = (MapLayer)el;
                                    foreach (MapPolygon mp in p.Children)
                                    {
                                        mp.Fill    = new SolidColorBrush(MiscFunctions.ColorFromInt(LayerStyle[layer].fill));
                                        mp.Stroke  = new SolidColorBrush(MiscFunctions.ColorFromInt(LayerStyle[layer].stroke));
                                        mp.Opacity = LayerStyle[layer].opacity;
                                    }
                                }

                                if (el.GetType().Equals(typeof(MapPolyline)))
                                {
                                    MapPolyline p = (MapPolyline)el;
                                    p.Stroke           = new SolidColorBrush(MiscFunctions.ColorFromInt(LayerStyle[layer].stroke));
                                    p.StrokeThickness  = 2;
                                    p.StrokeMiterLimit = 0;
                                }
                                if (el.GetType().Equals(typeof(MapPolygon)))
                                {
                                    MapPolygon p = (MapPolygon)el;
                                    p.Stroke  = new SolidColorBrush(MiscFunctions.ColorFromInt(LayerStyle[layer].stroke));
                                    p.Fill    = new SolidColorBrush(MiscFunctions.ColorFromInt(LayerStyle[layer].fill));
                                    p.Opacity = LayerStyle[layer].opacity;
                                }
                            }
                        }
                        renderStop = DateTime.Now;
                    }
                    else
                    {
                        ShowMessage("Too many records for Vector display, " + resultCnt + ". Try a smaller area of interest.");
                    }
                }
            }
            else
            {
                ShowMessage("Error occurred while loading layer from database:" + e.Error.Message);
            }
            // if this is the last layer call cleanup loading and allow menu interaction
            if (--layerCnt == 0)
            {
                SidePanelBorder.IsHitTestVisible = true;
                loaderStop();
            }
            //update metrics
            ((TextBlock)metrics.FindName("features")).Text = totalFeatures.ToString();
            ((TextBlock)metrics.FindName("points")).Text   = totalPoints.ToString();
            ((TextBlock)metrics.FindName("bytesize")).Text = totalByteSize.ToString();
        }
Exemplo n.º 45
0
        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);
        }
Exemplo n.º 46
0
        void StartDraw(Location location)
        {
            if (DwType == DrawType.DrawLine || DwType == DrawType.DrawCalLength)
            {
                if (!locationList.Any())
                {
                    line           = new MapPolyline();
                    line.Locations = new LocationCollection()
                    {
                        location
                    };
                    line.StrokeThickness = 2;
                    line.Opacity         = 1;
                    line.Stroke          = new SolidColorBrush(Color.FromArgb(200, 253, 128, 68));
                    line.StrokeLineJoin  = PenLineJoin.Round;
                    locationList.Add(location);
                    lyr.Children.Add(line);
                    currentLine.Add(line);

                    AddToMapLayer(CreatePanel(null, "起点"), location, PositionOrigin.TopLeft);
                }
                else
                {
                    locationList.Add(location);
                    if (DwType == DrawType.DrawCalLength)
                    {
                        var panel = CreatePanel(null, GetDistanceStringFromLocations(locationList));
                        AddToMapLayer(panel, location, PositionOrigin.TopLeft);
                    }

                    if (line.Locations.Count == locationList.Count)
                    {
                        line.Locations[line.Locations.Count - 1] = location;
                    }
                }

                AddToMapLayer(CreatePoint(), location, PositionOrigin.Center);
            }
            else if (DwType == DrawType.DrawPolygon || DwType == DrawType.DrawCalArea)
            {
                if (!locationList.Any())
                {
                    poly           = new MapPolygon();
                    poly.Locations = new LocationCollection()
                    {
                        location
                    };
                    poly.StrokeThickness = 2;
                    poly.Opacity         = 0.5;
                    poly.Stroke          = new SolidColorBrush(Colors.Red);
                    poly.Fill            = new SolidColorBrush(Color.FromArgb(200, 253, 128, 68));
                    poly.StrokeLineJoin  = PenLineJoin.Round;
                    locationList.Add(location);
                    lyr.Children.Add(poly);
                    currentLine.Add(poly);
                }
                else
                {
                    locationList.Add(location);
                    if (poly.Locations.Count == locationList.Count)
                    {
                        poly.Locations[poly.Locations.Count - 1] = location;
                    }
                }
                AddToMapLayer(CreatePoint(), location, PositionOrigin.Center);
            }
            else if (DwType == DrawType.DrawRect)
            {
                if (!locationList.Any())
                {
                    poly           = new MapPolygon();
                    poly.Locations = new LocationCollection()
                    {
                        location, location, location, location
                    };
                    poly.StrokeThickness = 2;
                    poly.Opacity         = 0.5;
                    poly.Stroke          = new SolidColorBrush(Colors.Red);
                    poly.Fill            = new SolidColorBrush(Color.FromArgb(200, 253, 128, 68));
                    poly.StrokeLineJoin  = PenLineJoin.Round;

                    locationList.Add(location);
                    lyr.Children.Add(poly);
                    currentLine.Add(poly);
                }
                else
                {
                    locationList.Add(location);

                    var del = CreateDeleteButton();
                    lyr.AddChild(del, location, new System.Windows.Point(-13, 6));
                    currentLine.Add(del);
                    dicLines.Add(_tag, currentLine);

                    if (EndDrawRect != null)
                    {
                        EndDrawRect(this, locationList, -1, _tag);
                    }
                    DwType = DrawType.None;
                }
            }
            else if (DwType == DrawType.DrawCustomPoint)
            {
                locationList.Add(location);

                UpdateMovePanel(null, "", location);
                AddToMapLayer(CreatePoint(), location, PositionOrigin.Center);
                var del = CreateDeleteButton();
                lyr.AddChild(del, location, new System.Windows.Point(-13, 6));
                currentLine.Add(del);
                dicLines.Add(_tag, currentLine);

                if (EndDrawCustomPoint != null)
                {
                    EndDrawCustomPoint(this, locationList, -1, _tag);
                }
                DwType = DrawType.None;
            }
        }
Exemplo n.º 47
0
        private void RedrawWaypoint()
        {
            List <BasicGeoposition> waypointPositions = new List <BasicGeoposition>();

            for (int i = 0; i < mission.waypoints.Count; ++i)
            {
                if (waypointLayer.MapElements.Count == i)
                {
                    MapIcon waypointIcon = new MapIcon()
                    {
                        Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/waypoint.png")),
                        NormalizedAnchorPoint = new Windows.Foundation.Point(0.5, 0.5),
                        ZIndex = 0,
                    };
                    waypointLayer.MapElements.Add(waypointIcon);
                }

                var geolocation = new BasicGeoposition()
                {
                    Latitude = mission.waypoints[i].location.latitude, Longitude = mission.waypoints[i].location.longitude
                };
                (waypointLayer.MapElements[i] as MapIcon).Location = new Geopoint(geolocation);
                waypointPositions.Add(geolocation);
            }

            if (waypointPositions.Count >= 2)
            {
                if (routeLayer.MapElements.Count == 0)
                {
                    var polyline = new MapPolyline
                    {
                        StrokeColor     = Windows.UI.Color.FromArgb(255, 0, 255, 0),
                        Path            = new Geopath(waypointPositions),
                        StrokeThickness = 2
                    };
                    routeLayer.MapElements.Add(polyline);
                }
                else
                {
                    var waypointPolyline = routeLayer.MapElements[0] as MapPolyline;
                    waypointPolyline.Path = new Geopath(waypointPositions);
                }
            }



            /*for (int i = 0; i < mission.waypoints.Count; ++i)
             * {
             *      waypointLayer.MapElements.Add(waypointIcon);
             *      var geolocation = new BasicGeoposition() { Latitude = mission.waypoints[i].location.latitude, Longitude = mission.waypoints[i].location.longitude };
             *      (waypointLayer.MapElements[i] as MapIcon).Location = new Geopoint(geolocation);
             *      waypointPositions.Add(geolocation);
             * }
             *
             *
             * if (waypointPositions.Count >= 2)
             * {
             *      var polyline = new MapPolyline
             *      {
             *              StrokeColor = Windows.UI.Color.FromArgb(255, 255, 0, 0),
             *              Path = new Geopath(waypointPositions),
             *              StrokeThickness = 2
             *      };
             *      routeLayer.MapElements.Add(polyline);
             * }*/
        }
Exemplo n.º 48
0
        private void MapSetup()
        {
            var locs         = new LocationCollection();
            var mapPolylines = new List <MapPolyline>();
            var pins         = new List <Pushpin>();

            foreach (var data in geoJsons.Select((value, index) => new { value, index }))
            {
                foreach (var feature in data.value.features.Select((value, index) => new { value, index }))
                {
                    switch (data.index)
                    {
                    case 0:

                        var routeLine = new MapPolyline
                        {
                            Stroke          = new SolidColorBrush(Colors.Red),
                            StrokeThickness = 4
                        };
                        routeLine.Locations = new LocationCollection();

                        foreach (var loc in feature.value.geometry.coordinates)
                        {
                            routeLine.Locations.Add(new Location(loc[1], loc[0]));
                        }

                        mapPolylines.Add(routeLine);

                        var pin = new Pushpin
                        {
                            Location = new Location(feature.value.geometry.coordinates[0][1],
                                                    feature.value.geometry.coordinates[0][0]),
                            ToolTip = "Departure"
                        };

                        var geo = this.geoJsons.Where(x => x.features[0].geometry.coordinates[0][1]
                                                      .Equals(feature.value.geometry.coordinates[0][1]) && x.features[0].geometry.coordinates[0][0]
                                                      .Equals(feature.value.geometry.coordinates[0][0])).Single();
                        if (geo.station != null)
                        {
                            DepartureStation.Content = geo.station.name;
                        }
                        pins.Add(pin);
                        break;

                    case 1:

                        var routeLine2 = new MapPolyline
                        {
                            Stroke          = new SolidColorBrush(Colors.Yellow),
                            StrokeThickness = 4
                        };
                        routeLine2.Locations = new LocationCollection();

                        foreach (var loc in feature.value.geometry.coordinates)
                        {
                            routeLine2.Locations.Add(new Location(loc[1], loc[0]));
                        }

                        mapPolylines.Add(routeLine2);

                        var pin1 = new Pushpin
                        {
                            Location = new Location(feature.value.geometry.coordinates[0][1],
                                                    feature.value.geometry.coordinates[0][0]),
                            ToolTip = "Departure Station"
                        };

                        pins.Add(pin1);
                        break;

                    case 2:

                        var routeLine3 = new MapPolyline
                        {
                            Stroke          = new SolidColorBrush(Colors.Green),
                            StrokeThickness = 4
                        };
                        routeLine3.Locations = new LocationCollection();

                        foreach (var loc in feature.value.geometry.coordinates)
                        {
                            routeLine3.Locations.Add(new Location(loc[1], loc[0]));
                        }

                        mapPolylines.Add(routeLine3);

                        var pin2 = new Pushpin
                        {
                            Location = new Location(feature.value.geometry.coordinates[0][1],
                                                    feature.value.geometry.coordinates[0][0]),
                            ToolTip = "Arrival Station"
                        };
                        var geo1 = this.geoJsons.Where(x => x.features[0].geometry.coordinates[0][1]
                                                       .Equals(feature.value.geometry.coordinates[0][1]) && x.features[0].geometry.coordinates[0][0]
                                                       .Equals(feature.value.geometry.coordinates[0][0])).Single();

                        if (geo1.station != null)
                        {
                            ArrivalStation.Content = geo1.station.name;
                        }

                        pins.Add(pin2);
                        break;
                    }

                    foreach (var coordinate in feature.value.geometry.coordinates)
                    {
                        locs.Add(new Location(coordinate[1], coordinate[0]));
                    }
                }
            }

            //Adding pins and routes with different colours
            for (var i = 0; i < mapPolylines.Count; i++)
            {
                MyMap.Children.Add(mapPolylines[i]);
            }

            for (var i = 0; i < pins.Count; i++)
            {
                MyMap.Children.Add(pins[i]);
            }
            //Adding last pin
            var pinFinal = new Pushpin
            {
                Location = locs[locs.Count - 1],
                ToolTip  = "Arrival"
            };

            if (pins.Count == 1)
            {
                depStackPane.Visibility = System.Windows.Visibility.Collapsed;
                arrStackPane.Visibility = System.Windows.Visibility.Collapsed;
            }

            MyMap.Children.Add(pinFinal);
        }
        /*/public void CalcDima(RootObject daveRequestJson)
         * {
         *  List<xDimaWSService.RouteLocation> dimaWayPointList = new List<xDimaWSService.RouteLocation>();
         *  xDimaWSService.RouteLocation[] dipw = null;
         *
         *  var violatedLocationsList = new List<xDimaWSService.OnRoadRouteLocation>();
         *  violatedIdList = new List<string>();
         *  idList = new List<string>();
         *
         *  var drr = new xDimaWSService.CreateAndGetDistanceMatrixRequest
         *  {
         *      coordinateFormat = "EPSG:4326",
         *      storedProfile = cbxStoredProfile.Text
         *  };
         *
         *  var dimaTaTheme = new xDimaWSService.Theme
         *  {
         *      id = "PTV_TruckAttributes",
         *      enabledSpecified = true
         *  };
         *
         *  dimaTaTheme.enabled = false;
         *
         *  if (cbxFLTruckAttributes.Checked == true)
         *  {
         *      dimaTaTheme.enabled = true;
         *  }
         *
         *  drr.requestProfile = new xDimaWSService.RequestProfile()
         *  {
         *      featureLayerProfile = new xDimaWSService.FeatureLayerProfile()
         *      {
         *          themes = new xDimaWSService.Theme[]
         *          {
         *              dimaTaTheme
         *          },
         *      },
         *  };
         *
         *  if (daveRequestJson.stops.Count >= 2)
         *  {
         *      foreach (var stop in daveRequestJson.stops)
         *      {
         *          var wpt = new xDimaWSService.OnRoadRouteLocation()
         *          {
         *              coordinate = new xDimaWSService.Coordinate()
         *              {
         *                  x = stop.coordinate.locationX,
         *                  y = stop.coordinate.locationY
         *              }
         *          };
         *          dimaWayPointList.Add(wpt);
         *      }
         *  }
         *  else
         *  {
         *      MessageBox.Show("Not enough waypoints!");
         *      return;
         *  }
         *
         *  foreach (var scemId in daveRequestJson.stops)
         *  {
         *      idList.Add(scemId.scemid.ToString());
         *  }
         *
         *  dipw = dimaWayPointList.ToArray();
         *  drr.startLocations = dipw;
         *  var locationsList = dipw.OfType<xDimaWSService.OnRoadRouteLocation>().ToList();
         *  drr.resultFields = new xDimaWSService.DistanceMatrixContentsResultFields()
         *  {
         *      distances = true,
         *      distancesSpecified = true,
         *      violated = true,
         *      violatedSpecified = true,
         *      estimatedByDirectDistance = true,
         *      estimatedByDirectDistanceSpecified = true
         *  };
         *
         *  try
         *  {
         *      dimaResponse = xDimaClient.createDistanceMatrix(drr);
         *  }
         *  catch (System.Web.Services.Protocols.SoapException soapException)
         *  {
         *      System.Windows.Forms.MessageBox.Show(soapException.Detail.InnerXml.Replace(">", ">\r\n"));
         *      return;
         *  }
         *  catch (System.ServiceModel.FaultException faultException)
         *  {
         *      System.Windows.Forms.MessageBox.Show("Error when trying to calculate the dima" + "\r\n" + faultException.Message);
         *      return;
         *  }
         *  catch (Exception ex)
         *  {
         *      MessageBox.Show(ex.Message);
         *      return;
         *  }
         *
         *  waypointCount = dimaResponse.summary.numberOfStartLocations;
         *  distanceMatrixResponseContents = dimaResponse.contents as xDimaWSService.DistanceMatrixContentsArrays;
         *
         *  for (int i = 0; i < dimaResponse.summary.numberOfStartLocations; i++)
         *  {
         *      var numberOfViolations = 0;
         *      for (int j = 0; j < dimaResponse.summary.numberOfStartLocations; j++)
         *      {
         *          if (distanceMatrixResponseContents.violated[i * dimaResponse.summary.numberOfStartLocations + j])
         *          {
         *              numberOfViolations++;
         *          }
         *      }
         *      if (numberOfViolations >= waypointCount - 1)
         *      {
         *          violatedLocationsList.Add(locationsList[i]);
         *      }
         *  }
         *
         *  ShowDimaInDynMap(idList, locationsList, violatedLocationsList);
         *  waypointCount = 0;
         * }
         * /*/

        public void ShowRouteInDynMap()
        {
            var mapCoordFormat = "";

            if (cbxCoordFormat.Text == "EPSG:76131")
            {
                routingLayer = new ShapeLayer("Route")
                {
                    SpatialReferenceId = "PTV_MERCATOR"
                };
                mapCoordFormat = "PTV_MERCATOR";
            }
            else if (cbxCoordFormat.Text == "EPSG:4326")
            {
                routingLayer = new ShapeLayer("Route")
                {
                    SpatialReferenceId = "EPSG:4326"
                };
                mapCoordFormat = "EPSG:4326";
            }
            else if (cbxCoordFormat.Text == "EPSG:3857")
            {
                routingLayer = new ShapeLayer("Route")
                {
                    SpatialReferenceId = "EPSG:3857"
                };
                mapCoordFormat = "EPSG:3857";
            }

            if (routeResponse.polyline != null)
            {
                var routePoly = routeResponse.polyline.plain as xRouteWSService.Polyline;

                var points = new PointCollection();

                foreach (xRouteWSService.Coordinate p in routePoly.polyline)
                {
                    points.Add(new System.Windows.Point(p.x, p.y));
                }

                MapPolyline mapPolyLine = new MapPolyline()
                {
                    Points             = points,
                    Stroke             = new SolidColorBrush(Colors.Blue),
                    MapStrokeThickness = 10,
                    Opacity            = 1.0,
                    ScaleFactor        = 0.2
                };

                (routingLayer as ShapeLayer).Shapes.Add(mapPolyLine);
                mapPolyLine.ToolTip = string.Format("{0:0,0.0}km\n{1}", Math.Round(routeResponse.distance / 1000.0, 2), TimeSpan.FromSeconds(routeResponse.travelTime));
            }
            else
            {
                MessageBox.Show("Error while calculating route");
                return;
            }

            var markerStart = new Ptv.XServer.Controls.Map.Symbols.Ball
            {
                Color = Colors.Green
            };
            var markerVia = new Ptv.XServer.Controls.Map.Symbols.Ball
            {
                Color = Colors.Yellow
            };
            var markerDest = new Ptv.XServer.Controls.Map.Symbols.Ball
            {
                Color = Colors.Red
            };

            mapCoordStart = new System.Windows.Point(double.Parse(tbxStartX.Text.Replace(".", ",")), double.Parse(tbxStartY.Text.Replace(".", ",")));
            mapCoordDest  = new System.Windows.Point(double.Parse(tbxDestX.Text.Replace(".", ",")), double.Parse(tbxDestY.Text.Replace(".", ",")));
            ShapeCanvas.SetLocation(markerStart, mapCoordStart);
            ShapeCanvas.SetLocation(markerDest, mapCoordDest);
            markerStart.Width   = markerStart.Height = markerDest.Height = markerDest.Width = markerVia.Height = markerVia.Width = 10;
            markerStart.ToolTip = "Start";
            markerDest.ToolTip  = "Destination";

            if (cbxManipulateWpt.Checked == true)
            {
                mapCoordVia = new System.Windows.Point(double.Parse(tbxViaX.Text.Replace(".", ",")), double.Parse(tbxViaY.Text.Replace(".", ",")));
                ShapeCanvas.SetLocation(markerVia, mapCoordVia);
                markerVia.ToolTip = "Via";
                routingLayer.Shapes.Add(markerVia);
            }

            routingLayer.Shapes.Add(markerStart);
            routingLayer.Shapes.Add(markerDest);

            dynMap.Layers.Add(routingLayer);

            //zoom to contain route
            MapRectangle mergedRoutesRectangle = new MapRectangle();
            var          polyLine = routeResponse.polyline.plain as xRouteWSService.Polyline;

            var winPoints = from coord in polyLine.polyline
                            select new System.Windows.Point(coord.x, coord.y);

            mergedRoutesRectangle |= new MapRectangle(winPoints);

            dynMap.SetEnvelope(mergedRoutesRectangle.Inflate(1.2), mapCoordFormat);

            routingLayer.Refresh();
        }
        /// <summary>
        /// Renders a route response on the map.
        /// </summary>
        private void RenderRouteResponse(RouteRequest routeRequest, Response response)
        {
            //Render the route on the map.
            if (response != null && response.ResourceSets != null && response.ResourceSets.Length > 0 &&
                response.ResourceSets[0].Resources != null && response.ResourceSets[0].Resources.Length > 0 &&
                response.ResourceSets[0].Resources[0] is Route)
            {
                var route = response.ResourceSets[0].Resources[0] as Route;

                var timeSpan = new TimeSpan(0, 0, (int)Math.Round(route.TravelDurationTraffic));

                if (timeSpan.Days > 0)
                {
                    OutputTbx.Text = string.Format("Travel Time: {3} days {0} hr {1} min {2} sec\r\n", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Days);
                    OutputTbx.AppendText("\n");
                }
                else
                {
                    OutputTbx.Text = string.Format("Travel Time: {0} hr {1} min {2} sec\r\n", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds);
                    OutputTbx.AppendText("\n");
                }

                ///Hard code start date and time
                DateTime dt = new DateTime(2020, 5, 29, 23, 0, 0);

                /*
                 *    var tspan = route.RouteLegs[0].TravelDuration;
                 *    TimeSpan tispan = new TimeSpan(0,0,(int)(tspan));
                 *    DateTime newDate = dt.Add(tispan);
                 *    string ndt = (newDate).ToString();
                 *    OutputTbx.AppendText(ndt);
                 */

                //  var dest = DMatrix.Destination;



                //Route Travel Distance (In Miles)
                OutputTbx.AppendText("Travel Distance: ");
                var dist = route.TravelDistance;
                var dis  = dist.ToString();
                OutputTbx.AppendText(dis);
                OutputTbx.AppendText(" mi\n\n");

                ///Start Location and Start Time Output
                string num = (1).ToString();
                OutputTbx.AppendText(num); OutputTbx.AppendText("--");
                OutputTbx.AppendText(routeRequest.Waypoints[0].Address);
                OutputTbx.AppendText("\t");
                string ndt = (dt).ToString();
                OutputTbx.AppendText(ndt);
                OutputTbx.AppendText("\n");

///Output - Ordered Waypoints and corresponding ETA
                for (var i = 1; i < routeRequest.Waypoints.Count; i++)
                {
                    num = (i + 1).ToString();
                    OutputTbx.AppendText(num); OutputTbx.AppendText("--");
                    OutputTbx.AppendText(routeRequest.Waypoints[i].Address);
                    OutputTbx.AppendText("\t");
                    var      tspan   = route.RouteLegs[i - 1].TravelDuration;
                    TimeSpan tispan  = new TimeSpan(0, 0, (int)(tspan));
                    DateTime newDate = dt.Add(tispan); dt = newDate;
                    ndt = (newDate).ToString();
                    OutputTbx.AppendText(ndt);
                    OutputTbx.AppendText("\n");
                }


                ///for (var i = 0; i < routeRequest.Waypoints.Count; i++)

                /*    for (var i = 0; i < routeRequest.Waypoints.Count-1; i++)
                 *  {
                 *      var tspan = route.RouteLegs[i].TravelDuration;
                 *      string tnum = (tspan).ToString();
                 *      OutputTbx.AppendText(tnum);
                 *      OutputTbx.AppendText("\n");
                 *  }
                 */

                var routeLine = route.RoutePath.Line.Coordinates;
                var routePath = new LocationCollection();

                for (int i = 0; i < routeLine.Length; i++)
                {
                    routePath.Add(new Microsoft.Maps.MapControl.WPF.Location(routeLine[i][0], routeLine[i][1]));
                }

                var routePolyline = new MapPolyline()
                {
                    Locations       = routePath,
                    Stroke          = new SolidColorBrush(Colors.Red),
                    StrokeThickness = 3
                };

                MyMap.Children.Add(routePolyline);

                var locs = new List <Microsoft.Maps.MapControl.WPF.Location>();

                //Create pushpins for the optimized waypoints.
                //The waypoints in the request were optimized for us.
                for (var i = 0; i < routeRequest.Waypoints.Count; i++)
                {
                    var loc = new Microsoft.Maps.MapControl.WPF.Location(routeRequest.Waypoints[i].Coordinate.Latitude, routeRequest.Waypoints[i].Coordinate.Longitude);

                    //Only render the last waypoint when it is not a round trip.
                    if (i < routeRequest.Waypoints.Count - 1)
                    {
                        MyMap.Children.Add(new Pushpin()
                        {
                            Location = loc,
                            Content  = i
                        });
                    }

                    locs.Add(loc);
                }

                MyMap.SetView(locs, new Thickness(50), 0);
            }
            else if (response != null && response.ErrorDetails != null && response.ErrorDetails.Length > 0)
            {
                throw new Exception(String.Join("", response.ErrorDetails));
            }
        }
Exemplo n.º 51
0
        private void FileOpen_Click(object sender, RoutedEventArgs e)
        {
            string path = "";

            try
            {
                OpenFileDialog openDlg = new OpenFileDialog
                {
                    DefaultExt       = ".dat",
                    InitialDirectory = CurrentDir
                };
                openDlg.ShowDialog();
                path = openDlg.FileName;                    // get filepath

                if (path != "")
                {
                    currentUser.Load(path);                     // loads but list doesn't update without next line
                    lb_objects.ItemsSource = currentUser.OcICartoObj;
                    //MessageBox.Show(currentUser.ToString());	// DEBUG
                    foreach (ICartoObj obj in currentUser.OcICartoObj)
                    {
                        if (obj is POI)
                        {
                            temppoi = obj as POI;
                            Pushpin newPin = new Pushpin();
                            newPin.Location = new Location(temppoi.Latitude, temppoi.Longitude);
                            bingmap.Children.Add(newPin);
                        }
                        if (obj is Polyline)
                        {
                            temppl = obj as Polyline;
                            MapPolyline newMPL = new MapPolyline();
                            newMPL.Stroke          = new SolidColorBrush(temppl.Couleur);
                            newMPL.StrokeThickness = temppl.Epaisseur;
                            newMPL.Opacity         = 1;
                            newMPL.Locations       = new LocationCollection();
                            foreach (Coordonnees cd in temppl.ListeCoord)
                            {
                                newMPL.Locations.Add(new Location(cd.Latitude, cd.Longitude));
                            }
                            bingmap.Children.Add(newMPL);
                        }
                        if (obj is Polygon)
                        {
                            temppg = obj as Polygon;
                            MapPolygon newMPG = new MapPolygon();
                            newMPG.Fill      = new SolidColorBrush(temppg.Remplissage);
                            newMPG.Stroke    = new SolidColorBrush(temppg.Contour);
                            newMPG.Opacity   = temppg.Opacite;
                            newMPG.Locations = new LocationCollection();
                            foreach (Coordonnees cd in temppg.ListeCoord)
                            {
                                newMPG.Locations.Add(new Location(cd.Latitude, cd.Longitude));
                            }
                            bingmap.Children.Add(newMPG);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Exemplo n.º 52
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string navigationParameter;

            if (!NavigationContext.QueryString.TryGetValue(AppConstants.NAVIGATIONPARAMETER_TYPE, out navigationParameter))
            {
                navigationParameter = null;
            }

            if (App.ViewModel.Settings.IsTrial)
            {
                adRotatorControl.Visibility = System.Windows.Visibility.Visible;
                adDefaultControl.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                adRotatorControl.Visibility = System.Windows.Visibility.Collapsed;
                adDefaultControl.Visibility = System.Windows.Visibility.Collapsed;
            }

            var    lapViewModel          = App.ViewModel.Track.History.SelectedSession.SelectedLap;
            string lapMinimumLengthBlurb = string.Format("* {0} {1} {2}",
                                                         AppResources.Text_Blurb_OfficialLength,
                                                         Math.Round(App.ViewModel.Track.Length * Constants.APP_MINIMUMLAPLENGTH_FACTOR, 3),
                                                         App.ViewModel.Settings.IsMetricUnits
                                                         ? AppResources.Text_Unit_Kilometres
                                                         : AppResources.Text_Unit_Miles);

            var lapDetailViewModel = new LapDetailViewModel
            {
                Lap                     = lapViewModel,
                SpeedUnitText           = App.ViewModel.SpeedUnitText,
                LengthUnitText          = App.ViewModel.LengthUnitText,
                ProjectedLength         = lapViewModel.ProjectedLength(),
                SessionWeather          = App.ViewModel.Track.History.SelectedSession.Weather,
                GpsDeviceName           = App.ViewModel.Track.History.SelectedSession.GpsDeviceName,
                LapMinimumLengthBlurb   = lapMinimumLengthBlurb,
                IsOfficial              = null,
                LapBelongsToCurrentUser = true,
                IsLeaderboardTime       = string.Equals(navigationParameter, AppConstants.NAVIGATIONPARAMETER_VALUE_LEADERBOARD)
            };

            var bestLapViewModel = lapViewModel as BestLapViewModel;

            if (bestLapViewModel != null)
            {
                lapDetailViewModel.UserDisplayName         = bestLapViewModel.UserDisplayName;
                lapDetailViewModel.GpsDeviceName           = bestLapViewModel.GpsDeviceName;
                lapDetailViewModel.IsOfficial              = !bestLapViewModel.IsUnofficial;
                lapDetailViewModel.LapBelongsToCurrentUser = App.ViewModel.IsAuthenticated && bestLapViewModel.UserName == App.MobileService.CurrentUser.UserId;
            }

            DataContext = lapDetailViewModel;
            var sectorSplitsAhead = new Dictionary <int, bool>();

            foreach (var sector in App.ViewModel.Track.Sectors)
            {
                var sectorSplitDataPoint = lapDetailViewModel.Lap.DataPoints.Where(dp => dp.Latitude.HasValue && dp.Longitude.HasValue).SkipWhile(dp => dp.SectorNumber != sector.SectorNumber).TakeWhile(dp => dp.SectorNumber == sector.SectorNumber).LastOrDefault();
                if (!sector.IsFinishLine && sectorSplitDataPoint == null)
                {
                    sectorSplitsAhead.Add(sector.SectorNumber, false);
                    continue;
                }

                var sectorSplit = sector.IsFinishLine
                                    ? lapDetailViewModel.Lap.LapTime
                                    : sectorSplitDataPoint.ElapsedTime - lapDetailViewModel.Lap.StartElapsedTime;

                TimeSpan bestSplit;
                if (sector.IsFinishLine)
                {
                    bestSplit = App.ViewModel.Track.BestLap != null && App.ViewModel.Track.BestLap.DataPoints != null
                                ? App.ViewModel.Track.BestLap.LapTime
                                : sectorSplit;
                }
                else
                {
                    var bestSplitDataPoint = App.ViewModel.Track.BestLap != null && App.ViewModel.Track.BestLap.DataPoints != null
                                                ? App.ViewModel.Track.BestLap.DataPoints.Where(dp => dp.Latitude.HasValue && dp.Longitude.HasValue).SkipWhile(dp => dp.SectorNumber != sector.SectorNumber).TakeWhile(dp => dp.SectorNumber == sector.SectorNumber).LastOrDefault()
                                                : null;

                    bestSplit = bestSplitDataPoint != null
                                ? bestSplitDataPoint.ElapsedTime - App.ViewModel.Track.BestLap.StartElapsedTime
                                : sectorSplit;
                }

                var splitStatus = sectorSplit - bestSplit;
                lapDetailViewModel.SectorSplits.Add(Tuple.Create(sector.SectorNumber,
                                                                 sectorSplit,
                                                                 splitStatus));
                sectorSplitsAhead.Add(sector.SectorNumber, splitStatus <= TimeSpan.Zero);
            }

            mapCircuit.Center = new GeoCoordinate(App.ViewModel.Track.Latitude, App.ViewModel.Track.Longitude);
            mapCircuit.SetZoomLevelForTrack(App.ViewModel.Track.LengthInMetres());

            TrackSectorViewModel finishLineSector = null;

            foreach (var sector in App.ViewModel.Track.Sectors)
            {
                if (sector.IsFinishLine)
                {
                    finishLineSector = sector;
                }

                var sectorLine = new MapPolyline();
                sectorLine.StrokeColor = sector.IsFinishLine ? Colors.Orange : Colors.Black;
                sectorLine.Path.Add(new GeoCoordinate(sector.StartLatitude, sector.StartLongitude));
                sectorLine.Path.Add(new GeoCoordinate(sector.EndLatitude, sector.EndLongitude));
                mapCircuit.MapElements.Add(sectorLine);
            }

            LapDataPointViewModel previousGeographicDataPoint = App.ViewModel.Track.History.SelectedSession.SelectedLap.DataPoints.FirstOrDefault(dp => dp.Latitude != null && dp.Longitude != null);

            if (previousGeographicDataPoint == null)
            {
                return;
            }

            var finishLineMidPoint = finishLineSector == null
                                        ? null
                                        : GeoUtmConverter.Midpoint(GeographyPoint.Create(finishLineSector.StartLatitude, finishLineSector.StartLongitude),
                                                                   GeographyPoint.Create(finishLineSector.EndLatitude, finishLineSector.EndLongitude),
                                                                   finishLineSector.Heading);

            if (finishLineMidPoint != null && App.ViewModel.Track.History.SelectedSession.SelectedLap.IsComplete)
            {
                AddCoordinatesAsPathLineToMap(previousGeographicDataPoint.SectorNumber, sectorSplitsAhead, finishLineMidPoint, previousGeographicDataPoint.AsGeographyPoint());
            }

            LapDataPointViewModel previousAccelerometerDataPoint = null;
            LapDataPointViewModel maxSpeedDataPoint = null;
            double?minSpeed           = null;
            var    decelerationSpeeds = new List <Tuple <double?, TimeSpan> >();
            var    mapLineAheadColor  = new SolidColorBrush(System.Windows.Media.Colors.Green);
            var    mapLineBehindColor = new SolidColorBrush(System.Windows.Media.Colors.Red);

            foreach (var dataPoint in App.ViewModel.Track.History.SelectedSession.SelectedLap.DataPoints)
            {
                if (!dataPoint.Latitude.HasValue || !dataPoint.Longitude.HasValue)
                {
                    if (dataPoint.AccelerationX.HasValue || dataPoint.AccelerationY.HasValue || dataPoint.AccelerationZ.HasValue)
                    {
                        previousAccelerometerDataPoint = dataPoint;
                    }
                    continue;
                }

                if (maxSpeedDataPoint == null || dataPoint.Speed > maxSpeedDataPoint.Speed)
                {
                    maxSpeedDataPoint = dataPoint;
                }

                if (!minSpeed.HasValue || minSpeed < dataPoint.Speed)
                {
                    if (decelerationSpeeds.Count > 1 && decelerationSpeeds.Sum(ds => ds.Item2.TotalSeconds) > 0.5)
                    {
                        // Create a pushpin for maximum speed before braking
                        if (maxSpeedDataPoint != null)
                        {
                            string pushpinContent = string.Format("{0}{1}",
                                                                  Math.Round(maxSpeedDataPoint.Speed.Value).ToString(CultureInfo.CurrentCulture),
                                                                  App.ViewModel.Settings.IsMetricUnits
                                                                        ? AppResources.Text_Unit_MetricSpeed
                                                                        : AppResources.Text_Unit_ImperialSpeed);
                            var pushpinData = Tuple.Create(new GeoCoordinate(maxSpeedDataPoint.Latitude.Value, maxSpeedDataPoint.Longitude.Value), pushpinContent);
                            apexDataLayer.Add(pushpinData);

                            maxSpeedDataPoint = null;
                        }

                        double decelerationTime = decelerationSpeeds.Sum(ds => ds.Item2.TotalSeconds);
                        double?totalSpeedLost   = decelerationSpeeds.First().Item1 - decelerationSpeeds.Last().Item1;
                        if (totalSpeedLost.HasValue && (totalSpeedLost.Value / decelerationTime) > 3)
                        {
                            // Create a pushpin for minimum speed through corner and the nearest g-force reading (if available)
                            string pushpinContent;
                            if (previousAccelerometerDataPoint != null)
                            {
                                pushpinContent = string.Format("{0}{1} | {2}{3}",
                                                               Math.Round(minSpeed.Value).ToString(CultureInfo.CurrentCulture),
                                                               App.ViewModel.Settings.IsMetricUnits
                                                                    ? AppResources.Text_Unit_MetricSpeed
                                                                    : AppResources.Text_Unit_ImperialSpeed,
                                                               ComputeRelativeGforce(previousAccelerometerDataPoint, App.ViewModel.Track.History.SelectedSession.DeviceOrientation),
                                                               AppResources.Text_Unit_GForce);
                            }
                            else
                            {
                                pushpinContent = string.Format("{0}{1}",
                                                               Math.Round(minSpeed.Value).ToString(CultureInfo.CurrentCulture),
                                                               App.ViewModel.Settings.IsMetricUnits
                                                                    ? AppResources.Text_Unit_MetricSpeed
                                                                    : AppResources.Text_Unit_ImperialSpeed);
                            }
                            var pushpinData = Tuple.Create(new GeoCoordinate(previousGeographicDataPoint.Latitude.Value, previousGeographicDataPoint.Longitude.Value), pushpinContent);
                            apexDataLayer.Add(pushpinData);
                        }
                    }
                    decelerationSpeeds.Clear();
                    minSpeed = dataPoint.Speed;
                }
                else
                {
                    minSpeed = dataPoint.Speed;
                    decelerationSpeeds.Add(Tuple.Create(minSpeed, dataPoint.ElapsedTime - previousGeographicDataPoint.ElapsedTime));
                }
                AddCoordinatesAsPathLineToMap(dataPoint.SectorNumber, sectorSplitsAhead, previousGeographicDataPoint.AsGeographyPoint(), dataPoint.AsGeographyPoint());

                previousGeographicDataPoint = dataPoint;
            }

            if (finishLineMidPoint != null && App.ViewModel.Track.History.SelectedSession.SelectedLap.IsComplete)
            {
                AddCoordinatesAsPathLineToMap(previousGeographicDataPoint.SectorNumber, sectorSplitsAhead, previousGeographicDataPoint.AsGeographyPoint(), finishLineMidPoint);
            }

            base.OnNavigatedTo(e);
        }
Exemplo n.º 53
0
        void rsc_QueryRealRoadsCompleted(object sender, QueryRealRoadsCompletedEventArgs e)
        {
            MapLayer layer   = (MapLayer)this.ctlMap.FindName("realroads");
            var      builder = new StringBuilder();

            if (e.Error == null)
            {
                Color color = Colors.Blue;
                for (int i = 0; i < e.Result.Count; i++)
                {
                    string[] strArray = e.Result[i].Split(new char[] { ';' });

                    builder.Length = 0;
                    int index = 2;
                    while (index < (strArray.Length - 1))
                    {
                        builder.Append(strArray[index] + ": ");
                        index++;
                    }
                    string[] strArray2 = strArray[strArray.Length - 1].Split(new char[] { ',' });

                    if ((strArray2.Length == 1) && (strArray2[0].Length > 1))
                    {
                    }
                    else
                    {
                        LocationCollection locations;
                        Location           location2;

                        if (strArray2[0].Equals(strArray2[strArray2.Length - 1]))
                        {
                            var polygon = new MapPolygon
                            {
                                Stroke          = new SolidColorBrush(color),
                                StrokeThickness = 0.5,
                                Fill            = new SolidColorBrush(color),
                                Opacity         = 0.75
                            };
                            locations = new LocationCollection();
                            index     = 0;
                            while (index < strArray2.Length)
                            {
                                if (strArray2[index].IndexOf(" ") != -1)
                                {
                                    location2 = new Location(double.Parse(strArray2[index].Split(new char[] { ' ' })[0]),
                                                             double.Parse(strArray2[index].Split(new char[] { ' ' })[1]));
                                    locations.Add(location2);
                                }
                                index++;
                            }
                            polygon.Locations = locations;
                            ToolTipService.SetToolTip(polygon, builder.ToString());
                            layer.Children.Add(polygon);
                        }
                        else
                        {
                            var polyline = new MapPolyline {
                                Stroke = new SolidColorBrush(color), StrokeThickness = 6.0
                            };
                            var doubles = new DoubleCollection {
                                3.0, 3.0
                            };
                            polyline.StrokeDashArray = doubles;
                            locations = new LocationCollection();

                            for (index = strArray2.Length - 1; index >= 0; index--)
                            {
                                location2 = new Location(double.Parse(strArray2[index].Split(new char[] { ' ' })[0]),
                                                         double.Parse(strArray2[index].Split(new char[] { ' ' })[1]));

                                locations.Add(location2);
                            }

                            polyline.Locations = locations;
                            ToolTipService.SetToolTip(polyline, builder.ToString());

                            layer.Children.Add(polyline);
                        }
                    }
                }
            }
        }
Exemplo n.º 54
0
        public async Task DirectionFinderAsync()
        {
            MapPolyline CurrentDrawed = null;

            try
            {
                foreach (var item in MapView.MapControl.MapElements)
                {
                    if (item.GetType() == typeof(MapPolyline))
                    {
                        CurrentDrawed = (MapPolyline)item;
                    }
                }
            }
            catch { }
            if (Mode == DirectionMode.walking)
            {
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async delegate
                {
                    if (Origin != null && Destination != null)
                    {
                        DirectionsHelper.Rootobject r = null;
                        if (Waypoints == null)
                        {
                            r = await DirectionsHelper.GetDirections(Origin.Position, Destination.Position, DirectionsHelper.DirectionModes.walking);
                        }
                        else
                        {
                            var lst = new List <BasicGeoposition>();
                            foreach (var item in Waypoints)
                            {
                                if (item != null)
                                {
                                    lst.Add(new BasicGeoposition()
                                    {
                                        Latitude = item.Position.Latitude, Longitude = item.Position.Longitude
                                    });
                                }
                            }
                            if (lst.Count > 0)
                            {
                                r = await DirectionsHelper.GetDirections(Origin.Position, Destination.Position, DirectionsHelper.DirectionModes.walking, lst);
                            }
                            else
                            {
                                r = await DirectionsHelper.GetDirections(Origin.Position, Destination.Position, DirectionsHelper.DirectionModes.walking);
                            }
                        }
                        if (r == null || r.routes.Count() == 0)
                        {
                            //await new MessageDialog("No way to your destination!!!").ShowAsync();
                            return;
                        }
                        if (CurrentDrawed != null)
                        {
                            MapView.MapControl.MapElements.Remove(CurrentDrawed);
                        }
                        var route = DirectionsHelper.GetDirectionAsRoute(r.routes.FirstOrDefault(), (Color)Resources["SystemControlBackgroundAccentBrush"]);
                        MapView.MapControl.MapElements.Add(route);
                        var es = DirectionsHelper.GetTotalEstimatedTime(r.routes.FirstOrDefault());
                        var di = DirectionsHelper.GetDistance(r.routes.FirstOrDefault());
                        //await new MessageDialog($"we calculate that the route is about {di} and takes about {es}").ShowAsync();
                        await MapView.MapControl.TryZoomToAsync(16);
                        MapView.MapControl.Center       = Origin;
                        MapView.MapControl.DesiredPitch = 45;
                        MapViewVM.ActiveNavigationMode  = true;
                        new DisplayRequest().RequestActive();
                    }
                    else
                    {
                        await new MessageDialog(MultilingualHelpToolkit.GetString("StringSelectBothOriginAndDestination", "Text")).ShowAsync();
                    }
                });
            }
            else if (Mode == DirectionMode.driving)
            {
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async delegate
                {
                    if (Origin != null && Destination != null)
                    {
                        DirectionsHelper.Rootobject r = null;
                        if (Waypoints == null)
                        {
                            r = await DirectionsHelper.GetDirections(Origin.Position, Destination.Position, DirectionsHelper.DirectionModes.driving);
                        }
                        else
                        {
                            var lst = new List <BasicGeoposition>();
                            foreach (var item in Waypoints)
                            {
                                if (item != null)
                                {
                                    lst.Add(new BasicGeoposition()
                                    {
                                        Latitude = item.Position.Latitude, Longitude = item.Position.Longitude
                                    });
                                }
                            }
                            if (lst.Count > 0)
                            {
                                r = await DirectionsHelper.GetDirections(Origin.Position, Destination.Position, DirectionsHelper.DirectionModes.driving, lst);
                            }
                            else
                            {
                                r = await DirectionsHelper.GetDirections(Origin.Position, Destination.Position, DirectionsHelper.DirectionModes.driving);
                            }
                        }
                        if (r == null || r.routes.Count() == 0)
                        {
                            //await new MessageDialog("No way to your destination!!!").ShowAsync();
                            return;
                        }
                        if (CurrentDrawed != null)
                        {
                            MapView.MapControl.MapElements.Remove(CurrentDrawed);
                        }
                        var route = DirectionsHelper.GetDirectionAsRoute(r.routes.FirstOrDefault(), (Color)Resources["SystemControlBackgroundAccentBrush"]);
                        MapView.MapControl.MapElements.Add(route);
                        var es = DirectionsHelper.GetTotalEstimatedTime(r.routes.FirstOrDefault());
                        var di = DirectionsHelper.GetDistance(r.routes.FirstOrDefault());
                        //await new MessageDialog($"we calculate that the route is about {di} and takes about {es}").ShowAsync();
                        await MapView.MapControl.TryZoomToAsync(16);
                        MapView.MapControl.Center       = Origin;
                        MapView.MapControl.DesiredPitch = 45;
                        MapViewVM.ActiveNavigationMode  = true;
                        new DisplayRequest().RequestActive();
                    }
                    else
                    {
                        await new MessageDialog(MultilingualHelpToolkit.GetString("StringSelectBothOriginAndDestination", "Text")).ShowAsync();
                    }
                });
            }
            else
            {
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async delegate
                {
                    if (Origin != null && Destination != null)
                    {
                        DirectionsHelper.Rootobject r = null;
                        r = await DirectionsHelper.GetDirections(Origin.Position, Destination.Position, DirectionsHelper.DirectionModes.transit);
                        if (r == null || r.routes.Count() == 0)
                        {
                            //await new MessageDialog("No way to your destination!!!").ShowAsync();
                            return;
                        }
                        if (CurrentDrawed != null)
                        {
                            MapView.MapControl.MapElements.Remove(CurrentDrawed);
                        }
                        var route = DirectionsHelper.GetDirectionAsRoute(r.routes.FirstOrDefault(), (Color)Resources["SystemControlBackgroundAccentBrush"]);
                        MapView.MapControl.MapElements.Add(route);
                        var es = DirectionsHelper.GetTotalEstimatedTime(r.routes.FirstOrDefault());
                        var di = DirectionsHelper.GetDistance(r.routes.FirstOrDefault());
                        //await new MessageDialog($"we calculate that the route is about {di} and takes about {es}").ShowAsync();
                        await MapView.MapControl.TryZoomToAsync(16);
                        MapView.MapControl.Center       = Origin;
                        MapView.MapControl.DesiredPitch = 45;
                        MapViewVM.ActiveNavigationMode  = true;
                        new DisplayRequest().RequestActive();
                    }
                    else
                    {
                        await new MessageDialog(MultilingualHelpToolkit.GetString("StringSelectBothOriginAndDestination", "Text")).ShowAsync();
                    }
                });
            }
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (!IsInternet())
            {
                await new MessageDialog("Seems you are not connected to the Internet").ShowAsync();
                return;
            }
            else
            {
                progress.IsActive     = true;
                MyMap.MapServiceToken = "YP9WTSzOHUo0dbahsH8J~J-K6u01dT98SF4uCCKpiwA~AnGaYM6yJxoLF1tGHEIXHFskGfwSRJTr1S5aO1dB-TCXjQ1ZX0xEWgeYslbC3Fov";
                Geolocator locator = new Geolocator();
                locator.DesiredAccuracyInMeters = 50;
                var position = await locator.GetGeopositionAsync();

                await MyMap.TrySetViewAsync(position.Coordinate.Point, 17D);

                progress.IsActive = false;
                mySlider.Value    = 13;
                Arguments args = e.Parameter as Arguments;
                Dictionary <string, object> Parameters = args.Values;
                if (args.GetType(VoiceCommandType.NO_VOICE))
                {
                    mSource      = Parameters["source"].ToString();
                    mDestination = Parameters["destination"].ToString();
                    CabsAPI     api       = new CabsAPI();
                    GeoResponse sResponse = await api.GeoCodingResult(Token, mSource);

                    GeoResponse dResponse = await api.GeoCodingResult(Token, mDestination);

                    if (sResponse.Code == ResponseCode.SUCCESS && dResponse.Code == ResponseCode.SUCCESS)
                    {
                        AddMapIcon(Convert.ToDouble(sResponse.Position.Latitude), Convert.ToDouble(sResponse.Position.Longitude), mSource);
                        AddMapIcon(Convert.ToDouble(dResponse.Position.Latitude), Convert.ToDouble(dResponse.Position.Longitude), mDestination);
                    }
                    else
                    {
                        await new MessageDialog("Error retrieving Geopositions!").ShowAsync();
                        return;
                    }
                    MapPolyline polyline    = new MapPolyline();
                    var         coordinates = new List <BasicGeoposition>();
                    var         routeClient = new RouteClient();
                    coordinates = await routeClient.route(mSource, mDestination);

                    polyline.StrokeColor     = Windows.UI.Color.FromArgb(128, 255, 0, 0);
                    polyline.StrokeThickness = 5;
                    polyline.Path            = new Geopath(coordinates);
                    MyMap.MapElements.Add(polyline);
                    SrcBox.Text  = mSource;
                    DestBox.Text = mDestination;
                    PriceEstimateResponse pResponse = await api.GetEstimate(Token, Parameters["slat"].ToString(), Parameters["slng"].ToString(), Parameters["dlat"].ToString(), Parameters["dlng"].ToString());

                    if (pResponse.Code == ResponseCode.SUCCESS)
                    {
                        CabsListView.ItemsSource = pResponse.Estimates;
                        // ReadSpeech(new MediaElement(), "Showing Estimated cab fare from" + mSource + "to" + mDestination);
                    }
                }
            }
        }
Exemplo n.º 56
0
        public async void DirectionFinderFunctionality()
        {
            DirectionsHelper.DirectionModes mod = DirectionsHelper.DirectionModes.walking;
            switch (Mode)
            {
            case DirectionMode.walking:
                mod = DirectionsHelper.DirectionModes.walking;
                break;

            case DirectionMode.driving:
                mod = DirectionsHelper.DirectionModes.driving;
                break;

            case DirectionMode.transit:
                mod = DirectionsHelper.DirectionModes.transit;
                break;

            default:
                break;
            }
            try
            {
                MapPolyline CurrentDrawed = null;
                try
                {
                    foreach (var item in MapView.MapControl.MapElements)
                    {
                        if (item.GetType() == typeof(MapPolyline))
                        {
                            CurrentDrawed = (MapPolyline)item;
                        }
                    }
                }
                catch { }
                if (Origin != null && Destination != null)
                {
                    DirectionsHelper.Rootobject r = null;
                    if (Waypoints == null)
                    {
                        r = await DirectionsHelper.GetDirections(Origin.Position, Destination.Position, mod);
                    }
                    else
                    {
                        var lst = new List <BasicGeoposition>();
                        foreach (var item in Waypoints)
                        {
                            if (item != null)
                            {
                                lst.Add(new BasicGeoposition()
                                {
                                    Latitude = item.Position.Latitude, Longitude = item.Position.Longitude
                                });
                            }
                        }
                        if (lst.Count > 0)
                        {
                            r = await DirectionsHelper.GetDirections(Origin.Position, Destination.Position, mod, lst);
                        }
                        else
                        {
                            r = await DirectionsHelper.GetDirections(Origin.Position, Destination.Position, mod);
                        }
                    }
                    if (r == null || r.routes.Count() == 0)
                    {
                        await new MessageDialog(MultilingualHelpToolkit.GetString("StringNoWayToDestination", "Text")).ShowAsync();
                        return;
                    }
                    if (CurrentDrawed != null)
                    {
                        MapView.MapControl.MapElements.Remove(CurrentDrawed);
                    }
                    var route = DirectionsHelper.GetDirectionAsRoute(r.routes.FirstOrDefault(), (Color)Resources["SystemControlBackgroundAccentBrush"]);
                    MapView.MapControl.MapElements.Add(route);
                    var es = DirectionsHelper.GetTotalEstimatedTime(r.routes.FirstOrDefault());
                    var di = DirectionsHelper.GetDistance(r.routes.FirstOrDefault());
                    if (Mode == DirectionMode.transit)
                    {
                        foreach (var item in r.routes.FirstOrDefault().legs)
                        {
                            foreach (var item2 in item.steps)
                            {
                                if (item2.transit_details != null)
                                {
                                    var ico = RandomAccessStreamReference.CreateFromUri(new Uri("http:" + item2.transit_details.line.vehicle.icon));
                                    MapView.MapControl.MapElements.Add(new MapIcon()
                                    {
                                        Image = ico, Title = "arrival " + item2.transit_details.headsign, Location = new Geopoint(new BasicGeoposition()
                                        {
                                            Latitude = item2.transit_details.arrival_stop.location.lat, Longitude = item2.transit_details.arrival_stop.location.lng
                                        })
                                    });
                                    MapView.MapControl.MapElements.Add(new MapIcon()
                                    {
                                        Image = ico, Title = "departure  " + item2.transit_details.headsign, Location = new Geopoint(new BasicGeoposition()
                                        {
                                            Latitude = item2.transit_details.departure_stop.location.lat, Longitude = item2.transit_details.departure_stop.location.lng
                                        })
                                    });
                                }
                            }
                        }
                    }
                    await new MessageDialog($"{MultilingualHelpToolkit.GetString("StringDirectionCalculated", "Text")}".Replace("{di}", di).Replace("{es}", es)).ShowAsync();
                    //await new MessageDialog($"we calculate that the route is about {di} and takes about {es}").ShowAsync();
                    await MapView.MapControl.TryZoomToAsync(16);

                    MapView.MapControl.Center       = Origin;
                    MapView.MapControl.DesiredPitch = 45;
                    MapViewVM.ActiveNavigationMode  = true;
                    new DisplayRequest().RequestActive();
                }
                else
                {
                    await new MessageDialog(MultilingualHelpToolkit.GetString("StringSelectBothOriginAndDestination", "Text")).ShowAsync();
                }
            }
            catch (Exception ex)
            {
                //await new MessageDialog("error on DirectionFinder in Walking Mode" + Environment.NewLine + ex.Message).ShowAsync();
            }
        }
Exemplo n.º 57
0
        private void LineMouseLeave(object sender, MouseEventArgs e)
        {
            MapPolyline line = e.OriginalSource as MapPolyline;

            lineLabelLayer.Children.Remove(line.DataContext as FrameworkElement);
        }
Exemplo n.º 58
0
        //Fonction pour importer les Trajets d'un ficher .CSV
        private void Polyline_Import_Button(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                InitialDirectory = "c:\\",
                Filter           = "csv files (*.csv)|*.csv"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                try
                {
                    using (StreamReader sr = new StreamReader(openFileDialog.FileName))
                    {
                        string line = "";

                        while ((line = sr.ReadLine()) != null)
                        {
                            string[] list = Regex.Split(line, @";+");
                            //C'est que c'est un POI donc ajout du POI
                            if (list[2] != String.Empty)
                            {
                                Pushpin  pin         = new Pushpin();
                                Location pinLocation = new Location();

                                POI TmpPoi = new POI(Convert.ToDouble(list[0]), Convert.ToDouble(list[1]), list[2]);

                                pin.Tag = TmpPoi;
                                pinLocation.Latitude  = TmpPoi.Latitude;
                                pinLocation.Longitude = TmpPoi.Longitude;

                                pin.Location = pinLocation;

                                //Ajoute le pin a la carte
                                map.Children.Add(pin);

                                //Ajoute à la liste
                                User.Liste.Add(TmpPoi);
                            }

                            if (ListeTmp == null)
                            {
                                ListeTmp    = new List <Coordonnees>();
                                PolylineTpm = new MapPolyline
                                {
                                    Stroke          = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Blue),
                                    StrokeThickness = 3,
                                    Opacity         = 1,
                                    Locations       = new LocationCollection()
                                };
                            }
                            ListeTmp.Add(new Coordonnees(Convert.ToDouble(list[0]), Convert.ToDouble(list[1])));

                            PolylineTpm.Locations.Add(new Location(Convert.ToDouble(list[0]), Convert.ToDouble(list[1])));
                        }

                        Polyline TmpPolyline = new Polyline
                        {
                            Coordonnees = ListeTmp
                        };
                        TmpPolyline.Description = openFileDialog.SafeFileName;

                        //Ajoute à la liste
                        User.Liste.Add(TmpPolyline);
                        map.Children.Add(PolylineTpm);

                        PolylineTpm = null;
                        ListeTmp    = null;
                    }
                    StatBar.Text = "Path imported"; //Affichage dans la StatusBar
                }
                catch (Exception)
                {
                    ErrorWindow error = new ErrorWindow("The file could not be read");
                    error.ShowDialog(); //bloque la page
                }
            }
        }
Exemplo n.º 59
0
        //Ajouter un item
        private void AddItem(Location pinLocation)
        {
            if (POI_Box.IsSelected == true)
            {
                //La position du pin sur la carte
                Pushpin pin = new Pushpin();

                POI TmpPoi = new POI(pinLocation.Latitude, pinLocation.Longitude, "");

                OptPOI text = new OptPOI(TmpPoi);
                text.ShowDialog(); //bloque la page

                pin.Tag = TmpPoi;
                pinLocation.Latitude  = TmpPoi.Latitude;
                pinLocation.Longitude = TmpPoi.Longitude;

                pin.Location = pinLocation;

                //Ajoute le pin a la carte
                map.Children.Add(pin);

                //Ajoute à la liste
                User.Liste.Add(TmpPoi);
                StatBar.Text = "POI added"; //Affichage dans la StatusBar
            }

            if (Polyline_Box.IsSelected == true)
            {
                if (ListeTmp == null)
                {
                    ListeTmp    = new List <Coordonnees>();
                    PolylineTpm = new MapPolyline
                    {
                        Stroke          = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Blue),
                        StrokeThickness = 3,
                        Opacity         = 1,
                        Locations       = new LocationCollection()
                    };
                    map.Children.Add(PolylineTpm);
                }

                ListeTmp.Add(new Coordonnees(pinLocation.Latitude, pinLocation.Longitude));

                PolylineTpm.Locations.Add(new Location(pinLocation.Latitude, pinLocation.Longitude));

                if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
                {
                    Polyline TmpPolyline = new Polyline
                    {
                        Coordonnees = ListeTmp
                    };
                    OptPolyline text = new OptPolyline(TmpPolyline);
                    text.ShowDialog(); //bloque la page

                    //Ajoute à la liste
                    PolylineTpm.StrokeThickness = TmpPolyline.Epaisseur;
                    User.Liste.Add(TmpPolyline);
                    map.Children.Remove(PolylineTpm);
                    PolylineTpm.Stroke = new System.Windows.Media.SolidColorBrush(TmpPolyline.Couleur);
                    map.Children.Add(PolylineTpm);

                    PolylineTpm = null;
                    ListeTmp    = null;
                }
                StatBar.Text = "Polyline added"; //Affichage dans la StatusBar
            }

            if (Polygone_Box.IsSelected == true)
            {
                if (ListeTmp == null)
                {
                    ListeTmp   = new List <Coordonnees>();
                    PolygonTpm = new MapPolygon
                    {
                        Fill            = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.LightBlue),
                        Stroke          = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Blue),
                        StrokeThickness = 3,
                        Opacity         = 0.6,
                        Locations       = new LocationCollection()
                    };
                    map.Children.Add(PolygonTpm);
                }

                ListeTmp.Add(new Coordonnees(pinLocation.Latitude, pinLocation.Longitude));

                PolygonTpm.Locations.Add(new Location(pinLocation.Latitude, pinLocation.Longitude));

                if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
                {
                    Polygon TmpPolygon = new Polygon
                    {
                        Coordonnees = ListeTmp
                    };
                    OptPolygon text = new OptPolygon(TmpPolygon);
                    text.ShowDialog(); //bloque la page

                    //Ajoute à la liste
                    User.Liste.Add(TmpPolygon);
                    map.Children.Remove(PolygonTpm);
                    PolygonTpm.Fill    = new System.Windows.Media.SolidColorBrush(TmpPolygon.CouleurRemplissage);
                    PolygonTpm.Stroke  = new System.Windows.Media.SolidColorBrush(TmpPolygon.CouleurContour);
                    PolygonTpm.Opacity = TmpPolygon.Opacite;
                    map.Children.Add(PolygonTpm);

                    PolygonTpm = null;
                    ListeTmp   = null;
                }
                StatBar.Text = "Polygon added"; //Affichage dans la StatusBar
            }
        }
Exemplo n.º 60
-26
        public void SetAnimDash(PointCollection pc, ShapeLayer layer)
        {
            MapPolyline animDashLine = new MapPolyline()
            {
                MapStrokeThickness = 20,
                Points = pc,
                ScaleFactor = 0.2
            };

            animDashLine.Stroke = new SolidColorBrush(System.Windows.Media.Color.FromArgb(128, 255, 255, 255));
            animDashLine.StrokeLineJoin = PenLineJoin.Round;
            animDashLine.StrokeStartLineCap = PenLineCap.Flat;
            animDashLine.StrokeEndLineCap = PenLineCap.Triangle;
            animDashLine.StrokeDashCap = PenLineCap.Triangle;
            var dc = new DoubleCollection { 2, 2 };
            animDashLine.IsHitTestVisible = false;
            animDashLine.StrokeDashArray = dc;

            DoubleAnimation animation = new DoubleAnimation
            {
                From = 4,
                To = 0,
                FillBehavior = System.Windows.Media.Animation.FillBehavior.HoldEnd,
                RepeatBehavior = RepeatBehavior.Forever
            };

            var strokeStoryboard = new Storyboard();
            strokeStoryboard.Children.Add(animation);
            Storyboard.SetTargetProperty(animation, new PropertyPath("(Line.StrokeDashOffset)"));
            Storyboard.SetTarget(animation, animDashLine);
            strokeStoryboard.Begin();
            layer.Shapes.Add(animDashLine);
        }