Ejemplo n.º 1
0
        private void CalculateRoute()
        {
            try
            {
                var routeCalculator = new RouteCalculator(
                    CredentialsProvider,
                    To,
                    From,
                    Dispatcher,
                    result =>
                {
                    // Clear the route collection to have only one route at a time.
                    Routes.Clear();

                    // Create a new route based on route calculator result,
                    // and add the new route to the route collection.
                    var routeModel = new RouteModel(result.Result.RoutePath.Points);
                    Routes.Add(routeModel);

                    // Set the map to center on the new route.
                    var viewRect = LocationRect.CreateLocationRect(routeModel.Locations);
                    Map.SetView(viewRect);
                });

                // Display an error message in case of fault.
                routeCalculator.Error += r => MessageBox.Show(r.Reason);

                // Start the route calculation asynchronously.
                routeCalculator.CalculateAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public void LocationItemDistanceClusterer_ShouldRenderPinsInDefinedAmountOfTime()
        {
            // Arrange
            double zoomLevel = 10;

            var stopwatch          = new Stopwatch();
            int numberOfGeoObjects = 100000;
            int clusteringDistance = 50;
            var centerPoint        = new Position(47.05016819999999d, 8.309307200000034d);
            var visiblePins        = GenerateRandomTestGeoObjects(numberOfGeoObjects, centerPoint, zoomLevel).ToList();

            var boundingRectangle = LocationRect.CreateLocationRect(visiblePins.Select(x => x.Location));

            ILocationClusterer <IClusteredGeoObject> pushpinClusterer = new RectangularClusterer <IClusteredGeoObject>();

            // Act
            stopwatch.Start();
            var clusters = pushpinClusterer.Cluster(visiblePins, boundingRectangle, zoomLevel);

            stopwatch.Stop();

            // Assert
            pushpinClusterer.Should().NotBeNull();
            //pushpinClusterer.PushpinModels.Should().HaveCount(1); //not always
            //pushpinClusterer.PushpinModels.First().ClusterCount.Should().Be(19875);
            stopwatch.ElapsedMilliseconds.Should().BeLessOrEqualTo(50);
            this.output.WriteLine("Test duration: {0}ms", stopwatch.ElapsedMilliseconds);
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Center map code.
 /// </summary>
 private void CenterMap()
 {
     if (Pushpins != null)
     {
         var locations = Pushpins.Select(model => model.Location);
         LocationMap.SetView(LocationRect.CreateLocationRect(locations));
     }
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Standard WP7 method which is running always when user navigates to page.
        /// </summary>
        /// <param name="e">NavigationService argument</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            string action = string.Empty;

            if (NavigationContext.QueryString.TryGetValue("showPushpins", out action))
            {
                bool isGeoCoordinatesSet = ((App.AppDictionary["Pushpins"] as List <GPSEntity>) != null);
                if (Convert.ToBoolean(action) && isGeoCoordinatesSet)
                {
                    List <GeoCoordinate> allPinsLocation = new List <GeoCoordinate>();

                    foreach (var pinPosition in App.AppDictionary["Pushpins"] as List <GPSEntity> )
                    {
                        Pushpin pushpin = new Pushpin();
                        pushpin.Location = pinPosition.Location;
                        pushpin.Content  = pinPosition.Title;
                        Map.Children.Add(pushpin);
                        allPinsLocation.Add(pinPosition.Location);
                    }

                    Map.SetView(LocationRect.CreateLocationRect(allPinsLocation));
                }
            }
            else if (!string.IsNullOrEmpty(App.AppDictionary["Latitude"] as String) && !string.IsNullOrEmpty(App.AppDictionary["Longitude"] as String) && !string.IsNullOrEmpty(App.AppDictionary["Radius"] as String))
            {
                _latitude  = App.AppDictionary["Latitude"] as String;
                _longitude = App.AppDictionary["Longitude"] as String;
                _radius    = App.AppDictionary["Radius"] as String;

                if (Math.Abs(Convert.ToDouble(_latitude)) <= 90 && (Math.Abs(Convert.ToDouble(_longitude)) <= 180))
                {
                    _viewModel.Map.StartLocation = new GeoCoordinate(Convert.ToDouble(_latitude), Convert.ToDouble(_longitude));
                    double resolution = 156543.04 * Math.Cos(Convert.ToDouble(_latitude)) / Math.Pow(2, Map.ZoomLevel); // resolution in m/px
                    double distance   = Math.Abs(Convert.ToDouble(_radius) / resolution);                               // distance in px
                    Point  point      = GetPoint(_viewModel.Map.StartLocation);
                    _viewModel.Map.StopLocation = GetCoords(new Point(point.X, point.Y - distance));
                    _isLoadedCoordinates        = true;

                    // for right zoom level
                    while (distance < 200)
                    {
                        _zoom++;
                        distance *= 2;
                    }

                    DrawCircle(_zoom);
                }
            }

            _isSelecting  = false;
            Map.IsEnabled = true;
        }
Ejemplo n.º 5
0
        //检测到位置更改时
        //当定位服务已准备就绪并接收数据时,它将开始引发 PositionChanged 事件
        void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs <GeoCoordinate> e)
        {
            Location location = new Location();//实例化一个位置位置类的实例

            //将当前的经纬度值赋给位置对象
            location.Latitude  = e.Position.Location.Latitude;
            location.Longitude = e.Position.Location.Longitude;

            thislocation = location;

            Pushpin pushpin = new Pushpin();//实例化一个图钉实例

            pushpin.Content  = "You";
            pushpin.Location = location;

            Location patientlocation = new Location();

            //patientlocation.Latitude = 40.106;
            //patientlocation.Longitude = 116.3333;


            patientlocation.Latitude  = System.Convert.ToDouble(Patientlatitude);
            patientlocation.Longitude = System.Convert.ToDouble(PatientLongitude);


            Pushpin patientpushin = new Pushpin();

            patientpushin.Content  = "Patient";
            patientpushin.Location = patientlocation;
            this.map1.Children.Add(patientpushin);

            MapPolyline line = new MapPolyline();

            line.Locations = new LocationCollection {
                location, patientlocation
            };



            this.map1.Mode = map1.Mode = new RoadMode();
            this.map1.Children.Add(pushpin);//将图钉显示在地图上

            LocationRect rect = LocationRect.CreateLocationRect(line.Locations);

            map1.SetView(rect);


            this.map1.ZoomLevel = 12;
            //    this.map1.SetView(location, 12);//缩放界别为10(1-16),始终将当前位置位于地图中心
        }
        async protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            var   storeId = NavigationContext.QueryString["storeId"];
            Store store   = App.ViewModel.Stores.Where(item => item.Id == storeId).FirstOrDefault();

            if (store == null)
            {
                store = App.ViewModel.SelectedStore;
            }
            if (store == null)
            {
                store = App.ViewModel.SelectedOffer.Store;
            }

            DataContext = store;

            base.OnNavigatedTo(e);

            var routeApi = new RouteAPIHelper();
            var from     = new GeoCoordinate
            {
                Latitude  = App.ViewModel.UserViewModel.Location.Latitude,
                Longitude = App.ViewModel.UserViewModel.Location.Longitude
            };
            var to = new GeoCoordinate
            {
                Latitude  = double.Parse(store.Latitude),
                Longitude = double.Parse(store.Longitude)
            };
            var route = await routeApi.GetRouteAsync(from, to);

            if (route != null)
            {
                RouteLayer.Children.Add(route);
                RouteMap.SetView(LocationRect.CreateLocationRect(route.Locations));
            }

            RouteMap.Children.Add(new Pushpin()
            {
                Location = from, Content = "o"
            });
            RouteMap.Children.Add(new Pushpin()
            {
                Location = to, Content = store.Dealer.Name
            });
        }
        private void UpdateMap(GeoCoordinate location)
        {
            if (previous.IsUnknown)
            {
                Pushpin startPin = CreatePushpin(location, Colors.Green);
                routeLayer.AddChild(startPin, startPin.Location);
            }

            pinLayer.Children.Clear();
            Pushpin pin = CreatePushpin(location, Colors.Blue, "You");

            pinLayer.AddChild(pin, pin.Location);

            mapControl.Center = location;
            mapControl.SetView(LocationRect.CreateLocationRect(routeLine.Locations));
            routeLine.Locations.Add(location);
        }
Ejemplo n.º 8
0
        private void DisplayRoute(TripMessage tripMessage)
        {
            try
            {
                foreach (MapPolyline line in routes)
                {
                    Map.Children.Remove(line);
                }
            }
            catch (Exception) { }

            if (tripMessage.Trip.BoundingBoxBottomRight != null && tripMessage.Trip.BoundingBoxTopLeft != null)
            {
                Map.SetView(LocationRect.CreateLocationRect(tripMessage.Trip.BoundingBoxBottomRight.GeoCoordinate, tripMessage.Trip.BoundingBoxTopLeft.GeoCoordinate));
            }
            var trips = tripMessage.Trip.TripRoutes.ToList();

            foreach (TripRoute tripRoute in tripMessage.Trip.TripRoutes)
            {
                if (tripRoute.Coordinates.Count() >= 2)
                {
                    MapPolyline route = new MapPolyline();
                    routes.Add(route);
                    route.Stroke          = ThemeColourConverter.GetBrushFromHex(tripRoute.Colour);
                    route.StrokeThickness = 9;
                    route.Locations       = new LocationCollection();

                    MapPolyline routeBlack = new MapPolyline();
                    routes.Add(routeBlack);
                    routeBlack.Stroke          = ThemeColourConverter.GetBrushFromHex(ThemeColourConverter.Black);
                    routeBlack.StrokeThickness = 11;
                    routeBlack.Locations       = new LocationCollection();

                    foreach (Coordinate coordinate in tripRoute.Coordinates)
                    {
                        route.Locations.Add(coordinate.GeoCoordinate);
                        routeBlack.Locations.Add(coordinate.GeoCoordinate);
                    }

                    Map.Children.Insert(0, route);
                    Map.Children.Insert(0, routeBlack);
                }
            }
        }
Ejemplo n.º 9
0
        private static void RouteChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            var routeMapControl = dependencyObject as MapRouteControl;

            if (routeMapControl == null)
            {
                return;
            }
            var route = dependencyPropertyChangedEventArgs.NewValue as RouteModel;

            if (route == null)
            {
                return;
            }

            var viewRect = LocationRect.CreateLocationRect(route.Locations);

            routeMapControl.ParentMap.SetView(viewRect);
        }
