Ejemplo n.º 1
0
        /// <summary>
        /// Updates each map item in the set, setting whether it's in the view specified by the given
        /// location rect and zoom level.
        /// </summary>
        /// <param name="locationRect">The location rect component of the view.</param>
        /// <param name="zoomLevel">The zoom level component of the view.</param>
        public override void UpdateVisibilty(LocationRect locationRect, int zoomLevel)
        {
            // If the location rect has no area...
            if (locationRect.Width <= 0 || locationRect.Height <= 0)
            {
                // ...then clear the visibility on each map item.
                foreach (MapItem item in _Items)
                {
                    item.InView = false;
                }
            }
            else
            {
                // ...otherwise, do the normal visibility update.
                NormalizedMercatorRect queryRect = new NormalizedMercatorRect(locationRect);

                foreach (MapItem item in _Items)
                {
                    bool inView = false;

                    if (zoomLevel <= item.MaxZoomLevel && zoomLevel >= item.MinZoomLevel)
                    {
                        NormalizedMercatorRect itemRect = item.BoundingRectAtZoomLevel(zoomLevel);

                        if (queryRect.Intersects(itemRect))
                        {
                            inView = true;
                        }
                    }

                    item.InView = inView;
                }
            }
        }
Ejemplo n.º 2
0
        public static List<LocationResult> findLocations(String query, String authKey, LocationRect usermapView = null)
        {
            List<LocationResult> result = new List<LocationResult>();

            if (String.IsNullOrEmpty(query) || String.IsNullOrWhiteSpace(query)) return (result);

            String location = "?query=" + query.Trim();

            String culture = "&culture=en-GB";

            String output = "&o=xml";

            string userMapView = "";

            if (usermapView != null)
            {
                userMapView = "&usermapView=" +
                    usermapView.South.ToString(CultureInfo.CreateSpecificCulture("en-GB")) + "," +
                    usermapView.West.ToString(CultureInfo.CreateSpecificCulture("en-GB")) + "," +
                    usermapView.North.ToString(CultureInfo.CreateSpecificCulture("en-GB")) + "," +
                    usermapView.East.ToString(CultureInfo.CreateSpecificCulture("en-GB"));
            }
                       
            string key = "&key=" + authKey;

            string geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations" + location + culture + output + userMapView + key;

            //Make the request and get the response
            XmlDocument geocodeResponse = GetXmlResponse(geocodeRequest);

            XmlElement root = geocodeResponse.DocumentElement;

            XmlNamespaceManager nsmgr = new XmlNamespaceManager(geocodeResponse.NameTable);
            nsmgr.AddNamespace("ns", "http://schemas.microsoft.com/search/local/ws/rest/v1");

            if (int.Parse(root.SelectSingleNode("//ns:EstimatedTotal", nsmgr).InnerText) > 0)
            {
                XmlNodeList resources = root.SelectNodes("//ns:Location", nsmgr);

                foreach (XmlNode resource in resources)
                {
                    result.Add(new LocationResult(resource, nsmgr));
                }

                if (usermapView != null)
                {
                    // sort on distance from usermap center
                    result.Sort(new Comparison<LocationResult>((a, b) => a.getSqrdDistToLocation(usermapView.Center).CompareTo(b.getSqrdDistToLocation(usermapView.Center))));
                }
            }
            else
            {
                // no results found
                SystemSounds.Hand.Play();
            }

            return (result);
        }
Ejemplo n.º 3
0
 public void GetFotos(LocationRect rect, MapLayer phtosLayer, CustomMap mp)
 {
     photosLayer = null;
     currentMap = null;
     currentMap = mp;
     photosLayer = phtosLayer;
     GetPhotosFlickr(rect);
     GetFotosPanoramico(rect);
 }
Ejemplo n.º 4
0
 private void AutoFocusMap()
 {
     var bounds = new LocationRect(
         coordinates.Max((p) => p.Latitude),
         coordinates.Min((p) => p.Longitude),
         coordinates.Min((p) => p.Latitude),
         coordinates.Max((p) => p.Longitude));
     pictureMap.SetView(bounds);
 }
Ejemplo n.º 5
0
        public MainPage()
        {
            InitializeComponent();

            LocationRect usa = new LocationRect(
              new Location(50, -120),
              new Location(30, -70));
            this.visualizationLayer.ItemsSource = this.GeneratePoiCollection(50, usa);
        }
 public static LocationCollection LocationRectToLocationCollection(LocationRect locationRect)
 {
     var locations = new LocationCollection
                         {
                             locationRect.Northwest,
                             locationRect.Southwest,
                             locationRect.Southeast,
                             locationRect.Northeast,
                             locationRect.Northwest
                         };
     return locations;
 }
Ejemplo n.º 7
0
 private void GetFotosPanoramico(LocationRect bbox)
 {
     PanoramioNet.BoundaryBox PanoramioOptions = new PanoramioNet.BoundaryBox
     {
         MaximumLatitude = bbox.North,
         MinimumLatitude = bbox.South,
         MaximumLongitude = bbox.East,
         MinimumLongitude = bbox.West
     };
     Panoramio PanoramioAPI = new Panoramio();
     PanoramioAPI.GetPhotoCollectionCompleted += new Panoramio.PhotoCollectionHandler(_panoramioAPI_GetPhotoCollectionCompleted);
     PanoramioAPI.GetPhotos(PanoramioOptions, "square", 0, 10);
 }
        public GeoLocationPickerView()
        {
            InitializeComponent();        
            map.CredentialsProvider = new ApplicationIdCredentialsProvider(BingMapsKey.Key);
            map.PreviewMouseWheel += map_PreviewMouseWheel;
                     
            map.CredentialsProvider.GetCredentials((c) =>
            {              
                BingMapsKey.SessionKey= c.ApplicationId;
            });

            ResetView = new LocationRect(Location.MaxLatitude,Location.MinLongitude,Location.MinLatitude,Location.MaxLongitude);
        }
Ejemplo n.º 9
0
        public static LocationRect AsLocationRect(this BoundingBox bb)
        {
            if (bb == null)
            {
                throw new ArgumentNullException("bb");
            }

            var locRect = new LocationRect(bb.NorthLatitude, bb.WestLongitude, bb.SouthLatitude, bb.EastLongitude);
            locRect.Northeast = FixGeoCoordinate(locRect.Northeast);
            locRect.Northwest = FixGeoCoordinate(locRect.Northwest);
            locRect.Southeast = FixGeoCoordinate(locRect.Southeast);
            locRect.Southwest = FixGeoCoordinate(locRect.Southwest);
            return locRect;
        }
Ejemplo n.º 10
0
        private ObservableCollection<MapItem> GeneratePoiCollection(int count, LocationRect region)
        {
            ObservableCollection<MapItem> data = new ObservableCollection<MapItem>();

            for (int i = 0; i < count; i++)
            {
                Location baseLocation = new Location(
                        region.North - rnd.NextDouble() * region.GeoSize.Height,
                        region.West + rnd.NextDouble() * region.GeoSize.Width);
                this.GenerateMapItem(data, baseLocation, i);
            }

            return data;
        }
Ejemplo n.º 11
0
        public MainWindow()
        {
            InitializeComponent();

            LocationRect rect = new LocationRect(new Location(39, -120), new Location(32, -113));
            ObservableCollection<Location> items = this.CreatePointsInRect(1000, rect);

            ClusteredDataSource dataSource = new ClusteredDataSource();
            dataSource.GenerateClustersOnZoom = true;
            dataSource.ItemTemplate = this.Resources["ClusteredItemTemplate"] as DataTemplate;
            dataSource.ClusterItemTemplate = this.Resources["ClusterTemplate"] as DataTemplate;
            dataSource.ItemsSource = items;

            this.informationLayer.ClusteredDataSource = dataSource;
        }
