// adds pushpins for the POI locations. The pusphins can be customised depending on the place.
        // the method also adds poi info to the listview
        private async void addPushPinAtPOIAndAddtoList(JsonSchemas.NavteqPoiSchema.Response response)
        {
            if (response != null && response.ResultSet != null &&
                response.ResultSet.Results != null &&
                response.ResultSet.Results.Length > 0)
            {
                this.Dispatcher.Invoke(() =>
                {
                    myMap.Children.Clear();
                    nearbyPlacesList.Visibility = Visibility.Visible;
                });
                foreach (var poi in response.ResultSet.Results)
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        var loc      = new Microsoft.Maps.MapControl.WPF.Location(poi.Latitude, poi.Longitude);
                        var pin      = new Pushpin();
                        pin.Tag      = poi;
                        pin.Content  = "" + StaticVariables.POINumber;
                        pin.Location = loc;
                        myMap.Children.Add(pin);
                    });
                    BitmapImage poiImage = await getImageryOfPOI(new Coordinate(poi.Latitude, poi.Longitude));

                    addPOIToListView(poiImage, poi, StaticVariables.POINumber++);
                }
            }

            else
            {
                setSystemWarningMessagesToSpeechLabel(SystemMessages.NOPOI_MESSAGE);
                System.Diagnostics.Trace.WriteLine("No result");
            }
        }
Exemplo n.º 2
0
        public static LocationCollection GetCircleVertices(Location location, double dRadius)
        {
            var       locCollection = new LocationCollection();
            const int earthRadius   = 6367; // Earth Radius in Kilometers

            //Convert location to radians based on
            var latitude  = Math.PI / 180 * location.Latitude;
            var longitude = Math.PI / 180 * location.Longitude;

            var d = dRadius / earthRadius;

            for (var x = 0; x < 360; x++)
            {
                var angle      = x * (Math.PI / 180); //radians
                var latRadians = Math.Asin(Math.Sin(latitude) * Math.Cos(d) +
                                           Math.Cos(latitude) * Math.Sin(d) * Math.Cos(angle));
                var lngRadians = longitude + Math.Atan2(Math.Sin(angle) * Math.Sin(d) * Math.Cos(latitude),
                                                        Math.Cos(d) - Math.Sin(latitude) * Math.Sin(latRadians));

                //Get location of the point
                var pt = new Location(180.0 * latRadians / Math.PI, 180.0 * lngRadians / Math.PI);

                //Add the new calculated point to the collection
                locCollection.Add(pt);
            }

            return(locCollection);
        }
Exemplo n.º 3
0
        private async void aser(GeocodeRequest request)
        {
            //Process the request by using the ServiceManager.
            var response = await ServiceManager.GetResponseAsync(request);



            if (response != null &&
                response.ResourceSets != null &&
                response.ResourceSets.Length > 0 &&
                response.ResourceSets[0].Resources != null &&
                response.ResourceSets[0].Resources.Length > 0)
            {
                var result = response.ResourceSets[0].Resources[0] as BingMapsRESTToolkit.Location;

                Microsoft.Maps.MapControl.WPF.Location location = new Microsoft.Maps.MapControl.WPF.Location();

                location.Longitude = result.Point.Coordinates[1];
                location.Latitude  = result.Point.Coordinates[0];

                Pushpin pushpin = new Pushpin();
                pushpin.Location = location;

                mMap.Children.Add(pushpin);

                ////mMap.SetView(location, 14);
            }
        }
        public void drawCircle(Microsoft.Maps.MapControl.WPF.Location Loc, double dRadius, Color fillColor)
        {
            var locCollection = new LocationCollection();
            var EarthRadius   = 6367; // Earth Radius in Kilometers

            //Convert location to radians based on
            var latitude  = (Math.PI / 180) * (Loc.Latitude);
            var longitude = (Math.PI / 180) * (Loc.Longitude);

            var d = dRadius / EarthRadius;

            for (int x = 0; x < 360; x++)
            {
                var angle      = x * (Math.PI / 180); //radians
                var latRadians = Math.Asin(Math.Sin(latitude) * Math.Cos(d) + Math.Cos(latitude) * Math.Sin(d) * Math.Cos(angle));
                var lngRadians = longitude + Math.Atan2(Math.Sin(angle) * Math.Sin(d) * Math.Cos(latitude), Math.Cos(d) - Math.Sin(latitude) * Math.Sin(latRadians));

                //Get location of the point
                var pt = new Microsoft.Maps.MapControl.WPF.Location(180.0 * latRadians / Math.PI, 180.0 * lngRadians / Math.PI);

                //Add the new calculatied poitn to the collection
                locCollection.Add(pt);
            }

            MapPolygon polygon = new MapPolygon();

            polygon.Fill            = new SolidColorBrush(fillColor);
            polygon.Stroke          = new SolidColorBrush(Colors.Black);
            polygon.StrokeThickness = 1;
            polygon.Opacity         = 0.65;
            polygon.Locations       = locCollection;

            myMap.Children.Add(polygon);
        }