Ejemplo n.º 10
0
        void pin_Tap(object sender1, System.Windows.Input.GestureEventArgs e1)
        {
            List <GeoCoordinate> locations = new List <GeoCoordinate>();

            locations.Add(currentLocation);
            Pushpin senderAs = sender1 as Pushpin;

            locations.Add(senderAs.Location);
            destination = senderAs;
            DestinationPoint.Children.Clear();
            DestinationPoint.Children.Add(destination);

            RouteServiceClient routeService = new RouteServiceClient("BasicHttpBinding_IRouteService");

            routeService.CalculateRouteCompleted += (sender, e) =>
            {
                DrawRoute(e);
            };

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

            routeService.CalculateRouteAsync(new RouteRequest()
            {
                Credentials = new Credentials()
                {
                    ApplicationId = LocationManager.bingApiKey
                },
                Options = new RouteOptions()
                {
                    RoutePathType = RoutePathType.Points
                },
                Waypoints = new ObservableCollection <Waypoint>(
                    locations.Select(x => new Waypoint()
                {
                    Location = new Microsoft.Phone.Controls.Maps.Platform.Location()
                    {
                        Latitude = x.Latitude, Longitude = x.Longitude
                    }
                }))
            });
            SetDriveMode(true);
        }
        private static void UpdateItemsSource(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var map = d as Map;
            var newPushPinCollection = e.NewValue as IEnumerable <IClusteredGeoObject>;

            if (newPushPinCollection != null && newPushPinCollection.Any() && map != null)
            {
                // Read dependency properties
                var pushpinTemplate        = GetPushpinTemplate(d);
                var clusterPushpinTemplate = GetClusterTemplate(d);
                ////var clusteringDistance = GetClusteringDistance(d);

                // Perform clustering
                var visibleAreaTopLeft     = map.ConvertViewportPointToGeoCoordinate(new Point(0, 0));
                var visibleAreaBottomRight = map.ConvertViewportPointToGeoCoordinate(new Point(map.ActualWidth, map.ActualHeight));
                var boundingRectangle      = LocationRect.CreateLocationRect(visibleAreaTopLeft.ToPosition(), visibleAreaBottomRight.ToPosition());

                //var clusterer = new SectorClusterer<IClusteredGeoObject>();
                var clusterer = new RectangularClusterer <IClusteredGeoObject>();

                //var stopwatch = new Stopwatch();
                //stopwatch.Start();
                IEnumerable <IClusteredLocation <IClusteredGeoObject> > clusteredLocations = clusterer.Cluster(newPushPinCollection, boundingRectangle, map.ZoomLevel);
                if (map.ZoomLevel >= 18)
                {
                    clusteredLocations = clusteredLocations.SelectMany(x => x.ClusteredItems).Select(
                        clusteredGeoObject =>
                    {
                        var rect = new ClusteredLocationRect <IClusteredGeoObject>(boundingRectangle);
                        rect.Add(clusteredGeoObject);
                        return(rect);
                    }).ToList();
                }

                //stopwatch.Stop();
                //Console.WriteLine("UPDATED CLUSTER IN {0}ms", stopwatch.ElapsedMilliseconds);

                // Update map on UI
                map.Dispatcher.BeginInvoke(
                    () =>
                {
                    // Remove layer which hosts pushpins
                    var clusteredPushpinLayer = map.Layers.FirstOrDefault(x => x.All(y => y.Content is IClusteredLocation <IClusteredGeoObject>));
                    map.Layers.Remove(clusteredPushpinLayer);

                    // Create new layer
                    var layer = new MapLayer();

                    // The descending-by-latitude ordering makes sure the pins are not overlapping eachother
                    Position lastGeoCoordinate = Position.Unknown;
                    foreach (var pushPinModel in clusteredLocations.OrderByDescending(p => p.Location.Latitude))
                    {
                        var mapOverlay = new MapOverlay
                        {
                            GeoCoordinate = new GeoCoordinate(pushPinModel.Location.Latitude, pushPinModel.Location.Longitude),
                            Content       = pushPinModel
                        };

                        if (pushPinModel.IsClustered)
                        {
                            mapOverlay.ContentTemplate = clusterPushpinTemplate;
                            mapOverlay.PositionOrigin  = new System.Windows.Point(0.5, 0.5);
                        }
                        else
                        {
                            mapOverlay.ContentTemplate = pushpinTemplate;

                            // In case two/more pins have the same GPS position, we add a random offset to longitude/latitude.
                            if (Math.Abs(pushPinModel.Location.Latitude - lastGeoCoordinate.Latitude) < 0.00005 &&
                                Math.Abs(pushPinModel.Location.Longitude - lastGeoCoordinate.Longitude) < 0.00005)
                            {
                                mapOverlay.GeoCoordinate = lastGeoCoordinate.WithRandomOffset().ToGeoCoordinate();
                            }
                            lastGeoCoordinate = pushPinModel.Location;
                        }

                        layer.Add(mapOverlay);
                    }

                    // Finally, add all items (pushpins, clusters and current location) to the map.
                    if (layer.Any())
                    {
                        map.Layers.Insert(ItemsSourceLayerIndex, layer);
                    }
                });
            }
        }