Ejemplo n.º 12
0
        private ObservableCollection<Location> CreatePointsInRect(int count, LocationRect rect)
        {
            ObservableCollection<Location> collection = new ObservableCollection<Location>();

            rect.MapControl = this.radMap;

            for (int i = 0; i < count; i++)
            {
                Location loc = new Location(
                    rect.North - rect.GeoSize.Height * rnd.NextDouble(),
                    rect.West + rect.GeoSize.Width * rnd.NextDouble());

                collection.Add(loc);
            }

            return collection;
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Updates each map item in the set, setting whether it's in the view specified by the given
        /// location rect and zoom level.
        /// </summary>
        /// <param name="locationRect">The location rect component of the view.</param>
        /// <param name="zoomLevel">The zoom level component of the view.</param>
        public override void UpdateVisibilty(LocationRect locationRect, int zoomLevel)
        {
            Debug.Assert(_NewVisibleItems.Count == 0);

            // If the location rect has no area...
            if (locationRect.Width <= 0 || locationRect.Height <= 0)
            {
                // ...then clear the visibility on each map item.

                foreach (MapItem item in _VisibleItems)
                {
                    item.InView = false;
                }

                _VisibleItems.Clear();
            }
            else
            {
                // ... otherwise, do the normal visibility update.

                foreach (MapItem item in _Items.IntersectingItems(new NormalizedMercatorRect(locationRect), zoomLevel))
                {
                    _NewVisibleItems.Add(item);
                }

                _VisibleItems.ExceptWith(_NewVisibleItems);

                foreach (MapItem item in _VisibleItems)
                {
                    item.InView = false;
                }

                foreach (MapItem item in _NewVisibleItems)
                {
                    item.InView = true;
                }

                var temp = _VisibleItems;
                _VisibleItems = _NewVisibleItems;
                _NewVisibleItems = temp;
                _NewVisibleItems.Clear();
            }
        }
Ejemplo n.º 14
0
        private async void SetUpMap()
        {
            LocationCollection locations = new LocationCollection();
            foreach (var station in this.Stations)
            {
                Location location = new Location() { 
                    Latitude = station.Latitude,
                    Longitude = station.Longitude
                };

                locations.Add(location);
                DrawPin.SetStationPin(location, this.Map, station);
            }

            try
            {
                Data.LocationProvider.Location locator = new Data.LocationProvider.Location();
                Point currentLocation = await locator.CurrentPosition;

                if (currentLocation != null)
                {
                    Location myLocation = new Location(currentLocation.Latitude, currentLocation.Longitude);
                    string myCity = await GetCityByLocation(myLocation);
                    DrawPin.SetMyLocationPin(myLocation, this.Map);
                    if (myCity.Contains("London"))
                    {
                        locations.Add(myLocation);
                    }
                    LocationRect mapRectangle = new LocationRect(locations);
                    this.Map.SetView(mapRectangle);
                }
                else
                {
                    Notification.ShowMessage("Sorry! Couldn't get your position! No relevant information can be provided!");
                }
            }
            catch (Exception)
            {
                Notification.ShowMessage("Sorry! Could not load data! Try to reconnect to Internet and then press Refresh!");
            }
        }
Ejemplo n.º 15
0
        public void ItemsRequest(object sender, ItemsRequestEventArgs e)
        {
            List<object> items = new List<object>();
            double minZoom = e.MinZoom;
            Location upperLeft = e.UpperLeft;
            Location lowerRight = e.LowerRight;
            HotSpot centerSpot = new HotSpot();
            centerSpot.X = 0.5;
            centerSpot.Y = 0.5;
            Location bulgariaLocation = new Location(42.7669999748468, 25.2819999307394);
            LocationRect currentRegion = new LocationRect(upperLeft, lowerRight);

            if (currentRegion.Contains(bulgariaLocation))
            {
                if (minZoom == 3)
                {
                    Ellipse ellipse = new Ellipse();
                    ellipse.Width = 15;
                    ellipse.Height = 15;
                    ellipse.Fill = new SolidColorBrush(Colors.Red);
                    ellipse.SetValue(MapLayer.LocationProperty, bulgariaLocation);
                    MapLayer.SetHotSpot(ellipse, centerSpot);
                    ToolTipService.SetToolTip(ellipse, "Bulgaria");
                    items.Add(ellipse);
                }
                else if (minZoom == 6)
                {
                    Ellipse sofiaEllipse = new Ellipse();
                    sofiaEllipse.Width = 20;
                    sofiaEllipse.Height = 20;
                    sofiaEllipse.Stroke = new SolidColorBrush(Colors.Red);
                    sofiaEllipse.Fill = new SolidColorBrush(Colors.Transparent);
                    sofiaEllipse.StrokeThickness = 3;
                    sofiaEllipse.SetValue(MapLayer.LocationProperty, new Location(42.6957539183824, 23.3327663758679));
                    MapLayer.SetHotSpot(sofiaEllipse, centerSpot);
                    ToolTipService.SetToolTip(sofiaEllipse, "Sofia");
                    items.Add(sofiaEllipse);
                }
            }
            e.CompleteItemsRequest(items);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Calculate rectanble bounding a location.
        /// </summary>
        public LocationRect BoundingRectangle(GeoCoordinate center, double d)
        {
            LocationRect lr = new LocationRect();
            double lat1 = center.Latitude * RadPerDeg;
            double lon1 = center.Longitude * RadPerDeg;
            double dOverR = d / R;

              //          var lat2 = Math.asin(Math.sin(lat1) * Math.cos(d / R) +    Math.cos(lat1) * Math.sin(d / R) * Math.cos(brng));

            lr.North = Math.Asin(Math.Sin(lat1) * Math.Cos(dOverR) + Math.Cos(lat1) * Math.Sin(dOverR) * Math.Cos(North));
            lr.South = Math.Asin(Math.Sin(lat1) * Math.Cos(dOverR) + Math.Cos(lat1) * Math.Sin(dOverR) * Math.Cos(South));
            lr.East = lon1 + Math.Atan2(Math.Sin(East) * Math.Sin(dOverR) * Math.Cos(lat1), Math.Cos(dOverR) - Math.Sin(lat1) * Math.Sin(lat1));
            lr.West = lon1 + Math.Atan2(Math.Sin(West) * Math.Sin(dOverR) * Math.Cos(lat1), Math.Cos(dOverR) - Math.Sin(lat1) * Math.Sin(lat1));

            lr.North /= RadPerDeg;
            lr.South /= RadPerDeg;
            lr.East /= RadPerDeg;
            lr.West /= RadPerDeg;

            return lr;
        }
Ejemplo n.º 17
0
        public void LoadMap()
        {
            ActivityViewModel vm = this.DataContext as ActivityViewModel;

            MapPolyline line = new MapPolyline();
            var locations = new LocationCollection();

            foreach (var waypoint in vm.ActivityGpsData.Waypoints)
                locations.Add(new Location(Convert.ToDouble(waypoint.Latitude), Convert.ToDouble(waypoint.Longitude), Convert.ToDouble(waypoint.Elevation)));

            line.Locations = locations;
            line.StrokeThickness = 3;
            line.Stroke = new SolidColorBrush(Colors.Red);
            map.Children.Add(line);

            map.Loaded += (s, e) =>
            {
                LocationRect boundingBox = new LocationRect(locations);
                map.SetView(boundingBox);
            };
        }
        private static Location CoerceLocation(Location locationToCoerce, LocationRect screenBounds, LocationRect shapeBounds)
        {
            if (locationToCoerce.Longitude < shapeBounds.East - (screenBounds.East - screenBounds.West) / 2)
            {
                locationToCoerce.Longitude = shapeBounds.East - (screenBounds.East - screenBounds.West) / 2;
            }
            else if (locationToCoerce.Longitude > shapeBounds.West + (screenBounds.East - screenBounds.West) / 2)
            {
                locationToCoerce.Longitude = shapeBounds.West + (screenBounds.East - screenBounds.West) / 2;
            }

            if (locationToCoerce.Latitude < shapeBounds.North - (screenBounds.North - screenBounds.South) / 2)
            {
                locationToCoerce.Latitude = shapeBounds.North - (screenBounds.North - screenBounds.South) / 2;
            }
            else if (locationToCoerce.Latitude > shapeBounds.South + (screenBounds.North - screenBounds.South) / 2)
            {
                locationToCoerce.Latitude = shapeBounds.South + (screenBounds.North - screenBounds.South) / 2;
            }

            return locationToCoerce;
        }
Ejemplo n.º 19
0
        public LocationResult(XmlNode location, XmlNamespaceManager nsmgr)
        {
           
            Name = location.SelectSingleNode("ns:Name",nsmgr).InnerText;
       
            string latStr = location.SelectSingleNode("ns:Point/ns:Latitude",nsmgr).InnerText;
            string lonStr = location.SelectSingleNode("ns:Point/ns:Longitude", nsmgr).InnerText;

            double lat = double.Parse(latStr, CultureInfo.InvariantCulture);
            double lon = double.Parse(lonStr, CultureInfo.InvariantCulture);
            
            Geotag = new Location(lat, lon);

            string southLat = location.SelectSingleNode("ns:BoundingBox/ns:SouthLatitude", nsmgr).InnerText;
            string westLon = location.SelectSingleNode("ns:BoundingBox/ns:WestLongitude", nsmgr).InnerText;
            string northLat = location.SelectSingleNode("ns:BoundingBox/ns:NorthLatitude", nsmgr).InnerText;
            string eastLon = location.SelectSingleNode("ns:BoundingBox/ns:EastLongitude", nsmgr).InnerText;

            Location corner1 = new Location(double.Parse(southLat, CultureInfo.InvariantCulture),double.Parse(westLon, CultureInfo.InvariantCulture));
            Location corner2 = new Location(double.Parse(northLat, CultureInfo.InvariantCulture),double.Parse(eastLon, CultureInfo.InvariantCulture));

            BoundingBox = new LocationRect(corner1,corner2);
           
        }
Ejemplo n.º 20
0
        private bool clusterObjects(BackgroundWorker worker, IList <MapLayerObject> objectsInView, int zoomLevel, LocationRect bounds)
        {
            //step one, get list of those to be clustered and reset their cluster status
            var clusterableMapLayerObjects = new List <IClusterable>();

            foreach (var layerObject in objectsInView)
            {
                if (layerObject.Element is IClusterable)
                {
                    var clusterable = ((IClusterable)layerObject.Element);
                    clusterable.IsCluster   = false;
                    clusterable.IsClustered = false;
                    clusterable.ClusteredElements.Clear();
                    layerObject.ToBeRendered = false;
                    clusterableMapLayerObjects.Add(clusterable);
                }
            }

            //quick exit if nothing to cluster
            if (clusterableMapLayerObjects.Count == 0)
            {
                return(true);
            }

            //exit loop if thread cancelled
            if (worker != null && worker.CancellationPending)
            {
                return(false);
            }

            //step 2 apply the clustering algorithm of your choice here.
            //Note you want an algorithm that returns consistant results or else things shift to much

            //if < 2500 items we can use the QT clustering, slow but accurate
            if (objectsInView.Count < 2500)
            {
                if (!QTCluster(clusterableMapLayerObjects, worker, zoomLevel))
                {
                    return(false);
                }
            }
            else
            {
                //else fall back to simple grid - fast but snaps to a predefined grid which looks average.
                if (!GridCluster(clusterableMapLayerObjects, worker, zoomLevel, bounds))
                {
                    return(false);
                }
            }

            //step three, set clusters and singles to be visible
            foreach (var layerObject in objectsInView)
            {
                if (layerObject.Element is IClusterable)
                {
                    if (!((IClusterable)layerObject.Element).IsClustered)
                    {
                        layerObject.ToBeRendered = true;
                    }
                }
            }

            //step four remove items no longer in view
            return(removeItemsNotInView(worker, objectsInView, false));
        }
Ejemplo n.º 21
0
        private void SetBestView(InformationLayer layer)
        {
            LocationRect bestView = layer.GetBestView(layer.Items.Cast <object>());

            RadMap1.SetView(bestView);
        }
Ejemplo n.º 22
0
        private void ShowImage(int imageIndex)
        {
            // Check for potential error
            if (this.selectedImages.Count <= imageIndex || imageIndex < 0)
            {
                this.ReturnToMap();
                return;
            }

            ImageAtLocation image = this.selectedImages[imageIndex];

            if (this.preloadedImages != null && this.preloadedImages[imageIndex] != null)
            {
                currentImage.Source = this.preloadedImages[imageIndex];
            }
            else
            {
                BitmapImage b1 = new BitmapImage();
                b1.BeginInit();
                b1.CacheOption       = BitmapCacheOption.Default;
                b1.UriSource         = new Uri(image.ImagePath, UriKind.RelativeOrAbsolute);
                b1.DecodePixelHeight = 800;
                b1.EndInit();
                b1.Freeze();
                currentImage.Source = b1;

                if (this.preloadedImages != null && imageIndex == 0)
                {
                    this.preloadedImages[0] = b1;
                }
            }

            this.imageCounter.Text  = (imageIndex + 1) + "/" + this.selectedImages.Count;
            this.ImageFileName.Text = System.IO.Path.GetFileName(image.ImagePath);
            this.ImageSaveDate.Text = "";
            this.ImageTaken.Text    = image.TimeImageTaken.ToString(App.RegionalCulture);
            this.Creator.Text       = image.Creator.ToString();

            // Zoom the inner map
            this.InnerMap.Children.Clear();
            int     i         = 0;
            Pushpin activePin = null;

            foreach (ImageAtLocation img in this.selectedImages)
            {
                ColoredPushpin pin = _options.RenderEntity(img);
                string         strokeColor;
                pin.FillColor   = App.MapVM.GetPushpinColors(img, out strokeColor);
                pin.StrokeColor = strokeColor;

                pin.Tag = i + 1;
                if (i == imageIndex)
                {
                    ControlTemplate myTemplate = (ControlTemplate)FindResource("PushpinControlTemplate");
                    pin.Template = myTemplate;
                    pin.ApplyTemplate();
                    activePin = pin;
                }
                else
                {
                    this.InnerMap.Children.Add(pin);
                }
                i++;
            }
            // Make sure the active pin are added last
            this.InnerMap.Children.Add(activePin);

            if (image.HasLocation)
            {
                // Set the URL for the google street view
                List <Location> locations = this.selectedImages.Where(s => s.Location != null).Select(s => s.Location).ToList();
                LocationRect    bounds    = new LocationRect(locations);

                double height = Measure(bounds.North, bounds.East, bounds.South, bounds.West);
                //int zoom = GetZoomLevel(height, bounds.Center.Latitude, this.webView.ActualHeight, this.webView.ActualWidth);
                //if (zoom > 19)
                //    zoom = 19;
                //if (zoom < 0)
                //    zoom = 19;
                //if (zoom < 4)
                //    zoom = 4;

                //this.StreetViewContainer.NavigationCompleted += StreetViewContainer_NavigationCompleted;
                string googleStreetViewString =
                    string.Format(@"https://www.google.com/maps/@?api=1&map_action=pano&viewpoint={0},{1}&heading=-45&pitch=0&fov=80",
                                  //string.Format(@"https://www.google.com/maps/@{0},{1},{2}z",
                                  image.Location.Latitude.ToString(CultureInfo.InvariantCulture), image.Location.Longitude.ToString(CultureInfo.InvariantCulture));
                //this.StreetViewContainer.Navigate(new Uri(googleStreetViewString));
                this.MyBrowserControl.URL = googleStreetViewString;
            }
        }
Ejemplo n.º 23
0
        void dgFileList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((DataGrid)sender).SelectedIndex >= 0)
            {
                var sFileName = ((DataGrid)sender).SelectedItems[0].ToString();

                var         xmldoc = new XmlDocument();         //XmlDataDocument();
                XmlNodeList xmlnode;
                int         i  = 0;
                var         fs = new FileStream(lblFolder.Content + @"\" + sFileName, FileMode.Open, FileAccess.Read);
                xmldoc.Load(fs);
                xmlnode = xmldoc.GetElementsByTagName("trkpt");
                myMap.Children.Clear();
                var myPolyline = new MapPolyline();
                myPolyline.Stroke          = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Blue);
                myPolyline.StrokeThickness = 5;
                myPolyline.Locations       = new LocationCollection();
                var    startLocation = new Location();
                var    lastLocation  = new Location();
                double minLat        = 0;
                double minLon        = 0;
                double maxLat        = 0;
                double maxLon        = 0;

                for (i = 0; i <= xmlnode.Count - 1; i++)
                {
                    double lat = Convert.ToDouble(xmlnode[i].Attributes["lat"].Value.ToString());
                    double lon = Convert.ToDouble(xmlnode[i].Attributes["lon"].Value.ToString());
                    myPolyline.Locations.Add(new Microsoft.Maps.MapControl.WPF.Location(lat, lon));

                    if (i == 0)
                    {
                        startLocation = new Location(lat, lon);
                    }
                    if (i == (xmlnode.Count - 1))
                    {
                        lastLocation = new Location(lat, lon);
                    }

                    if (i == 0)
                    {
                        minLat = lat;
                        minLon = lon;
                        maxLat = lat;
                        maxLon = lon;
                    }
                    else
                    {
                        if (lat < minLat)
                        {
                            minLat = lat;
                        }
                        if (lon < minLon)
                        {
                            minLon = lon;
                        }
                        if (lat > maxLat)
                        {
                            maxLat = lat;
                        }
                        if (lon > maxLon)
                        {
                            maxLon = lon;
                        }
                    }
                }

                myMap.Children.Add(myPolyline);

                var locationRectangle = new List <Location>();
                locationRectangle.Add(new Location(minLat, minLon));
                locationRectangle.Add(new Location(maxLat, maxLon));

                var boundingBox = new LocationRect(locationRectangle);

                myMap.SetView(boundingBox);
                myMap.ZoomLevel = myMap.ZoomLevel - 0.2;

                var startPin = new Pushpin();
                var endPin   = new Pushpin();
                startPin.Location = startLocation;
                endPin.Location   = lastLocation;

                myMap.Children.Add(startPin);
                myMap.Children.Add(endPin);
            }
        }