Exemplo n.º 5
0
        /*
         * Implemented after http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
         */
        public static bool IsPointInPolygon(IList<Location> polygonVertices, Location point)
        {
            var loc = polygonVertices;

            int i, j;
            var isInside = false;
            for (i = 0, j = loc.Count - 1; i < loc.Count; j = i++)
            {
                if (
                    (
                        (loc.ElementAt(i).Longitude > point.Longitude) != (loc.ElementAt(j).Longitude > point.Longitude)
                    )
                    &&
                    (
                        point.Latitude < (loc.ElementAt(j).Latitude - loc.ElementAt(i).Latitude)
                                *
                                (point.Longitude - loc.ElementAt(i).Longitude)
                        /
                        (loc.ElementAt(j).Longitude - loc.ElementAt(i).Longitude)
                        +
                        loc.ElementAt(i).Latitude
                    )
                    )
                    isInside = !isInside;
            }
            return isInside;
        }
Exemplo n.º 6
0
        public static async Task <string> ConvertLocationToAddressAsync(Location location)
        {
            string data = "";

            try
            {
                var uri = Config.Host + "/maps/api/geocode/json?latlng=" + location.Latitude.ToString() + "," +
                          location.Longitude.ToString() + "&language=lt&key=" +
                          Config.Google_Api_Key;

                var client   = new HttpClient();
                var response = await client.GetAsync(uri);

                response.EnsureSuccessStatusCode();
                var responseBody = await response.Content.ReadAsStringAsync();

                var o = JObject.Parse(responseBody);

                data = (string)o.SelectToken("results[0].formatted_address");


                return(data);
            }
            catch (Exception ex)
            {
                Console.Write(ex.ToString());
            }

            return(data);
        }
Exemplo n.º 7
0
 private static IEnumerable <Location> GetCircle(Location center, double radius)
 {
     for (int i = 0; i < 360; i++)
     {
         yield return(CalculateDerivedPosition(center, radius, i));
     }
 }
Exemplo n.º 8
0
        private WijkagentModels.Location GetLocationFromClick(MouseButtonEventArgs e)
        {
            // Get the mouse click coordinates
            Point mousePosition = e.GetPosition(this);

            Microsoft.Maps.MapControl.WPF.Location location = wpfMapMain.ViewportPointToLocation(mousePosition);
            return(new WijkagentModels.Location(location.Latitude, location.Longitude));
        }
Exemplo n.º 9
0
        public Pushpin CreateMarker(Microsoft.Maps.MapControl.WPF.Location location)
        {
            Pushpin pin = new Pushpin {
                Location = location
            };

            return(pin);
        }
Exemplo n.º 10
0
        private void BtnCalc_Click(object sender, RoutedEventArgs e)
        {
            string myFile = @"c:\ProgramData\Adobe\ARM\Reader_15.008.20082\Visual Studio\C#\Bing\Gpx\1_בדצמ׳_2020_22_02_01.gpx";


            ds.ReadXml(myFile);

            myTbl = ds.Tables["trkpt"];

            var locs = new LocationCollection();

            for (int i = 0; i < myTbl.Rows.Count; i = i + 10)
            {
                locs.Add(new Microsoft.Maps.MapControl.WPF.Location(Convert.ToDouble(myTbl.Rows[i]["lat"]), Convert.ToDouble(myTbl.Rows[i]["lon"])));
            }

            var routeLine = new MapPolyline()
            {
                Locations       = locs,
                Stroke          = new SolidColorBrush(Colors.Blue),
                StrokeThickness = 5
            };

            mMap.Children.Add(routeLine);

            Microsoft.Maps.MapControl.WPF.Location start = new Microsoft.Maps.MapControl.WPF.Location(locs[locs.Count - 1].Latitude, locs[locs.Count - 1].Longitude);
            Microsoft.Maps.MapControl.WPF.Location end   = new Microsoft.Maps.MapControl.WPF.Location(locs[0].Latitude, locs[0].Longitude);

            Pushpin pushpinStart = new Pushpin();

            pushpinStart.Location = start;

            Pushpin pushpinEnd = new Pushpin();

            pushpinEnd.Location = end;

            //mMap.Children.Add(pushpinStart);
            mMap.Children.Add(pushpinEnd);

            Image image = new Image();

            BitmapImage bitmap = new BitmapImage(new Uri("pack://application:,,,/Bing;component/Resources/pushRed2.png"));

            image.Source = bitmap;
            image.Width  = 50;
            image.Height = 50;

            MapLayer layer = new MapLayer();

            PositionOrigin position = PositionOrigin.BottomCenter;

            layer.AddChild(image, start, position);

            mMap.Children.Add(layer);

            mMap.SetView(start, 10);
            mMap.Center = start;
        }