Ejemplo n.º 12
0
        private void busService_GetPathCompleted(object sender, localService.GetPathCompletedEventArgs e)
        {
            pathList = e.Result;
            startLocation.Latitude  = pathList[0].StartLatitude;
            startLocation.Longitude = pathList[0].StartLongitude;
            endLocation.Latitude    = pathList[pathList.Count - 1].EndLatitude;
            endLocation.Longitude   = pathList[pathList.Count - 1].EndLongitude;

            for (int i = 0; i < pathList.Count; i++)
            {
                if (pathList[i].BusServiceNum != 0)
                {
                    localService.Service1Client transitPath = new localService.Service1Client();
                    transitPath.GetBusStopAsync(Convert.ToInt32(pathList[i].BusServiceNum), pathList[i].StartLatitude, pathList[i].StartLongitude, pathList[i].EndLatitude, pathList[i].EndLongitude);
                    transitPath.GetBusStopCompleted += new EventHandler <localService.GetBusStopCompletedEventArgs>(transitPath_GetBusStopCompleted);

                    previous           = new Location();
                    previous.Latitude  = pathList[i].StartLatitude;
                    previous.Longitude = pathList[i].StartLongitude;

                    pinLayer.Children.Add(ppM.createPushPin(pathList[i].Mode, previous, pathList[i].Sequence, pathList[i].Location));

                    current           = new Location();
                    current.Latitude  = pathList[i].EndLatitude;
                    current.Longitude = pathList[i].EndLongitude;

                    pinLayer.Children.Add(ppM.createPushPin(pathList[i].Mode, current, pathList[i].Sequence, pathList[i].Location));
                }

                else
                {
                    if (pathList[i].Mode.Equals("Walk"))
                    {
                        routeLine = new MapPolyline();
                        System.Windows.Media.Color routeColor = Colors.Red;
                        routeLine.Locations = new LocationCollection();
                        SolidColorBrush routeBrush = new SolidColorBrush(routeColor);
                        routeLine.Stroke          = routeBrush;
                        routeLine.Opacity         = 0.65;
                        routeLine.StrokeThickness = 5.0;
                        myRouteLayer.Children.Add(routeLine);
                    }
                    else
                    {
                        routeLine = new MapPolyline();
                        System.Windows.Media.Color routeColor = Colors.Green;
                        routeLine.Locations = new LocationCollection();
                        SolidColorBrush routeBrush = new SolidColorBrush(routeColor);
                        routeLine.Stroke          = routeBrush;
                        routeLine.Opacity         = 0.65;
                        routeLine.StrokeThickness = 5.0;
                        myRouteLayer.Children.Add(routeLine);
                    }

                    previous           = new Location();
                    previous.Latitude  = pathList[i].StartLatitude;
                    previous.Longitude = pathList[i].StartLongitude;
                    routeLine.Locations.Add(previous);
                    pinLayer.Children.Add(ppM.createPushPin(pathList[i].Mode, previous, pathList[i].Sequence, pathList[i].Location));

                    current           = new Location();
                    current.Latitude  = pathList[i].EndLatitude;
                    current.Longitude = pathList[i].EndLongitude;
                    routeLine.Locations.Add(current);
                }
                if (i == pathList.Count - 1)
                {
                    var rect = LocationRect.CreateLocationRect(startLocation, endLocation);
                    myMap.SetView(rect);
                }
            }
        }