Ejemplo n.º 24
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);
                }
            }
        }
Ejemplo n.º 25
0
 public ClusteredLocationRect(LocationRect locationRect)
 {
     this.LocationRect = locationRect;
 }
        private ClusteredLocation <T> GetClusterForThisSector(List <ClusteredLocationRect <T> > clusters, LocationRect sector)
        {
            foreach (var cluster in clusters)
            {
                if (cluster.LocationRect.Intersects(sector))
                {
                    return(cluster);
                }
            }

            var newCluster = new ClusteredLocationRect <T>(sector);

            clusters.Add(newCluster);

            return(newCluster);
        }
Ejemplo n.º 27
0
        private void GetPhotos(MapLayer layer)
        {
            IsBusy = true;

            //this is not right
            PanoramioNet.Panoramio panoramioApi = new PanoramioNet.Panoramio();
            panoramioApi.GetMediumPhotoCollectionCompleted += new PanoramioNet.Panoramio.PhotoCollectionHandler(panoramioApi_GetMediumPhotoCollectionCompleted);

            if (Photos == null)
                Photos = new ObservableCollection<PhotoItem>();
            else
                Photos.Clear();
            foreach (var mp in layer.Children)
            {
                if (mp is MapPolygon)
                {

                    LocationRect rec = new LocationRect((mp as MapPolygon).Locations);
                    PanoramioNet.BoundaryBox PanoramioOptions = new PanoramioNet.BoundaryBox
                    {
                        MaximumLatitude = rec.North,
                        MinimumLatitude = rec.South,
                        MaximumLongitude = rec.East,
                        MinimumLongitude = rec.West
                    };
                    panoramioApi.GetPhotosmedium(PanoramioOptions, "medium", 0, 10);
                }
            }
        }