Exemplo n.º 11
0
 private void bntLocation2_Click(object sender, RoutedEventArgs e)
 {
     //45.644274, 25.595408
     Microsoft.Maps.MapControl.WPF.Location location = new Microsoft.Maps.MapControl.WPF.Location(45.644274, 25.595408);
     myMap.Center = location;
     if (pushPin2.Visibility == Visibility.Hidden)
     {
         pushPin2.Visibility = Visibility.Visible;
     }
 }
Exemplo n.º 12
0
 private void bntLocation1_Click(object sender, RoutedEventArgs e)
 {
     //45.653050, 25.582512
     Microsoft.Maps.MapControl.WPF.Location location = new Microsoft.Maps.MapControl.WPF.Location(45.653050, 25.582512);
     myMap.Center = location;
     if (pushPin1.Visibility == Visibility.Hidden)
     {
         pushPin1.Visibility = Visibility.Visible;
     }
 }
Exemplo n.º 13
0
        /// <summary>
        /// Logika routingu.
        /// Skorzystałem z BingMapsRESTToolkit
        /// </summary>
        /// <param name="fwp">FirstWaypoint - Lokalizacja jednego pina - tego ze zwierzakiem</param>
        /// <param name="swp">SecondWaypoint - Lokalizacja drugiego pina - destynacji</param>
        /// <param name="key">Klucz do map bing</param>
        /// <param name="map">Referencja do mapy, aby dodać do niej drogę</param>
        /// <returns></returns>
        public static async Task GetRoute(Microsoft.Maps.MapControl.WPF.Location fwp, Microsoft.Maps.MapControl.WPF.Location swp, String key, Map map)
        {
            var request = new RouteRequest()
            {
                Waypoints = new List <SimpleWaypoint>()
                {
                    new SimpleWaypoint(fwp.Latitude, fwp.Longitude),
                    new SimpleWaypoint(swp.Latitude, swp.Longitude)
                },
                BingMapsKey  = key,
                RouteOptions = new RouteOptions()
                {
                    TravelMode      = TravelModeType.Driving,
                    Optimize        = RouteOptimizationType.Time,
                    RouteAttributes = new List <RouteAttributeType>()
                    {
                        RouteAttributeType.RoutePath
                    }
                }
            };

            var response = await request.Execute();

            if (response != null &&
                response.ResourceSets != null &&
                response.ResourceSets.Length > 0 &&
                response.ResourceSets[0].Resources != null &&
                response.ResourceSets[0].Resources.Length > 0)
            {
                var                result    = response.ResourceSets[0].Resources[0] as Route;
                double[][]         routePath = result.RoutePath.Line.Coordinates;
                LocationCollection locs      = new LocationCollection();

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

                MainWindow.Waypoints = new LocationCollection();
                MainWindow.Waypoints = locs;

                MainWindow.ReceivedRoute = new MapPolyline()
                {
                    Locations       = locs,
                    Stroke          = new SolidColorBrush(Colors.Black),
                    StrokeThickness = 2
                };

                map.Children.Add(MainWindow.ReceivedRoute);
            }
        }
Exemplo n.º 14
0
 public void AddSpawningPoint(Location loc)
 {
     BountyPushpin pin = new BountyPushpin();
     pin.ToolTip = string.Format("{0} (Spawning Point)", BountyName);
     pin.PopupContent = new PopupContentFactory()
             .AppendWikiLink(BountyName)
             .AppendDulfyLink(BountyName)
             .Content;
     pin.Location = loc;
     Children.Add(pin);
 }
Exemplo n.º 15
0
        //Get the location by clicking on the map
        private void myMap_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;

            myMap.Children.RemoveAt(0);

            Point mousePosition = e.GetPosition(this);

            Microsoft.Maps.MapControl.WPF.Location pinLocation = myMap.ViewportPointToLocation(mousePosition);

            PlacePin(pinLocation.Latitude, pinLocation.Longitude);
        }
 // the method gets the location(latitude and longitude) on map based on where the kinect hand (preferrably right hand) is pointing at the map.
 private Microsoft.Maps.MapControl.WPF.Location getLocationFromScreenPoint()
 {
     Microsoft.Maps.MapControl.WPF.Location l = null;
     this.Dispatcher.Invoke(() =>
     {
         System.Windows.Point mapPoint = KinectCanvas.TranslatePoint(kinectHandPositionOnScreen, myMap);
         // Due to some alignment problem, the Y coordinate is shifted (Open Issue: need to figure out the problem). Hence this offset tries to place the point exactly on the kinect hand position
         mapPoint.Y = mapPoint.Y - StaticVariables.handPointOffsetY;
         l          = myMap.ViewportPointToLocation(mapPoint);
     });
     return(l);
 }