Ejemplo n.º 28
0
 /// <summary>
 /// Converts a LocationRect into a BoundingBox object.
 /// </summary>
 /// <param name="locationRect">A Bing Maps LocationRect object</param>
 /// <returns>A BoundingBox representation of the LocationRect object</returns>
 public static BoundingBox ToGeometry(this LocationRect locationRect)
 {
     return(new BoundingBox(locationRect.Center.ToGeometry(), locationRect.Width, locationRect.Height));
 }
Ejemplo n.º 29
0
 /// <summary>
 /// Determines if two LocationRect's intersect.
 /// </summary>
 /// <param name="rect">The base LocationRect.</param>
 /// <param name="rect2">A LocationRect to test the intersection of.</param>
 /// <returns>A boolean indicating if the two LocationRect's intersect.</returns>
 public static bool Intersects(this LocationRect rect, LocationRect rect2)
 {
     return(rect.ToGeometry().Intersects(rect2.ToGeometry()));
 }
Ejemplo n.º 30
0
 /// <summary>
 /// Checks whether two <see cref="LocationRect"/> values are equal.
 /// </summary>
 /// <param name="locationRect1"></param>
 /// <param name="locationRect2"></param>
 /// <returns></returns>
 public static bool Equals(LocationRect locationRect1, LocationRect locationRect2)
 {
     return(locationRect1.Northwest == locationRect2.Northwest && locationRect1.Southeast == locationRect2.Southeast);
 }
Ejemplo n.º 31
0
        private void Pin_LayoutUpdated(object sender, EventArgs e)
        {
            if (pin.Location != null)
            {
                this.bounds = myMap.BoundingRectangle;
                double centerLat = bounds.Center.Latitude;
                double centerLon = bounds.Center.Longitude;
                //Update the current latitude and longitude
                double latitude   = pin.Location.Latitude;
                double longtitude = pin.Location.Longitude;
                if (firstTime)
                {
                    myMap.SetView(new Location(latitude, longtitude), zoom);
                    PlainPosition.X = 0;
                    PlainPosition.Y = 0;
                    firstTime       = false;
                    preX            = latitude;
                    preY            = longtitude;
                    return;
                }
                if (!freeMove)
                {
                    //we are moving left or right.
                    if ((latitude - preY) == 0)
                    {
                        //we are moving right
                        if (preX < longtitude && longtitude + diffrance >= bounds.East)
                        {
                            myMap.SetView(new Location(centerLat, 2 * longtitude - centerLon - diffrance), zoom);
                        }
                        else if (preX > longtitude && longtitude - diffrance <= bounds.West)
                        {
                            myMap.SetView(new Location(centerLat, 2 * longtitude - centerLon + diffrance), zoom);
                        }
                    }
                    else
                    {
                        //found the Slope between the two points
                        double m = (longtitude - preX) / (latitude - preY);

                        //we are moving up with positive M and pass the limit of the current map page.
                        if (m > 0 && preY < latitude && latitude + diffrance >= bounds.North)
                        {
                            //we are exceed from the right side above.
                            if (longtitude >= centerLon)
                            {
                                myMap.SetView(new Location(2 * latitude - centerLat - diffrance, 2 * longtitude - centerLon), zoom);
                            }
                            //we are exceed from the left side above.
                            else
                            {
                                myMap.SetView(new Location(2 * latitude - centerLat - diffrance, centerLon), zoom);
                            }
                        }
                        //we are moving up moving with nagative M and pass the limit of the current map page.
                        else if (m < 0 && preY < latitude && latitude + diffrance >= bounds.North)
                        {
                            //we are exceed from the right side above.
                            if (longtitude < centerLon)
                            {
                                myMap.SetView(new Location(2 * latitude - centerLat - diffrance, 2 * longtitude - centerLon), zoom);
                            }
                            //we are exceed from the left side above.
                            else
                            {
                                myMap.SetView(new Location(2 * latitude - centerLat - diffrance, centerLon), zoom);
                            }
                        }
                        //we are moving down with positive M and pass the limit of the current map page.
                        else if (m > 0 && preY > latitude && latitude - diffrance <= bounds.South)
                        {
                            //we are exceed from the right side down.
                            if (longtitude < centerLon)
                            {
                                myMap.SetView(new Location(2 * latitude - centerLat + diffrance, 2 * longtitude - centerLon), zoom);
                            }
                            //we are exceed from the left side down.
                            else
                            {
                                myMap.SetView(new Location(2 * latitude - centerLat + diffrance, centerLon), zoom);
                            }
                        }
                        //we are moving down with nagative M and pass the limit of the current map page.
                        else if (m < 0 && preY > latitude && latitude - diffrance <= bounds.South)
                        {
                            //we are exceed from the right side down.
                            if (longtitude >= centerLon)
                            {
                                myMap.SetView(new Location(2 * latitude - centerLat + diffrance, 2 * longtitude - centerLon), zoom);
                            }
                            //we are exceed from the left side down.
                            else
                            {
                                myMap.SetView(new Location(2 * latitude - centerLat + diffrance, centerLon), zoom);
                            }
                        }

                        //we are moving with positive M and going to exceed the map from the right side of the map
                        else if (m > 0 && longtitude + diffrance >= bounds.East)
                        {
                            //we are at the top part of the right side of the map.
                            if (latitude >= centerLat)
                            {
                                myMap.SetView(new Location(2 * latitude - centerLat, 2 * longtitude - centerLon - diffrance), zoom);
                            }
                            //we are at the down part of the right side of the map.
                            else
                            {
                                myMap.SetView(new Location(centerLat, 2 * longtitude - centerLon - diffrance), zoom);
                            }
                        }
                        //we are moving with negative M and going to exceed the map from the right side of the map
                        else if (m < 0 && longtitude + diffrance >= bounds.East)
                        {
                            //we are at the down part of the right side of the map.
                            if (latitude <= centerLat)
                            {
                                myMap.SetView(new Location(2 * latitude - centerLat, 2 * longtitude - centerLon - diffrance), zoom);
                            }
                            //we are at the top part of the right side of the map.
                            else
                            {
                                myMap.SetView(new Location(centerLat, 2 * longtitude - centerLon - diffrance), zoom);
                            }
                        }
                        //we are moving down and going to exceed the map from the left side of the map
                        else if (m < 0 && longtitude - diffrance <= bounds.West)
                        {
                            //we are at the Top part of the left side of the map.
                            if (latitude >= centerLat)
                            {
                                myMap.SetView(new Location(2 * latitude - centerLat, 2 * longtitude - centerLon + diffrance), zoom);
                            }
                            //we are at the down part of the left side of the map.
                            else
                            {
                                myMap.SetView(new Location(centerLat, 2 * longtitude - centerLon + diffrance), zoom);
                            }
                        }
                        //we are moving up and going to exceed the map from the left side of the map
                        else if (m > 0 && longtitude - diffrance <= bounds.West)
                        {
                            //we are at the down part of the left side of the map.
                            if (latitude <= centerLat)
                            {
                                myMap.SetView(new Location(2 * latitude - centerLat, 2 * longtitude - centerLon + diffrance), zoom);
                            }
                            //we are at the Top part of the left side of the map.
                            else
                            {
                                myMap.SetView(new Location(centerLat, 2 * longtitude - centerLon + diffrance), zoom);
                            }
                        }
                    }
                    preX = longtitude;
                    preY = latitude;
                }
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Handles click event on search button and handles search functionality
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Search_Click(object sender, RoutedEventArgs e)
        {
            if (EndDatePicker.SelectedDate != null && StartDatePicker.SelectedDate != null)
            {
                //Clear prior search
                myMap.Visibility      = Visibility.Hidden;
                myMapLabel.Visibility = Visibility.Collapsed;
                myMap.Children.Clear();
                SearchResults.Visibility = Visibility.Collapsed;
                AddressList.Children.Clear();
                ErrorMessage.Visibility = Visibility.Collapsed;
                LoadingLabel.Visibility = Visibility.Visible;

                LocationData locationData = locationApi.getLocationData(LocationBox.Text);
                myMap.Center = locationData.CentrePoint;

                ComboBoxItem crimetype = (ComboBoxItem)CrimeType.SelectedItem;

                string crimeTag = (String)crimetype.Tag;

                DateTime startDate = (DateTime)StartDatePicker.SelectedDate;
                DateTime endDate   = (DateTime)EndDatePicker.SelectedDate;

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

                try
                {
                    locations = await policeApi.getCrimeLocations(locationData, startDate, endDate, crimeTag);

                    LocationCollection locationCollection = new LocationCollection();

                    // create List of locations to add to heat map layer
                    foreach (Location location in locations)
                    {
                        locationCollection.Add(location);
                    }

                    // Create new HeatMapLayer setting view properties
                    layer = new HeatMapLayer()
                    {
                        ParentMap = myMap,
                        Locations = locationCollection,
                        Radius    = 500,
                        Opacity   = 0.5
                    };

                    // Add to map view as child component layer
                    myMap.Children.Add(layer);

                    LocationRect box = new LocationRect(locations);
                    myMap.SetView(box);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("--Error retrieving data from server--\n" +
                                    "Please try one or more of the following: \n" +
                                    "* Ensuring your are entering a valid geolocation in England and Wales (e.g avoid any special characters)\n" +
                                    "* Narrowing the search area (e.g South London/Chelsea instead of London \n" +
                                    "* Reducing the date range \n" +
                                    "* Searching for less common crimes (e.g bicycle crime instead of public order offences)\n\n"
                                    ,
                                    "Error", MessageBoxButton.OK);
                    Debug.WriteLine(ex.StackTrace);
                    InitializeComponent();
                }
                LoadingLabel.Visibility = Visibility.Hidden;
                myMap.Visibility        = Visibility.Visible;
                myMap.Focus(); //allows '+' and '-' to zoom the map
            }
            else
            {
                MessageBox.Show("Please enter a start and end date", "Enter date", MessageBoxButton.OK);
            }
        }
Ejemplo n.º 33
0
        public void Fill(GPSTrackerViewModel viewModel, bool centerMap = true)
        {
            Children.Clear();

            //Color routeColor = Colors.Blue;
            //SolidColorBrush routeBrush = new SolidColorBrush(routeColor);
            //var routeLine = new MapPolyline();
            //routeLine.Locations = new LocationCollection();
            //routeLine.Stroke = routeBrush;
            //routeLine.Opacity = 0.50;
            //routeLine.StrokeThickness = 5.0;


            //MapLayer myRouteLayer = new MapLayer();
            //Children.Add(myRouteLayer);

            //// Add the route line to the new layer.
            //myRouteLayer.Children.Add(routeLine);
            //foreach (var gpsPoint in points)
            //{
            //    routeLine.Locations.Add(gpsPoint.ToLocation());
            //}

            var myRouteLayer = new MapLayer();

            Children.Add(myRouteLayer);
            lapsLayer        = new MapLayer();
            selectedLapLayer = new MapLayer();
            Children.Add(selectedLapLayer);
            Children.Add(lapsLayer);
            // Add the route line to the new layer.
            var routeLine = createMapLine(myRouteLayer);
            var firstLine = routeLine;

            for (int index = 0; index < viewModel.GPSPoints.Count; index++)
            {
                var gpsPoint = viewModel.GPSPoints[index];
                if (gpsPoint.Point.IsPoint())
                {
                    routeLine.Locations.Add(gpsPoint.ToLocation());
                }
                else if (routeLine.Locations != null && routeLine.Locations.Count > 0)
                {
                    routeLine = createMapLine(myRouteLayer);
                }
            }

            //add laps start-end points
            foreach (var lapViewModel in viewModel.Laps)
            {
                Pushpin pin = new Pushpin();
                pin.Content  = lapViewModel.Nr;
                pin.Location = lapViewModel.EndPoint.ToLocation();
                pin.ToolTip  = new usrLapPushpinInfo(lapViewModel);
                lapsLayer.Children.Add(pin);
            }

            var correctPoints = viewModel.GPSPoints.Where(x => x.Point.IsPoint());

            if (centerMap)
            {
                mapBounds = new LocationRect(
                    correctPoints.Max((p) => p.Point.Latitude),
                    correctPoints.Min((p) => p.Point.Longitude),
                    correctPoints.Min((p) => p.Point.Latitude),
                    correctPoints.Max((p) => p.Point.Longitude));
                //map.SetView(mapBounds);//here we got exception so moved this line to SizeChanged event
                Center = firstLine.Locations.FirstOrDefault();
            }
            updateLapsLayer();

            //add finish image (flag at the end of track)
            var startImg = new Image();

            startImg.Source = "pack://application:,,,/BodyArchitect.Client.Module.GPSTracker;component/Resources/Start16.png".ToBitmap();
            startImg.Width  = 16;
            startImg.Height = 16;
            myRouteLayer.AddChild(startImg, correctPoints.Last().ToLocation());
        }
        private async Task <IEnumerable <PictureViewModel> > LoadMorePictures(string keywords, LocationRect searchBounds)
        {
            try
            {
                double?maxDistance = null;
                double?longitude   = null;
                double?latitude    = null;
                if (searchBounds != null)
                {
                    maxDistance = LocationService.ComputeRadiusInKm(searchBounds);
                    longitude   = searchBounds.Center.Longitude;
                    latitude    = searchBounds.Center.Latitude;
                }
                var items = await ExecuteAsync(new SearchMediaInCategoryRequest { Keywords = keywords, MaxDistance = maxDistance, Latitude = latitude, Longitude = longitude, MaxAge = 1000 * Constants.MillisPerDay, PageNumber = 0, PageSize = Constants.ItemsPerPage, Category = Category.Id });

                var basePictureUri = new Uri(ResourceDictionary["BaseThumbnailUrl"] as string, UriKind.Absolute);
                var result         = new List <PictureViewModel>(items.Content.Count());
                foreach (var item in items.Content)
                {
                    result.Add(new PictureViewModel(basePictureUri, item));
                }
                return(result);
            }
            catch (Exception)
            {
                return(Enumerable.Empty <PictureViewModel>());
            }
        }
 void clear()
 {
     if (GeoLocationRect != null)
     {
         findLocationComboBox.ItemsSource = new List<LocationResult>();
         GeoLocationRect = null;
         map.SetView(ResetView);
         selectedLocationTextBox.Text = null;
     }
 }
        private void SetBestView(string filter)
        {
            if (this.visualizationLayer != null && this.visualizationLayer.ItemsSource != null)
            {
                var allItems = this.visualizationLayer.ItemsSource as ObservableCollection<MapItem>;
                if (allItems == null) return;
                allItems.ToList().ForEach(x => x.IsVisible = false);

                var filderedItems = allItems.Where(x => x.CountryName == filter).ToList();
                if (filderedItems.Count > 0)
                {
                    filderedItems.ForEach(x => x.IsVisible = true);
                    LocationRect bestViewRect = this.visualizationLayer.GetBestView(filderedItems);

                    // Expanding locationRect in order to avoid cuttting of PushPins.
                    LocationRect realBestView = new LocationRect(
                     new Location(bestViewRect.North + 0.075, bestViewRect.West ),
                     new Location(bestViewRect.South - 0.075, bestViewRect.East ));

                    this.radMap.SetView(realBestView);
                }
            } 
        }
Ejemplo n.º 37
0
 public static void SetObservedBoundingRectangle(DependencyObject obj, LocationRect value)
 {
     obj.SetValue(ObservedBoundingRectangleProperty, value);
 }
Ejemplo n.º 38
0
        /// <summary>
        /// Performs a search against the Bing Maps Search API
        /// </summary>
        /// <param name="query">User provided Search term</param>
        /// <param name="searchBoundaries">The BoundingRectangle of the map.</param>
        /// <param name="culture">The Culture of the map</param>
        /// <param name="credentials">Your API Credentials</param>
        /// <remarks>Retrieve Data by creating an Event Handler for SearchCompleted</remarks>
        public void Search(string query, LocationRect searchBoundaries, string culture, Credentials credentials)
        {
            SearchRequest request = new SearchRequest();
            request.Culture = culture;
            request.Query = query;

            // Don't raise exceptions.
            request.ExecutionOptions = new SearchService.ExecutionOptions();
            request.ExecutionOptions.SuppressFaults = true;

            LocationRect mapBounds = new LocationRect(searchBoundaries);
            request.UserProfile = new SearchService.UserProfile();
            request.UserProfile.MapView = mapBounds;

            //Pass in credentials for web services call.
            request.Credentials = credentials;

            //execute the request
            SearchClient.SearchAsync(request);
        }
Ejemplo n.º 39
0
        private static Location CoerceLocation(Location locationToCoerce, LocationRect screenBounds, LocationRect shapeBounds)
        {
            if (locationToCoerce.Longitude < shapeBounds.East - (screenBounds.East - screenBounds.West) / 2)
            {
                locationToCoerce.Longitude = shapeBounds.East - (screenBounds.East - screenBounds.West) / 2;
            }
            else if (locationToCoerce.Longitude > shapeBounds.West + (screenBounds.East - screenBounds.West) / 2)
            {
                locationToCoerce.Longitude = shapeBounds.West + (screenBounds.East - screenBounds.West) / 2;
            }

            if (locationToCoerce.Latitude < shapeBounds.North - (screenBounds.North - screenBounds.South) / 2)
            {
                locationToCoerce.Latitude = shapeBounds.North - (screenBounds.North - screenBounds.South) / 2;
            }
            else if (locationToCoerce.Latitude > shapeBounds.South + (screenBounds.North - screenBounds.South) / 2)
            {
                locationToCoerce.Latitude = shapeBounds.South + (screenBounds.North - screenBounds.South) / 2;
            }

            return(locationToCoerce);
        }
Ejemplo n.º 40
0
 public void plotPath(string start, string end)
 {
     string[] result = MappMon.mySocket.getLocations((App.Current as App).uid, start, end);
     if (!result[0].Equals("error"))
     {
         int resultLength          = result.Length - 1;
         LocationCollection points = new LocationCollection();
         int    i         = 0;
         double eastSide  = -180;
         double westSide  = 180;
         double northSide = -90;
         double southSide = 90;
         while (i < resultLength)
         {
             string[] resString = result[i].Split(new Char[] { '|' });
             //System.Diagnostics.Debug.WriteLine(resString);
             Double longi;
             longi = Double.Parse(resString[0]);
             if (longi < westSide)
             {
                 westSide = longi - 1;
             }
             if (longi > eastSide)
             {
                 eastSide = longi + 1;
             }
             Double lat;
             lat = Double.Parse(resString[1]);
             if (lat > northSide)
             {
                 northSide = lat + 1;
             }
             if (lat < southSide)
             {
                 southSide = lat - 1;
             }
             points.Add(new System.Device.Location.GeoCoordinate(lat, longi));
             Pushpin pin = new Pushpin();
             pin.Location = new GeoCoordinate(lat, longi);
             strokeLayer.Children.Add(pin);
             i++;
         }
         string       id         = "Movement from " + start + " to " + end;
         MapPolyline  actualLine = new MapPolyline();
         LocationRect view       = new LocationRect();
         view.East            = eastSide;
         view.West            = westSide;
         view.North           = northSide;
         view.South           = southSide;
         actualLine.Locations = points;
         Color StrokeColor = new Color();
         StrokeColor.B              = 10;
         StrokeColor.A              = 200;
         StrokeColor.G              = 10;
         StrokeColor.R              = 250;
         actualLine.Stroke          = new SolidColorBrush(StrokeColor);
         actualLine.Opacity         = 0.9;
         actualLine.StrokeThickness = 5;
         geoMap.SetView(view);
         geoMap.Children.Add(actualLine);
         geoMap.UpdateLayout();
     }
     else
     {
         //bitch and moan somehow.
     }
 }
Ejemplo n.º 41
0
        private bool SetMe()
        {
            if (this.SafePlaceCount() > 0)
            {
                Debug.WriteLine("SetMe");

                var places = (List<Place>) this.DataContext;

                // using Linq here is concise, but, other algorithms can be faster I bet
                var boundingRectangle = new LocationRect(
                    places.Max((p) => p.Latitude),
                    places.Min((p) => p.Longitude),
                    places.Min((p) => p.Latitude),
                    places.Max((p) => p.Longitude));

                this.Map.SetView(boundingRectangle);

                return true;
            }
            else
            {
                return false;
            }
        }
 private bool LocationRectContainedBy(LocationRect outer, LocationRect inner)
 {
     // TODO: This algorithm will almost certainly fail around the equator
     if (Math.Abs(inner.North) < Math.Abs(outer.North) && 
         Math.Abs(inner.South) > Math.Abs(outer.South) &&
         Math.Abs(inner.West) < Math.Abs(outer.West) && 
         Math.Abs(inner.East) > Math.Abs(outer.East))
     {
         return true;
     }
     else
     {
         return false;
     }
 }
Ejemplo n.º 43
0
 private void ChangeLocation(LocationRect box)
 {
     location           = new GeoAddress();
     location.Longitude = box.Center.Longitude;
     location.Latitude  = box.Center.Latitude;
 }
Ejemplo n.º 44
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);
      }
    }