Exemplo n.º 17
0
        public void AddSpawningPoint(Location loc)
        {
            BountyPushpin pin = new BountyPushpin();

            pin.ToolTip      = string.Format("{0} (Spawning Point)", BountyName);
            pin.PopupContent = new PopupContentFactory()
                               .AppendWikiLink(BountyName)
                               .AppendDulfyLink(BountyName)
                               .Content;
            pin.Location = loc;
            Children.Add(pin);
        }
Exemplo n.º 18
0
        private async void Rut(RouteRequest routeRequest)
        {
            var response = await routeRequest.Execute();



            BoundingBox rect = new BoundingBox(new double[] { response.ResourceSets[0].Resources[0].BoundingBox[0], response.ResourceSets[0].Resources[0].BoundingBox[1], response.ResourceSets[0].Resources[0].BoundingBox[2], response.ResourceSets[0].Resources[0].BoundingBox[3] });

            Microsoft.Maps.MapControl.WPF.Location shani = new Microsoft.Maps.MapControl.WPF.Location(31.876640708011877, 34.81796609362201);


            mMap.SetView(shani, 14);
        }
        // the method adds a pushpin at the location of the kinect hand position (preferrably right hand)
        // the kinectHandPositionOnScreen has a default value of 0,0. It gets updated based on hand position.
        private void ShowLocationOfKinectHandPoint()
        {
            // The kinectHandPositionOnScreen gives coordinates relative to the UIElement on which kinect hands are drawn which in this case is 'KinectCanvas'.
            // This coordinates needs to translated relative to the Map UIElement to find out the location.
            System.Windows.Point mapPoint = KinectCanvas.TranslatePoint(kinectHandPositionOnScreen, myMap);
            // Due to some alignment problem, the Y coordinate is shifted (Open Issue: need to figure out the problem). Hence this offset tries to place the point exactly on the kinect hand position
            mapPoint.Y = mapPoint.Y - StaticVariables.handPointOffsetY;
            Microsoft.Maps.MapControl.WPF.Location l = myMap.ViewportPointToLocation(mapPoint);
            Pushpin pushpin = new Pushpin();

            pushpin.Location = l;
            myMap.Children.Add(pushpin);
        }
        /// <summary>
        /// Calculates the best map view for a list of locations for a map. Based on https://rbrundritt.wordpress.com/2009/07/21/determining-best-map-view-for-an-array-of-locations/
        /// </summary>
        /// <param name="locations">List of location objects</param>
        /// <param name="mapWidth">Map width in pixels</param>
        /// <param name="mapHeight">Map height in pixels</param>
        /// <param name="buffer">Width in pixels to use to create a buffer around the map. This is to keep pushpins from being cut off on the edge</param>
        /// <returns>The best center and zoom level for the specified set of locations.</returns>
        public void GetBestMapView(List <Microsoft.Maps.MapControl.WPF.Location> locations, double mapWidth, double mapHeight, int buffer, out Microsoft.Maps.MapControl.WPF.Location center, out double zoomLevel)
        {
            center    = new Microsoft.Maps.MapControl.WPF.Location();
            zoomLevel = 0;

            double maxLat = -85;
            double minLat = 85;
            double maxLon = -180;
            double minLon = 180;

            //calculate bounding rectangle
            for (int i = 0; i < locations.Count; i++)
            {
                if (locations[i].Latitude > maxLat)
                {
                    maxLat = locations[i].Latitude;
                }

                if (locations[i].Latitude < minLat)
                {
                    minLat = locations[i].Latitude;
                }

                if (locations[i].Longitude > maxLon)
                {
                    maxLon = locations[i].Longitude;
                }

                if (locations[i].Longitude < minLon)
                {
                    minLon = locations[i].Longitude;
                }
            }

            center.Latitude  = (maxLat + minLat) / 2;
            center.Longitude = (maxLon + minLon) / 2;

            double zoom1 = 0, zoom2 = 0;

            //Determine the best zoom level based on the map scale and bounding coordinate information
            if (maxLon != minLon && maxLat != minLat)
            {
                //best zoom level based on map width
                zoom1 = Math.Log(360.0 / 256.0 * (mapWidth - 2 * buffer) / (maxLon - minLon)) / Math.Log(2);
                //best zoom level based on map height
                zoom2 = Math.Log(180.0 / 256.0 * (mapHeight - 2 * buffer) / (maxLat - minLat)) / Math.Log(2);
            }

            //use the most zoomed out of the two zoom levels
            zoomLevel = (zoom1 < zoom2) ? zoom1 : zoom2;
        }