Ejemplo n.º 45
0
        private void OnMapMovementWorkerOnDoWork(object sender, DoWorkEventArgs args)
        {
            var currentZoomLevel = (double)args.Argument;
            var worker           = sender as BackgroundWorker;

            //make sure we are within rendering levels or else remove everything
            if (currentZoomLevel > MaxZoomLevel || currentZoomLevel < MinZoomLevel)
            {
                //remove all items
                if (!removeItemsNotInView(worker, mapLayerObjects, true))
                {
                    args.Cancel = true;
                }
                return;
            }


            if (EnableScaling)
            {
                updateScale(currentZoomLevel);
            }

            //are we cancelled?
            if (worker != null && worker.CancellationPending)
            {
                args.Cancel = true;
                return;
            }

            //virtualize objects add / remove if in view.
            LocationRect mapview = MapInstance.BoundingRectangle;

            List <MapLayerObject> objectsInView;
            bool noChange;

            //determine what should be in view
            if (!getObjectsInView(worker, mapview, out objectsInView, out noChange))
            {
                args.Cancel = true;
                return;
            }

            //round the current zoom to the nearest full level
            var snapLevel = (int)Math.Round(currentZoomLevel, 0);

            //if nothing has changed then we can simply exit here
            if (!isDirty && noChange && snapLevel == currentSnapLevel)
            {
                return;
            }

            //something has changed must render next time we can:
            isDirty          = true;
            currentSnapLevel = snapLevel;

            //remove items no longer in view
            if (!removeItemsNotInView(worker, mapLayerObjects, false))
            {
                args.Cancel = true;
                return;
            }

            //simplify complex shapes in view
            if (EnableReduction)
            {
                if (!reduceComplexObjects(worker, objectsInView, snapLevel))
                {
                    args.Cancel = true;
                    return;
                }
            }

            //cluster points in view
            if (EnableClustering)
            {
                if (!clusterObjects(worker, objectsInView, snapLevel, mapview))
                {
                    args.Cancel = true;
                    return;
                }
            }

            //add final objects to view
            if (!addObjectsInViewToUI(worker, objectsInView))
            {
                args.Cancel = true;
                return;
            }

            //update the scale again as new objects could be added.
            if (EnableScaling)
            {
                updateScale(currentZoomLevel);
            }

            isDirty = false;
        }
Ejemplo n.º 46
0
 public WMSTileSource(string WMSURL, string layerName, string time, Range <double> range, LocationRect locationRect)
     : base(WMSURL + "SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&LAYERS=" + layerName + "&STYLES=&SRS=EPSG%3A4326&BBOX={0}&WIDTH=256&HEIGHT=256&FORMAT=image/png&TRANSPARENT=TRUE&time=" + time, locationRect, range)
 {
 }
Ejemplo n.º 47
0
        /// <summary>
        /// Simple fast grid cluster algorithm with no object location shift
        /// Find the first object in each grid cell and make it the cluster
        /// Contains all the other objects in that cell
        /// </summary>
        /// <param name="clusterableMapLayerObjects">items to cluster</param>
        /// <param name="worker">thread to check in cancelled</param>
        /// <param name="zoomLevel">zoom level of map</param>
        /// <param name="bounds">The bounds of the map control</param>
        /// <returns>Was the action cancelled?</returns>
        private bool GridCluster(IEnumerable <IClusterable> clusterableMapLayerObjects, BackgroundWorker worker, int zoomLevel, LocationRect bounds)
        {
            //get width and height from bounds
            int x1;
            int x2;
            int y1;
            int y2;

            TileSystem.LatLongToPixelXY(bounds.North, bounds.West, zoomLevel, out x1, out y1);
            TileSystem.LatLongToPixelXY(bounds.South, bounds.East, zoomLevel, out x2, out y2);

            double width = Math.Abs(x2 - x1);
            // Break the map up into a grid
            var numXCells = (int)Math.Ceiling(width / clusterwidth);
            // Create an array to store the clusters
            var clusters = new Dictionary <int, IClusterable>();

            foreach (var clusterableMapObject in clusterableMapLayerObjects)
            {
                if (clusterableMapObject.Initalized)
                {
                    //what cluster cell does this belong to?
                    var x     = (int)Math.Floor((clusterableMapObject.ProjectedPoints[zoomLevel].X - x1) / clusterwidth);
                    var y     = (int)Math.Floor((clusterableMapObject.ProjectedPoints[zoomLevel].Y - y1) / clusterheight);
                    var index = x + y * numXCells;
                    //if this is the first it is the cluster
                    if (!clusters.ContainsKey(index))
                    {
                        clusters.Add(index, clusterableMapObject);
                        clusterableMapObject.IsCluster = true;
                    }
                    else
                    {
                        //else add to existing cluster
                        clusters[index].ClusteredElements.Add(clusterableMapObject);
                        clusterableMapObject.IsClustered = true;
                    }
                }
                else
                {
                    //listen for event when it is ready
                    clusterableMapObject.ProjectionComplete += (o, e) =>
                    {
                        isDirty = true;
                        startMapMovementWorker();
                    };
                }

                //exit loop if thread cancelled
                if (worker != null && worker.CancellationPending)
                {
                    return(false);
                }
            }

            return(true);
        }