Exemplo n.º 21
0
        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Maps.MapControl.WPF.Location pinlocation = Map.Center;

            Models.Location location = new Models.Location
            {
                Longitude = pinlocation.Longitude,
                Latitude  = pinlocation.Latitude,
                Name      = "Без Имени"
            };
            (DataContext as LocationViewModel).AddCommand.Execute(location);
            Update();
            SelectedPin = null;
        }
Exemplo n.º 22
0
        private async void MyMap_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            // Disables the default mouse click action.
            e.Handled = true;

            //Get the mouse click coordinates
            Point mousePosition = e.GetPosition(MyMap);

            //Convert the mouse coordinates to a locatoin on the map
            Location circleCenter = MyMap.ViewportPointToLocation(mousePosition);

            ViewModel.Latitude  = circleCenter.Latitude;
            ViewModel.Longitude = circleCenter.Longitude;
        }
Exemplo n.º 23
0
        public void SetUserLocation(Microsoft.Maps.MapControl.WPF.Location newLocation)
        {
            Pushpin newPin = new Pushpin()
            {
                Location   = newLocation,
                Content    = "YOU ARE HERE",
                Background = Brushes.DarkOrange,
                Foreground = Brushes.DarkOrange,
                FontSize   = 1
            };

            newPin.MouseEnter += NewPin_MouseEnter;
            newMap.Children.Add(newPin);
        }
Exemplo n.º 24
0
        public MapLayer CreateMarkerWithImage(string imageUri, Microsoft.Maps.MapControl.WPF.Location location)
        {
            MapLayer result = new MapLayer();

            Image imageStart = new Image();

            imageStart.Source = new BitmapImage(new Uri(imageUri, UriKind.Absolute));
            imageStart.Width  = 30;
            imageStart.Height = 30;


            result.AddChild(imageStart, location);

            return(result);
        }
 /// <summary>
 /// zooms the map to the address selected in the popup canvas
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void addressResultTree_MouseDoubleClick(object sender, MouseButtonEventArgs e)
 {
     try
     {
         hidePopupCanvas();
         SelectedObject     selectedObject = ((SelectedObject)((TreeViewItem)addressResultTree.SelectedItem).Tag);
         GeographicPosition location       = selectedObject.GeographicPosition;
         AddressType        firstOrDefault = selectedObject.FirstOrDefault;
         Location           loc            = new Microsoft.Maps.MapControl.WPF.Location(Double.Parse(location.Latitude.ToString()), Double.Parse(location.Longitude.ToString()));
         locationMap.SetView(loc, getZoom(firstOrDefault));
     }
     catch (Exception ex)
     {
         Logger.Error(ex.ToString());
     }
 }
Exemplo n.º 26
0
        /*
         * Distance using the Haversine formula.
         */
        public static double DirectDistance(Location p, Location q)
        {
            var qLatRad = q.Latitude * (Math.PI / 180);
            var pLatRad = p.Latitude * (Math.PI / 180);

            var deltaLat = (q.Latitude - p.Latitude) * (Math.PI / 180);
            var deltaLng = (q.Longitude - p.Longitude) * (Math.PI / 180);

            var a = Math.Pow(Math.Sin(deltaLat / 2), 2) +
                    Math.Cos(qLatRad) * Math.Cos(pLatRad) * Math.Pow(Math.Sin(deltaLng / 2), 2);
            //var c = 2 * Math.Asin(Math.Sqrt(a));
            var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));

            var d = c * EarthRadius;

            return d;
        }
Exemplo n.º 27
0
        private async void Sale(RouteRequest routeRequest)
        {
            var response = await routeRequest.Execute();

            if (response != null &&
                response.ResourceSets != null &&
                response.ResourceSets.Length > 0 &&
                response.ResourceSets[0].Resources != null &&
                response.ResourceSets[0].Resources.Length > 0)
            {
                var route  = response.ResourceSets[0].Resources[0] as Route;
                var coords = route.RoutePath.Line.Coordinates; //This is 2D array of lat/long values.
                var locs   = new LocationCollection();

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

                var routeLine = new MapPolyline()
                {
                    Locations       = locs,
                    Stroke          = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Blue),
                    StrokeThickness = 5
                };

                if (mMap.Children.Count > 0)
                {
                    mMap.Children.RemoveAt(0);
                }


                mMap.Children.Add(routeLine);

                Microsoft.Maps.MapControl.WPF.Location start = new Microsoft.Maps.MapControl.WPF.Location(locs[0].Latitude, locs[0].Longitude);

                mMap.SetView(start, 12);
                mMap.Center = start;

                Route aa = response.ResourceSets[0].Resources[0] as Route;
                txtKm.Text = aa.TravelDistance.ToString();

                txtTime.Text = App.SecondToHMS(aa.TravelDuration);
            }
        }
Exemplo n.º 28
0
        private void PlayerWorkerThread()
        {
            // wait for map data to be loaded before proceeding (or if we are cancelled)
            EventWaitHandle.WaitAny(new ManualResetEvent[] { m_MapDataLoaded, m_Canceled });

            while (m_Running)
            {
                try
                {
                    if (m_Link.DataAvailable && m_MapData.ContainsKey(m_Link.Map))
                    {
                        FloorMapDetails map = m_MapData[m_Link.Map];

                        // convert back to inches
                        double posX = m_Link.PositionX * 39.3700787;
                        double posZ = m_Link.PositionZ * 39.3700787;
                        double rot  = m_Link.RotationPlayer;

                        posX = ArenaNetMap.TranslateX(posX, map.MapRect, map.ContinentRect);
                        posZ = ArenaNetMap.TranslateZ(posZ, map.MapRect, map.ContinentRect);

                        Location loc = ArenaNetMap.Unproject(new Point(posX, posZ), ArenaNetMap.MaxZoomLevel);

                        // move the player icon
                        Dispatcher.Invoke(() =>
                        {
                            m_Player.Heading    = rot;
                            m_Player.Visibility = Visibility.Visible;

                            // only follow player if they've asked to and the location has changed
                            if (m_FollowPlayer && m_Player.Location != loc)
                            {
                                Map.SetView(loc, Map.ZoomLevel);
                            }

                            m_Player.Location = loc;
                        }, DispatcherPriority.Background, CancellationToken.None, new TimeSpan(0, 0, 1));
                    }
                }
                catch
                { }

                m_Canceled.WaitOne(100);
            }
        }
Exemplo n.º 29
0
        //Return distance between two locations
        public static double DistanceBetweenPlaces(Location loc1, Location loc2)
        {
            double R = 6371; // Earth radius km

            var sLat1 = Math.Sin(loc1.Latitude * (Math.PI / 180));
            var sLat2 = Math.Sin(loc2.Latitude * (Math.PI / 180));
            var cLat1 = Math.Cos(loc1.Latitude * (Math.PI / 180));
            var cLat2 = Math.Cos(loc2.Latitude * (Math.PI / 180));
            var cLon  = Math.Cos(loc1.Longitude * (Math.PI / 180) - loc2.Longitude * (Math.PI / 180));

            var cosD = sLat1 * sLat2 + cLat1 * cLat2 * cLon;

            var d = Math.Acos(cosD);

            var dist = R * d;

            return(dist);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Method to set current map view to defined lat lon
        /// </summary>
        /// <param name="lat"></param>
        /// <param name="lon"></param>
        public void setPosition(double lat, double lon)
        {
            //parse lat lon to mapcontrol Location object
            Microsoft.Maps.MapControl.WPF.Location gpsPos = new Microsoft.Maps.MapControl.WPF.Location(lat, lon);
            //center map on position
            myMap.Center = gpsPos;
            //if first fix set zoom level - disable this for subsequent fixes.
            if (firstfix)
            {
                firstfix        = false;
                myMap.ZoomLevel = 18;
            }
            //calculate locations of a circle of radius 5m around the current poitision
            var locations = GeoCodeCalc.CreateCircle(gpsPos, 0.005, DistanceMeasure.Kilometers);

            //set gps polygon (defined in XAML) Locations to the circle calculated above.
            gps.Locations = locations;
        }
Exemplo n.º 31
0
        /// <summary>
        /// Add vertex Method. Used to add multipoint polygons or lines (determined by featureType parameter) to the map.
        /// </summary>
        /// <param name="lat"></param>
        /// <param name="lon"></param>
        /// <param name="featureType"></param>
        public void addVertex(double lat, double lon, string featureType)
        {
            //parse lat lon to mapcontrol Location object
            Microsoft.Maps.MapControl.WPF.Location pos = new Microsoft.Maps.MapControl.WPF.Location(lat, lon);
            //Switch on the featureType
            switch (featureType)
            {
            //if polygon
            case "Polygon":
                //if not editing - first vertex added - initialize polygon object
                if (!editing)
                {
                    poly                 = new MapPolygon();
                    poly.Fill            = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Blue);
                    poly.Stroke          = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Black);
                    poly.StrokeThickness = 1;
                    poly.Locations       = new LocationCollection();
                    //add polygon to map.
                    myMap.Children.Add(poly);
                    editing = true;
                }
                //add position to Locations array
                poly.Locations.Add(pos);
                break;

            //if Line
            case "Line":
                //if not editing - first vertex added - initialize polyline object
                if (!editing)
                {
                    //instatiate line and style
                    line                 = new MapPolyline();
                    line.Stroke          = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Black);
                    line.StrokeThickness = 1;
                    line.Locations       = new LocationCollection();
                    //add line to map
                    myMap.Children.Add(line);
                    editing = true;
                }
                //push new location to the lines Locations array
                line.Locations.Add(pos);
                break;
            }
        }