Ejemplo n.º 48
0
 public double ComputeRadiusInKm(LocationRect box)
 {
     return(Math.Max(box.Height, box.Width) * DEGREES_TO_RADIANS * EARTH_MEAN_RADIUS_KM / 2.0);
 }
Ejemplo n.º 49
0
        public void UpdateLiveLocations()
        {
            if (ViewModel.LiveLocations.Count > 0)
            {
                var locations = new List <GeoCoordinate>();
                ContactLocation.Visibility = Visibility.Collapsed;
                foreach (var messageBase in ViewModel.LiveLocations)
                {
                    var message = messageBase as TLMessage48;
                    if (message != null)
                    {
                        var mediaGeoLive = message.Media as TLMessageMediaGeoLive;
                        if (mediaGeoLive != null)
                        {
                            mediaGeoLive.Date     = message.Date;
                            mediaGeoLive.EditDate = message.EditDate;
                            mediaGeoLive.From     = message.From;
                            if (mediaGeoLive.Active)
                            {
                                var geoPoint = mediaGeoLive.Geo as TLGeoPoint;
                                if (geoPoint != null)
                                {
                                    var location = new GeoCoordinate(geoPoint.Lat.Value, geoPoint.Long.Value);

                                    var pushPin = new Pushpin
                                    {
                                        CacheMode   = new BitmapCache(),
                                        Template    = (ControlTemplate)Resources["LiveContactPushpinTemplate"],
                                        DataContext = message,
                                        Tag         = "live",
                                        Location    = location
                                    };

                                    if (message.FromId.Value == IoC.Get <IStateService>().CurrentUserId)
                                    {
                                        locations.Add(CurrentLocation.Location);
                                        pushPin.SetBinding(Pushpin.LocationDependencyProperty, new Binding {
                                            Source = CurrentLocation, Path = new PropertyPath("Location")
                                        });
                                    }
                                    else
                                    {
                                        locations.Add(location);
                                    }

                                    Map.Children.Add(pushPin);
                                }
                            }
                        }
                    }
                }

                if (locations.Count > 0)
                {
                    Map.AnimationLevel = AnimationLevel.UserInput;
                    Map.ZoomLevel      = 16.0;

                    if (locations.Count == 1)
                    {
                        Map.Center = locations[0];
                    }
                    else
                    {
                        Map.Center = locations[0];
                        return;

                        double num1 = -90.0;
                        double num2 = 90.0;
                        double num3 = 180.0;
                        double num4 = -180.0;
                        foreach (GeoCoordinate location in locations)
                        {
                            num1 = Math.Max(num1, location.Latitude);
                            num2 = Math.Min(num2, location.Latitude);
                            num3 = Math.Min(num3, location.Longitude);
                            num4 = Math.Max(num4, location.Longitude);
                        }

                        var locationRect = new LocationRect(num1, num3, num2, num4);

                        var boundedRect = new LocationRect(locationRect.Center, locationRect.Width * 1.2, locationRect.Height * 1.4);

                        Deployment.Current.Dispatcher.BeginInvoke(() => Map.SetView(boundedRect))
                        ;
                    }
                }
                else
                {
                    ContactLocation.Visibility = Visibility.Visible;
                }
            }
        }
Ejemplo n.º 50
0
        /// <summary>
        /// Calls WKT Service 
        ///     Initializes input parameters
        ///     Calls Asynch service
        /// </summary>
        /// <remarks>
        /// Drawtools leaves the area of interest definition on MapLayer 'layerDraw'
        /// </remarks>
        public void ShowLayers()
        {
            // get list of checked layers
            List<string> layers = GetLayers();
            layerCnt = layers.Count;
            if (layers.Count > 0)
            {
                totalFeatures = 0;
                totalPoints = 0;
                totalByteSize = 0;

                string queryType = null;
                string area = null;
                double radius = 0.0;
                double reduce = 4000 - MainMap.ZoomLevel * 500;
                if (reduce < 0) reduce = 0;
                if ((bool)drawtools.Proximity.IsChecked)
                {
                    queryType = "buffer";
                    Ellipse pt = (Ellipse)layerDraw.FindName("Proximity");
                    if (pt != null && pt.Tag != null)
                    {
                        Location loc = MapLayer.GetPosition(pt);
                        //radius(meters) longitude,latitude
                        if (pt.Tag != null) radius = Double.Parse(pt.Tag.ToString());
                        else radius = 1.0;
                        area = loc.Longitude + " " + loc.Latitude;
                    }
                }
                else if ((bool)drawtools.PolyBuffer.IsChecked)
                {
                    queryType = "buffer";
                    //buffer width(meters)  lon,lat lon,lat ... lon,lat
                    MapPolyline poly = (MapPolyline)layerDraw.FindName("Buffer");
                    if (poly != null)
                    {
                        Slider s = (Slider)drawtools.FindName("BufferSlider");
                        radius = (s.Value * 1000);
                        StringBuilder sb = new StringBuilder();
                        bool first = true;
                        foreach (Location l in poly.Locations)
                        {
                            if (!first) sb.Append(",");
                            sb.Append(l.Longitude + " " + l.Latitude);
                            first = false;
                        }
                        area = sb.ToString();
                    }
                }
                else if ((bool)drawtools.AOI.IsChecked)
                {
                    queryType = "bbox";
                    StringBuilder sb = new StringBuilder();
                    MapPolygon drawrect = ((MapPolygon)layerDraw.FindName("AOI"));

                    if (drawrect != null)
                    {
                        // check for hemisphere overrun
                        if (validAOI(drawrect.Locations[0], drawrect.Locations[2]) && 
                            WithinHemisphere(drawrect.Locations[0], drawrect.Locations[2]))
                        {
                            foreach (Location l in drawrect.Locations)
                            {
                                sb.Append(l.Longitude + " " + l.Latitude + ",");
                            }
                            sb.Append(drawrect.Locations[0].Longitude + " " + drawrect.Locations[0].Latitude);
                            area = sb.ToString();
                        }
                        else
                        {
                            drawtools.draw = true;
                        }
                    }
                }
                else if ((bool)drawtools.Viewport.IsChecked)
                {
                    queryType = "bbox";
                    StringBuilder sb = new StringBuilder();
                    LocationRect bounds = MainMap.BoundingRectangle;
                    // check for hemisphere overrun
                    if (validAOI(bounds.Southeast, bounds.Northwest) && 
                        WithinHemisphere(bounds.Southeast, bounds.Northwest))
                    {
                        sb.Append(bounds.Southeast.Longitude + " ");
                        sb.Append(bounds.Southeast.Latitude + ",");
                        sb.Append(bounds.Northeast.Longitude + " ");
                        sb.Append(bounds.Northeast.Latitude + ",");
                        sb.Append(bounds.Northwest.Longitude + " ");
                        sb.Append(bounds.Northwest.Latitude + ",");
                        sb.Append(bounds.Southwest.Longitude + " ");
                        sb.Append(bounds.Southwest.Latitude + ",");
                        sb.Append(bounds.Southeast.Longitude + " ");
                        sb.Append(bounds.Southeast.Latitude);
                        area = sb.ToString();
                    }
                    else
                    {
                        drawtools.draw = true;
                    }
                }
                if (area != null)
                {
                    // disable side menu and start load spinner until call returns
                    SidePanelBorder.IsHitTestVisible = false;
                    loaderStart();

                    foreach (string layer in layers)
                    {
                        XAMLClient svc = new XAMLClient("CustomBinding_IXAML");
                        svc.GetSQLDataXAMLCompleted += new EventHandler<GetSQLDataXAMLCompletedEventArgs>(XAMLService_GetSQLDataXAMLCompleted);
                        XAMLParameters parameters = new XAMLParameters();
                        parameters.table = layer.Replace("layer", "").ToLower();
                        parameters.querytype = queryType;
                        parameters.reduce = reduce;
                        parameters.radius = radius;
                        parameters.points = area;
                        svc.GetSQLDataXAMLAsync(parameters,layer);
                    }
                }
            }
            else
            {
                drawtools.draw = true;
            }
        }
Ejemplo n.º 51
0
        public static Location GetMercatorCenter(LocationRect boundingRectangle)
        {
            var location = MercatorCube.Instance.ToLocation(new Point3D(VectorMath.Multiply(VectorMath.Add(MercatorCube.Instance.FromLocation(boundingRectangle.Northwest).ToPoint(), MercatorCube.Instance.FromLocation(boundingRectangle.Southeast).ToPoint()), 0.5), 0.0));

            return(new Location(location.Latitude, location.Longitude, boundingRectangle.Center.Altitude, boundingRectangle.Center.AltitudeReference));
        }