Exemplo n.º 32
0
        private void OnDoubleClick(
            object sender,
            System.Windows.Input.MouseButtonEventArgs e)
        {
            var viewportPos = e.GetPosition(_nativeMap);
            var pos         = new MsMaps.Location();
            var ok          = _nativeMap.TryViewportPointToLocation(
                viewportPos,
                out pos);

            if (ok)
            {
                _eventMap?.FireDoubleClick(
                    new Xamarin.Forms.Maps.Position(
                        pos.Latitude,
                        pos.Longitude));
                e.Handled = true;
            }
        }
        // the method gets and adds POI(Specific places if BingQueryFilters are specified) based on the point on application where the kinect hand (preferrably right hand) points.
        // In case of no POI is found it displays a no result message. The number of POI is limited by the user.
        private async void addPOIToMapFromKinectHandPosition(params BingQueryFilters.BingQueryFilter[] queryFilters)
        {
            Microsoft.Maps.MapControl.WPF.Location handLocation = getLocationFromScreenPoint();
            if (null != handLocation)
            {
                // returns a NavteqPoiSchema.Response containing details of the POI nearby the location.
                var pois = await getPOIForLocation(handLocation.Latitude, handLocation.Longitude, queryFilters);

                // in case of no result is found, a no result message needs to be displayed
                if (pois != null && pois.ResultSet != null &&
                    pois.ResultSet.Results != null &&
                    pois.ResultSet.Results.Length > 0)
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        myMap.Children.Clear();
                        nearbyPlacesList.Visibility = Visibility.Visible;
                    });
                    foreach (var poi in pois.ResultSet.Results)
                    {
                        this.Dispatcher.Invoke(() =>
                        {
                            var loc      = new Microsoft.Maps.MapControl.WPF.Location(poi.Latitude, poi.Longitude);
                            var pin      = new Pushpin();
                            pin.Tag      = poi;
                            pin.Location = loc;
                            pin.Content  = "" + StaticVariables.POINumber;
                            myMap.Children.Add(pin);
                        });
                        BitmapImage poiImage = await getImageryOfPOI(new Coordinate(poi.Latitude, poi.Longitude));

                        addPOIToListView(poiImage, poi, StaticVariables.POINumber++);
                    }
                }
                else
                {
                    setSystemWarningMessagesToSpeechLabel(SystemMessages.NOPOI_MESSAGE);
                }
            }
        }
        /// <summary>
        /// needs to be on a worker thread, it is expensive
        /// </summary>
        /// <remarks>
        /// call like this
        /// Task.Factory.StartNew(LoadItemsOnMap, Task.Factory.CancellationToken, TaskCreationOptions.None, _context);
        /// Keep out of load and unload
        /// </remarks>
        private void LoadItemsOnMap()
        {
            var articles = new List<Article>();

            foreach (var feed in InterfaceDataSource.GetFeedsInSubscriptions())
            {
                articles.AddRange(feed.Articles);
            }

            char[] delim = { ' ' };

            var locations = articles.Select(article => article.Summary + article.Title)
                .Select(x => CsvAdapter.LookUpCity(x.Split(delim, StringSplitOptions.RemoveEmptyEntries)))
                .ToList();
            //first or default will not throw an exception, but it will add nulls, remove those
            locations.RemoveAll(t => t == null);

            foreach (var location in locations)
            {
                double latitude;
                double longitude;

                if (double.TryParse(location.Item2, out latitude) &&
                    double.TryParse(location.Item3, out longitude))
                {
                    var latAndLong = new Microsoft.Maps.MapControl.WPF.Location(latitude, longitude);
                    var pushPin = new Pushpin { Location = latAndLong };
                    // to handle changing main windows control to maininterface
                    pushPin.MouseDoubleClick += InterfaceDataSource.PushPin_MouseDoubleClick;

                    // to remove pushpins from map
                    pushPin.MouseDoubleClick += PushPin_MouseDoubleClick;

                    //Keep reference so we can delete from map easily
                    InterfaceDataSource.Pushpins.Add(pushPin);
                    //add a context menu maybe? or a mouse over event?
                    MyMap.Children.Add(pushPin);
                }
            }
        }
 private static IEnumerable<Location> GetCircle(double latitude, double longitude, double radius)
 {
     var center = new Location(latitude, longitude);
     return GetCircle(center, radius);
 }
 private static IEnumerable<Location> GetCircle(Location center, double radius)
 {
     for (int i = 0; i < 360; i++)
     {
         yield return CalculateDerivedPosition(center, radius, i);
     }
 }
        /// <summary>
        /// Calculates the end-point from a given source at a given range (meters) and bearing (degrees).
        /// This methods uses simple geometry equations to calculate the end-point.
        /// </summary>
        /// <param name="source">Point of origin</param>
        /// <param name="range">Range in meters</param>
        /// <param name="bearing">Bearing in degrees</param>
        /// <returns>End-point from the source given the desired range and bearing.</returns>
        private static Location CalculateDerivedPosition(Location source, double range, double bearing)
        {
            const double DEGREES_TO_RADIANS = Math.PI / 180D;
            const double EARTH_RADIUS_M = 6371000D;

            double latA = source.Latitude * DEGREES_TO_RADIANS;
            double lonA = source.Longitude * DEGREES_TO_RADIANS;
            double angularDistance = range / EARTH_RADIUS_M;
            double trueCourse = bearing * DEGREES_TO_RADIANS;

            double lat = Math.Asin(
                Math.Sin(latA) * Math.Cos(angularDistance) +
                Math.Cos(latA) * Math.Sin(angularDistance) * Math.Cos(trueCourse));

            double dlon = Math.Atan2(
                Math.Sin(trueCourse) * Math.Sin(angularDistance) * Math.Cos(latA),
                Math.Cos(angularDistance) - Math.Sin(latA) * Math.Sin(lat));

            double lon = ((lonA + dlon + Math.PI) % (Math.PI * 2)) - Math.PI;

            return new Location(
                lat / DEGREES_TO_RADIANS,
                lon / DEGREES_TO_RADIANS);
        }
        private void AddItemsToMap(List<Feed> feeds)
        {
            var articles = new List<Article>();

            foreach (var feed in feeds)
            {
                articles.AddRange(feed?.Articles);
            }

            char[] delim = { ' ' };

            foreach (Article article in articles)
            {
                string str = article.Title + article.Summary;
                var location = CsvAdapter.LookUpCity(str.Split(delim, StringSplitOptions.RemoveEmptyEntries));

                if (location != null)
                {
                    double latitude;
                    double longitude;

                    if (double.TryParse(location.Item2, out latitude) &&
                        double.TryParse(location.Item3, out longitude))
                    {
                        var latAndLong = new Microsoft.Maps.MapControl.WPF.Location(latitude, longitude);
                        var pushPin = new Pushpin { Location = latAndLong, Content = article.Title, Tag = article };
                        pushPin.ToolTip = pushPin.Content.ToString();

                        // to handle changing main windows control to maininterface
                        pushPin.MouseDoubleClick += InterfaceDataSource.PushPin_MouseDoubleClick;

                        // to remove pushpins from map
                        pushPin.MouseDoubleClick += PushPin_MouseDoubleClick;

                        // Keep reference for easy deletion from map
                        InterfaceDataSource.Pushpins.Add(pushPin);
                        //add a context menu maybe? or a mouse over event?
                        MyMap.Children.Add(pushPin);
                    }
                }
            }
        }
Exemplo n.º 39
0
        public static Location RandomLocationWithinPolygon(IList<Location> polygonPoints)
        {
            if (polygonPoints.Count < 3)
                return null;

            var border = PolygonBorder(polygonPoints);

            var random = new Random();

            while (true)
            {
                var randomLng = random.NextDouble()*(border.MaxLng - border.MinLng) + border.MinLng;
                var randomLat = random.NextDouble()*(border.MaxLat - border.MinLat) + border.MinLat;
                var randomLocation = new Location(randomLat, randomLng);

                if (IsPointInPolygon(polygonPoints, randomLocation))
                {
                    return randomLocation;
                }
            }
        }
        /// <summary>
        /// zooms the map to the address selected in the popup canvas
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void addressResultTree_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                hidePopupCanvas();
                SelectedObject selectedObject = ((SelectedObject)((TreeViewItem)addressResultTree.SelectedItem).Tag);
                GeographicPosition location = selectedObject.GeographicPosition;
                AddressType firstOrDefault = selectedObject.FirstOrDefault;
                Location loc = new Microsoft.Maps.MapControl.WPF.Location(Double.Parse(location.Latitude.ToString()), Double.Parse(location.Longitude.ToString()));
                locationMap.SetView(loc, getZoom(firstOrDefault));

            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
            }
        }