Ejemplo n.º 52
0
 public static void SetMapBounds(DependencyObject obj, LocationRect value)
 {
     obj.SetValue(MapBoundsProperty, value);
 }
Ejemplo n.º 53
0
 private void DrawRoute(LocationCollection wayPoints)
 {
     MapShapeLayer shapeLayer = new MapShapeLayer();
     MapPolyline polyline = new MapPolyline();
     polyline.Locations = wayPoints;
     polyline.Color = Windows.UI.Colors.Red;
     polyline.Width = 5;
     shapeLayer.Shapes.Add(polyline);
     LocationRect mapRectangle = new LocationRect(wayPoints);
     this.map.SetView(mapRectangle);
     this.map.ShapeLayers.Add(shapeLayer);
 }
        private void findLocationComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            LocationResult location = (LocationResult)findLocationComboBox.SelectedItem;

            if (location == null) return;

            map.SetView(location.BoundingBox);
            GeoLocationRect = location.BoundingBox;
            selectedLocationTextBox.Text = location.Name;
        }
 public static void SetObservedBoundingRectangle(Map obj, LocationRect value)
 {
     obj.SetValue(ObservedBoundingRectangleProperty, value);
 }
Ejemplo n.º 56
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);
            }
        }
Ejemplo n.º 57
0
 public MapDetails(Credentials creds, string culture, LocationRect rect)
 {
     this.creds = creds;
     this.culture = culture;
     this.rect = rect;
 }
Ejemplo n.º 58
0
        public static List <LocationResult> findLocations(String query, String authKey, LocationRect usermapView = null)
        {
            List <LocationResult> result = new List <LocationResult>();

            if (String.IsNullOrEmpty(query) || String.IsNullOrWhiteSpace(query))
            {
                return(result);
            }

            String location = "?query=" + query.Trim();

            String culture = "&culture=en-GB";

            String output = "&o=xml";

            string userMapView = "";

            if (usermapView != null)
            {
                userMapView = "&usermapView=" +
                              usermapView.South.ToString(CultureInfo.CreateSpecificCulture("en-GB")) + "," +
                              usermapView.West.ToString(CultureInfo.CreateSpecificCulture("en-GB")) + "," +
                              usermapView.North.ToString(CultureInfo.CreateSpecificCulture("en-GB")) + "," +
                              usermapView.East.ToString(CultureInfo.CreateSpecificCulture("en-GB"));
            }

            string key = "&key=" + authKey;

            string geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations" + location + culture + output + userMapView + key;

            //Make the request and get the response
            XmlDocument geocodeResponse = GetXmlResponse(geocodeRequest);

            XmlElement root = geocodeResponse.DocumentElement;

            XmlNamespaceManager nsmgr = new XmlNamespaceManager(geocodeResponse.NameTable);

            nsmgr.AddNamespace("ns", "http://schemas.microsoft.com/search/local/ws/rest/v1");

            if (int.Parse(root.SelectSingleNode("//ns:EstimatedTotal", nsmgr).InnerText) > 0)
            {
                XmlNodeList resources = root.SelectNodes("//ns:Location", nsmgr);

                foreach (XmlNode resource in resources)
                {
                    result.Add(new LocationResult(resource, nsmgr));
                }

                if (usermapView != null)
                {
                    // sort on distance from usermap center
                    result.Sort(new Comparison <LocationResult>((a, b) => a.getSqrdDistToLocation(usermapView.Center).CompareTo(b.getSqrdDistToLocation(usermapView.Center))));
                }
            }
            else
            {
                // no results found
                SystemSounds.Hand.Play();
            }

            return(result);
        }
Ejemplo n.º 59
0
        public void UpdateUserRadius(String Radius,Bing.Maps.Location loc)
        {
            var R = 6371;

            var radius = Radius;      //radius of the circle
            var latitude = loc.Latitude;    //latitude of the circle center
            var longitude = loc.Longitude;   //longitude of the circle center

            var lat = (latitude * Math.PI) / 180;
            var lon = (longitude * Math.PI) / 180;
            var d = float.Parse(radius) / R;
            var circlePoints = new LocationCollection();

            for (int x = 0; x <= 360; x += 5)
            {
                var p2 = new Bing.Maps.Location(0, 0);
                var brng = x * Math.PI / 180;
                p2.Latitude = Math.Asin(Math.Sin(lat) * Math.Cos(d) + Math.Cos(lat) * Math.Sin(d) * Math.Cos(brng));

                p2.Longitude = ((lon + Math.Atan2(Math.Sin(brng) * Math.Sin(d) * Math.Cos(lat),
                                 Math.Cos(d) - Math.Sin(lat) * Math.Sin(p2.Latitude))) * 180) / Math.PI;
                p2.Latitude = (p2.Latitude * 180) / Math.PI;
                circlePoints.Add(p2);
            }

            userRadius = new LocationRect(circlePoints);
            var u = 0.001;
            userRadius = new LocationRect(new LocationCollection{ loc, new Bing.Maps.Location(loc.Latitude+u,loc.Longitude),new Bing.Maps.Location(loc.Latitude,loc.Longitude+u),
            new Bing.Maps.Location(loc.Latitude+u,loc.Longitude+u), new Bing.Maps.Location(loc.Latitude-u,loc.Longitude), new Bing.Maps.Location(loc.Latitude,loc.Longitude-u),
            new Bing.Maps.Location(loc.Latitude-u,loc.Longitude-u)});
        }
Ejemplo n.º 60
0
        // This is the callback method for the CalculateRoute request.
        private void routeService2_CalculateRouteCompleted(object sender, RouteService2.CalculateRouteCompletedEventArgs e)
        {
            try
            {
                // If the route calculate was a success and contains a route, then draw the route on the map.
                if ((e.Result.ResponseSummary.StatusCode == RouteService2.ResponseStatusCode.Success) & (e.Result.Result.Legs.Count != 0))
                {
                    // Add a map layer in which to draw the route.
                    MapLayer myRouteLayer = new MapLayer();
                    // Set properties of the route line you want to draw.



                    SolidColorBrush routeBrush = new SolidColorBrush(Colors.Red);

                    MapPolyline routeLine = new MapPolyline();
                    routeLine.Locations       = new LocationCollection();
                    routeLine.Stroke          = routeBrush;
                    routeLine.Opacity         = 0.65;
                    routeLine.StrokeThickness = 5.0;

                    foreach (Location p in e.Result.Result.RoutePath.Points)
                    {
                        //waypint to the routeline
                        routeLine.Locations.Add(new GeoCoordinate(p.Latitude, p.Longitude));
                    }



                    // Add the route line to the new layer.
                    myRouteLayer.Children.Add(routeLine);

                    // Figure the rectangle which encompasses the route. This is used later to set the map view.
                    // The rectangle must be defined as llx,lly, urx,ury. Since we don't know the exact route shape
                    // beforehand we need to validate the coordinates first
                    double minLat = routeLine.Locations[0].Latitude;
                    double minLon = routeLine.Locations[0].Longitude;
                    double maxLat = routeLine.Locations[routeLine.Locations.Count - 1].Latitude;
                    double maxLon = routeLine.Locations[routeLine.Locations.Count - 1].Longitude;

                    if (minLat > maxLat) // Swap min/max Lat
                    {
                        double tmpLat = 0;
                        tmpLat = minLat;
                        minLat = maxLat;
                        maxLat = tmpLat;
                    }
                    if (minLon > maxLon) // Swap min/max Lon
                    {
                        double tmpLon = 0;
                        tmpLon = minLon;
                        minLon = maxLon;
                        maxLon = tmpLon;
                    }
                    // This should always be a valid rectangle (minLat,minLon < maxLat,maxLon)
                    LocationRect rect = new LocationRect(minLat, minLon, maxLat, maxLon);

                    // Retrieve route directions from the RouteLeg.Itinerary class.
                    StringBuilder directions = new StringBuilder();

                    //Initialize directions counter
                    int instructionCount = 1;

                    //Loop through Interary instructions
                    foreach (var itineraryItem in e.Result.Result.Legs[0].Itinerary)
                    {
                        directions.Append(string.Format("{0}. {1} {2}\n",
                                                        instructionCount, itineraryItem.Summary.Distance, itineraryItem.Text));
                        instructionCount++;
                    }
                    // The itineraryItem.Text is in XML format e.g.:
                    //<VirtualEarth:Action>Depart</VirtualEarth:Action>
                    //<VirtualEarth:RoadName>Aigaiou</VirtualEarth:RoadName>
                    // toward
                    // <VirtualEarth:Toward>Cheimonidou</VirtualEarth:Toward>
                    // In this sample we will remove all tags around keywords.
                    // You could leave the tags on if you want to format the directions into a databound control
                    Regex  regex   = new Regex("<[/a-zA-Z:]*>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                    string results = regex.Replace(directions.ToString(), string.Empty);

                    RouteCalculated(myRouteLayer, rect, results);
                    i++;
                }
            }
            catch
            {
            }
        }