async void LookingFor_Loaded(object sender, RoutedEventArgs e) { Geolocator geolocator = new Geolocator(); //await Task.Delay(1500); Geoposition geoposition = null; try { geoposition = AppData.GeoPosition;// await geolocator.GetGeopositionAsync(); } catch (Exception ex) { // Handle errors like unauthorized access to location // services or no Internet access. } while (this.ViewModel.MatchingWhistles == null) { await Task.Delay(1000); } foreach (MatchingWhistles whistle in this.ViewModel.MatchingWhistles.matchingWhistles) { BasicGeoposition whistleLocation = new BasicGeoposition(); whistleLocation.Longitude = whistle.location.coordinates[0]; whistleLocation.Latitude = whistle.location.coordinates[1]; AddPushpin(whistleLocation, whistle.name, whistle._id); } myMapControl.Center = geoposition.Coordinate.Point; myMapControl.ZoomLevel = 15; }
public void AddPushpin(BasicGeoposition location, string text, string id) { var pin = new Grid() { Width = 50, Height = 50, Margin = new Windows.UI.Xaml.Thickness(-12) }; pin.Children.Add(new Image() { Source = new BitmapImage(new Uri("ms-appx:///Assets/pinPoint.png", UriKind.RelativeOrAbsolute)), Width = 50, Height = 50 }); pin.Children.Add(new TextBlock() { Text = text, FontSize = 12, Foreground = new SolidColorBrush(Colors.Yellow), HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center, VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center }); pin.Tag = id; pin.Tapped += pin_Tapped; MapControl.SetLocation(pin, new Geopoint(location)); myMapControl.Children.Add(pin); }
public MapView() { mapControl = new MapControl(); mapControl.ZoomInteractionMode = MapInteractionMode.GestureAndControl; mapControl.TiltInteractionMode = MapInteractionMode.GestureAndControl; mapControl.MapServiceToken = "ift37edNFjWtwMkOrquL~7gzuj1f0EWpVbWWsBaVKtA~Amh-DIg5R0ZPETQo7V-k2m785NG8XugPBOh52EElcvxaioPYSYWXf96wL6E_0W1g"; // Specify a known location BasicGeoposition cityPosition; Geopoint cityCenter; cityPosition = new BasicGeoposition() { Latitude = 2.4448143, Longitude = -76.6147395 }; cityCenter = new Geopoint(cityPosition); // Set map location mapControl.Center = cityCenter; mapControl.ZoomLevel = 13.0f; mapControl.LandmarksVisible = true; AddIcons(); this.Children.Add(mapControl); //this.Children.Add(_map); }
private async void handleResults(PhotoCollection results, ObservableCollection<ThumbnailImage> List) { foreach (var res in results) { Geopoint point = null; if (res.Longitude != 0 && res.Latitude != 0) { var position = new BasicGeoposition() { Latitude = res.Latitude, Longitude = res.Longitude }; point = new Geopoint(position); } else if (res.Tags.Contains("cars")) { var position = new BasicGeoposition() { Longitude = 13.416350, Latitude = 52.526105 }; point = new Geopoint(position); } List.Add(new ThumbnailImage() { ImagePath = new Uri(res.ThumbnailUrl), ImageTitle = res.Title, BigImage = new Uri(res.LargeUrl), GeoLocation = point }); } }
public BoundedImage(MapView map, Uri imageUri, BasicGeoposition northWest, BasicGeoposition southEast) { _map = map; _northWest = northWest; _southEast = southEast; _img = new Image(); _img.Stretch = Stretch.Fill; _img.Source = new BitmapImage(imageUri); this.Children.Add(_img); _map.ViewChanged += (center, zoom, heading) => { UpdatePosition(); }; _map.SizeChanged += (s, a) => { this.Width = _map.ActualWidth; this.Height = _map.ActualHeight; UpdatePosition(); }; UpdatePosition(); }
private async void showSpaceNeedleButton_Click(object sender, RoutedEventArgs e) { if (myMap.Is3DSupported) { this.myMap.Style = MapStyle.Aerial3DWithRoads; BasicGeoposition spaceNeedlePosition = new BasicGeoposition(); spaceNeedlePosition.Latitude = 47.6204; spaceNeedlePosition.Longitude = -122.3491; Geopoint spaceNeedlePoint = new Geopoint(spaceNeedlePosition); MapScene spaceNeedleScene = MapScene.CreateFromLocationAndRadius(spaceNeedlePoint, 400, /* show this many meters around */ 135, /* looking at it to the south east*/ 60 /* degrees pitch */); await myMap.TrySetSceneAsync(spaceNeedleScene); } else { string status = "3D views are not supported on this device."; rootPage.NotifyUser(status, NotifyType.ErrorMessage); } }
public static IEnumerable<PointList> GetRandomPoints(Geopoint point1, Geopoint point2, int nrOfPoints) { var result = new List<PointList>(); var p1 = new BasicGeoposition { Latitude = Math.Min(point1.Position.Latitude, point2.Position.Latitude), Longitude = Math.Min(point1.Position.Longitude, point2.Position.Longitude) }; var p2 = new BasicGeoposition { Latitude = Math.Max(point1.Position.Latitude, point2.Position.Latitude), Longitude = Math.Max(point1.Position.Longitude, point2.Position.Longitude) }; var dLat = p2.Latitude - p1.Latitude; var dLon = p2.Longitude - p1.Longitude; var r = new Random(DateTime.Now.Millisecond); for (var i = 0; i < nrOfPoints; i++) { var item = new PointList { Name = "Point " + i }; item.Points.Add(new Geopoint( new BasicGeoposition { Latitude = p1.Latitude + (r.NextDouble() * dLat), Longitude = p1.Longitude + (r.NextDouble() * dLon) })); result.Add(item); } return result; }
// http://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn631249.aspx public async Task<List<Portable.Model.GeocodeResult>> ExecuteQuery(string query) { throw new NotImplementedException("Not yet fully implemented, testing only"); try { // TODO: center for Austria (lat, lon), hint Austria in search string BasicGeoposition queryHint = new BasicGeoposition(); queryHint.Latitude = 47.643; queryHint.Longitude = -122.131; Geopoint hintPoint = new Geopoint(queryHint); MapLocationFinderResult result = await MapLocationFinder.FindLocationsAsync(query, hintPoint); if (result.Status == MapLocationFinderStatus.Success) { return result.Locations.Select(l => new Portable.Model.GeocodeResult() { Latitude = l.Point.Position.Latitude, Longitude = l.Point.Position.Longitude, Name = l.DisplayName, }).ToList(); } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } return new List<GeocodeResult>(); }
private async void InitializeMap() { var queryHintGeoPosition = new BasicGeoposition { Latitude = 47.643, Longitude = -122.131 }; var result = await MapLocationFinder.FindLocationsAsync(App.EventModel.EventAddress, new Geopoint(queryHintGeoPosition)); if (result != null && result.Locations.Count != 0) { await mapControl.TrySetViewAsync(result.Locations[0].Point, 16, 0, 0, MapAnimationKind.None); } var mapIconStreamReference = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/mappin.png")); var mapIcon = new MapIcon { Location = mapControl.Center, NormalizedAnchorPoint = new Point(0.5, 1.0), Title = "Event location", Image = mapIconStreamReference, ZIndex = 0 }; mapControl.MapElements.Add(mapIcon); }
public static List<BasicGeoposition> CalculateCircle(BasicGeoposition center, int radius) { List<BasicGeoposition> geoPositions = new List<BasicGeoposition>(); double earthRadius = 6371000D; double circunference = 2D * Math.PI * earthRadius; for (int i = 0; i <= 360; i++) { double bearing = ToRad(i); double circunferenceLatitudeCorrected = 2D * Math.PI * Math.Cos(ToRad(center.Latitude)) * earthRadius; double lat1 = circunference / 360D * center.Latitude; double lon1 = circunferenceLatitudeCorrected / 360D * center.Longitude; double lat2 = lat1 + Math.Sin(bearing) * radius; double lon2 = lon1 + Math.Cos(bearing) * radius; BasicGeoposition newBasicPosition = new BasicGeoposition(); newBasicPosition.Latitude = lat2 / (circunference / 360D); newBasicPosition.Longitude = lon2 / (circunferenceLatitudeCorrected / 360D); geoPositions.Add(newBasicPosition); } return geoPositions; }
private async void button_Click(object sender, RoutedEventArgs e) { if (MapControl1.IsStreetsideSupported) { BasicGeoposition cityPosition = new BasicGeoposition() { Latitude = 48.858, Longitude = 2.295 }; Geopoint cityCenter = new Geopoint(cityPosition); StreetsidePanorama panoramaNearCity = await StreetsidePanorama.FindNearbyAsync(cityCenter); if (panoramaNearCity != null) { StreetsideExperience ssView = new StreetsideExperience(panoramaNearCity); ssView.OverviewMapVisible = true; MapControl1.CustomExperience = ssView; } } else { ContentDialog viewNotSupportedDialog = new ContentDialog() { Title = "Streetside is not supported", Content = "\nStreetside views are not supported on this device.", PrimaryButtonText = "OK" }; await viewNotSupportedDialog.ShowAsync(); } }
public async Task<MapLocation> GetPositionFromAddressAsync(string address) { var locator = new Geolocator(); locator.DesiredAccuracyInMeters = 50; TimeSpan maxAge = new TimeSpan(0, 0, 1); TimeSpan timeout = new TimeSpan(0, 0, 15); // var position = await locator.GetGeopositionAsync(); var basicGeoposition = new BasicGeoposition(); var point = new Geopoint(basicGeoposition); var mapLocationFinderResult = await MapLocationFinder.FindLocationsAsync(address, point, 2); if (mapLocationFinderResult.Status == MapLocationFinderStatus.Success) { try { return mapLocationFinderResult.Locations[0]; } catch (Exception e) { return null; } } return default(MapLocation); }
private async void button1_Click(object sender, RoutedEventArgs e) { if (MapControl1.Is3DSupported) { MapControl1.Style = MapStyle.Aerial3D; BasicGeoposition hwGeoposition = new BasicGeoposition() { Latitude = 48.858, Longitude = 2.295 }; Geopoint hwPoint = new Geopoint(hwGeoposition); MapScene hwScene = MapScene.CreateFromLocationAndRadius(hwPoint, 80, 0, 60); await MapControl1.TrySetSceneAsync(hwScene, MapAnimationKind.Bow); } else { ContentDialog viewNotSupportedDialog = new ContentDialog() { Title = "3D is not supported", Content = "\n3D views are not supported on this device.", PrimaryButtonText = "OK" }; await viewNotSupportedDialog.ShowAsync(); } }
public static async void CalculateRoute(MapControl mapControl,double startLatitude, double startLongitude, double endLatitude, double endLongitude) { BasicGeoposition startLocation = new BasicGeoposition(); startLocation.Latitude = startLatitude; startLocation.Longitude = startLongitude; Geopoint startPoint = new Geopoint(startLocation); BasicGeoposition endLocation = new BasicGeoposition(); endLocation.Latitude = endLatitude; endLocation.Longitude = endLongitude; Geopoint endPoint = new Geopoint(endLocation); MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync( startPoint, endPoint, MapRouteOptimization.Time, MapRouteRestrictions.None); if (routeResult.Status == MapRouteFinderStatus.Success) { MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Colors.Aqua; viewOfRoute.OutlineColor = Colors.Black; mapControl.Routes.Add(viewOfRoute); await mapControl.TrySetViewBoundsAsync( routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.Bow); var distance = routeResult.Route.LengthInMeters.ToString(); } }
public LocationData(string name, string street, string streetNumber, string zipcode, string city, string country, int rating, double longitude, double latitude, List<string> openTimes, List<string> closeTimes, List<string> happyhourFrom, List<string> happyhourTo) { id = -1; this.name = name; this.street = street; this.streetNumber = streetNumber; this.zipcode = zipcode; this.city = city; this.country = country; this.rating = rating; this.longitude = longitude; this.latitude = latitude; position = new BasicGeoposition(); position.Longitude = longitude; position.Latitude = latitude; pubdays = new List<PubDay>(); for (int i = 0; i < 7; i++) { pubdays.Add(new PubDay(i)); } //getOpenAndClosingTime(openTimes, closeTimes, happyhourFrom, happyhourTo); }
public async Task LoadVehicleDetails() { listOfNewVehicles = new List<HSLVehicle>(); //Client request to get the data from the HSL server HttpClient httpClient = new HttpClient(); httpClient.MaxResponseContentBufferSize = 512000; string uri = "http://dev.hsl.fi/siriaccess/vm/json?operatorRef=HSL&" + DateTime.Now.Ticks.ToString(); HttpResponseMessage response = await httpClient.GetAsync(uri); try { response.EnsureSuccessStatusCode(); Stream StreamResponse = await response.Content.ReadAsStreamAsync(); DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(RootObject)); RootObject returnedData = (RootObject)s.ReadObject(StreamResponse); if (returnedData.Siri.ServiceDelivery.VehicleMonitoringDelivery.Count == 1) { try { CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher; await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { //Get the list of vehicles from the returned data var AllVehicle = from m in returnedData.Siri.ServiceDelivery.VehicleMonitoringDelivery[0].VehicleActivity select m; foreach (VehicleActivity singleVehicle in AllVehicle) { HSLVehicle hslVehicle = new HSLVehicle(); hslVehicle.LineRef = singleVehicle.MonitoredVehicleJourney.LineRef.value; hslVehicle.VehicleRef = singleVehicle.MonitoredVehicleJourney.VehicleRef.value; hslVehicle.Latitude = singleVehicle.MonitoredVehicleJourney.VehicleLocation.Latitude; hslVehicle.Longitude = singleVehicle.MonitoredVehicleJourney.VehicleLocation.Longitude; //Convert latitude and longitude to Geopoint BasicGeoposition queryHint = new BasicGeoposition(); queryHint.Latitude = hslVehicle.Latitude; queryHint.Longitude = hslVehicle.Longitude; hslVehicle.Location = new Geopoint(queryHint); //Add items to the observable collection listOfNewVehicles.Add(hslVehicle); //VehicleItems.Add(hslVehicle); } updateObservableCollectionVehicles(listOfNewVehicles); }); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } response.Dispose(); httpClient.Dispose(); }
public void AddPushpin(BasicGeoposition location, string text) { var pin = new Grid { Width = 200, Height = 100, Margin = new Thickness(-12), HorizontalAlignment = HorizontalAlignment.Left }; var pinImage = new Image { Source = new BitmapImage(new Uri("ms-appx:///Assets/my-position.png")), Width = 60, Height = 60}; pin.Children.Add(pinImage); pin.Children.Add(new TextBlock { TextTrimming = TextTrimming.CharacterEllipsis, Text = text, FontSize = 14, FontWeight = FontWeights.Bold, Foreground = new SolidColorBrush(Colors.Black), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top }); MapControl.SetLocation(pin, new Geopoint(location)); Map.Children.Add(pin); }
public LocationData() { id = -1; name = ""; street = ""; streetNumber = "0"; zipcode = "0000AA"; city = "Amsterdam"; country = "Nederland"; //longitude = 0.0; //latitude = 0.0; rating = 0; position = new BasicGeoposition(); pubdays = new List<PubDay>(); for (int i = 0; i < 7; i++) { pubdays.Add(new PubDay(i)); } /* List<string> time = new List<string>(); for (int i = 0; i < 7; i++) time.Add("00:00");*/ //getOpenAndClosingTime(time, time, time, time); }
private async void getAddressBtn_Click(object sender, RoutedEventArgs e) { try { //Request permission to get location //Pop up will occur if your app doesnot have permission to access location service of device var accessStatus = await Geolocator.RequestAccessAsync(); switch (accessStatus) { case GeolocationAccessStatus.Allowed: // The location to reverse geocode. //For now i am getting my current location Geolocator geolocator = new Geolocator { DesiredAccuracyInMeters = 50, DesiredAccuracy = PositionAccuracy.High }; //Set the desired accuracy that you want in meters Geoposition pos = await geolocator.GetGeopositionAsync(); BasicGeoposition location = new BasicGeoposition(); location.Latitude = pos.Coordinate.Point.Position.Latitude; location.Longitude = pos.Coordinate.Point.Position.Longitude; Geopoint pointToReverseGeocode = new Geopoint(location); // Reverse geocode the specified geographic location. MapLocationFinderResult result = await MapLocationFinder.FindLocationsAtAsync(pointToReverseGeocode); // If the query returns results, display the name of the town // contained in the address of the first result. if (result.Status == MapLocationFinderStatus.Success) { continent.Text = result.Locations[0].Address.Continent; countryName.Text = result.Locations[0].Address.Country; countryCode.Text = result.Locations[0].Address.CountryCode; region.Text = result.Locations[0].Address.Region; town.Text = result.Locations[0].Address.Town; street.Text = result.Locations[0].Address.Street; } else { await new MessageDialog("Something went wrong. Could not get finish current operation. Error: " + result.Status).ShowAsync(); } break; case GeolocationAccessStatus.Denied: //Unable to get data LoadPositionData(null); break; case GeolocationAccessStatus.Unspecified: //Unable to get data LoadPositionData(null); break; } } catch (Exception ex) { await new MessageDialog("Something went wrong. Could not get finish current operation.").ShowAsync(); } }
public void AddRegion(GeofenceCircularRegion region) { if (string.IsNullOrEmpty(region.Id)) return; RemoveRegion(region.Id); var position = new BasicGeoposition(); position.Latitude = region.Latitude; position.Longitude = region.Longitude; var geocircle = new Geocircle(position, region.Radius); Windows.Devices.Geolocation.Geofencing.MonitoredGeofenceStates mask = 0; if (region.NotifyOnEntry) { mask |= Windows.Devices.Geolocation.Geofencing.MonitoredGeofenceStates.Entered; } if (region.NotifyOnExit) { mask |= Windows.Devices.Geolocation.Geofencing.MonitoredGeofenceStates.Exited; } var geofence = new Windows.Devices.Geolocation.Geofencing.Geofence(region.Id, geocircle, mask, false, new TimeSpan(0, 0, CrossGeofence.StayedInDuration / 1000), DateTime.Now, TimeSpan.MaxValue); Windows.Devices.Geolocation.Geofencing.GeofenceMonitor.Current.Geofences.Add(geofence); GeofenceStore.SharedInstance.Save(region); }
public AddMapa() { this.InitializeComponent(); rootFrame = Window.Current.Content as Frame; SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible; SystemNavigationManager.GetForCurrentView().BackRequested += AddMapa_BackRequested; mapControl.ZoomInteractionMode = MapInteractionMode.GestureAndControl; mapControl.TiltInteractionMode = MapInteractionMode.GestureAndControl; mapControl.MapServiceToken = "ift37edNFjWtwMkOrquL~7gzuj1f0EWpVbWWsBaVKtA~Amh-DIg5R0ZPETQo7V-k2m785NG8XugPBOh52EElcvxaioPYSYWXf96wL6E_0W1g"; // Specify a known location BasicGeoposition posicion = new BasicGeoposition() { Latitude = 2.4448143, Longitude = -76.6147395 }; Geopoint point = new Geopoint(posicion); // Set map location mapControl.Center = point; mapControl.ZoomLevel = 13.0f; mapControl.LandmarksVisible = true; AddIcons(); //GridMapa.Children.Add(mapControl); }
private BasicGeoposition GetAtDistanceBearing(BasicGeoposition point, double distance, double bearing) { double degreesToRadian = Math.PI / 180.0; double radianToDegrees = 180.0 / Math.PI; double earthRadius = 6378137.0; double latA = point.Latitude * degreesToRadian; double lonA = point.Longitude * degreesToRadian; double angularDistance = distance / earthRadius; double trueCourse = bearing * degreesToRadian; 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; BasicGeoposition result = new BasicGeoposition { Latitude = lat * radianToDegrees, Longitude = lon * radianToDegrees }; return result; }
public static BasicGeoposition GetAtDistanceBearing(this BasicGeoposition point, double distance, double bearing) { const double degreesToRadian = Math.PI / 180.0; const double radianToDegrees = 180.0 / Math.PI; const double earthRadius = 6378137.0; var latA = point.Latitude * degreesToRadian; var lonA = point.Longitude * degreesToRadian; var angularDistance = distance / earthRadius; var trueCourse = bearing * degreesToRadian; var lat = Math.Asin( Math.Sin(latA) * Math.Cos(angularDistance) + Math.Cos(latA) * Math.Sin(angularDistance) * Math.Cos(trueCourse)); var dlon = Math.Atan2( Math.Sin(trueCourse) * Math.Sin(angularDistance) * Math.Cos(latA), Math.Cos(angularDistance) - Math.Sin(latA) * Math.Sin(lat)); var lon = ((lonA + dlon + Math.PI) % (Math.PI * 2)) - Math.PI; var result = new BasicGeoposition { Latitude = lat * radianToDegrees, Longitude = lon * radianToDegrees }; return result; }
public object Convert(object value, Type targetType, object parameter, string language) { var coord = value as ObservableCoordinate; if (coord != null) { var position = new BasicGeoposition { Latitude = coord.Latitude, Longitude = coord.Longitude }; return new Geopoint(position); } var viewmodel = value as CafeSummaryViewModel; if (viewmodel != null) { var position = new BasicGeoposition { Latitude = viewmodel.Latitude, Longitude = viewmodel.Longitude }; return new Geopoint(position); } return value; }
/// <summary> /// /// </summary> /// <param name="position"></param> public Geopoint(BasicGeoposition position) { #if WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP || WINDOWS_PHONE_81 _point = new Windows.Devices.Geolocation.Geopoint(position); #else Position = position; #endif }
//将 GCJ-02 坐标转换成 BD-09 坐标(火星转百度) public static BasicGeoposition bd_encrypt(BasicGeoposition gcjPosition) { double x = gcjPosition.Longitude, y = gcjPosition.Latitude; double z = Math.Sqrt(x * x + y * y) + 0.00002 * Math.Sin(y * x_pi); double theta = Math.Atan2(y, x) + 0.000003 * Math.Cos(x * x_pi); return new BasicGeoposition { Longitude = z * Math.Cos(theta) + 0.0065, Latitude = z * Math.Sin(theta) + 0.006 }; }
//将 BD-09 坐标转换成 GCJ-02坐标(百度转火星) public static BasicGeoposition bd_decrypt(BasicGeoposition bdPosition) { double x = bdPosition.Longitude - 0.0065, y = bdPosition.Latitude - 0.006; double z = Math.Sqrt(x * x + y * y) - 0.00002 * Math.Sin(y * x_pi); double theta = Math.Atan2(y, x) - 0.000003 * Math.Cos(x * x_pi); return new BasicGeoposition { Longitude = z * Math.Cos(theta), Latitude = z * Math.Sin(theta) }; }
public LocationData(String name, double latitude, double longitude, int geofenceradius) { this.name = name; this.position = new BasicGeoposition(); this.position.Longitude = longitude; this.position.Latitude = latitude; standardGeofenceRadius = geofenceradius; }
static bool outOfChina(BasicGeoposition geoposition) { if (geoposition.Longitude < 72.004 || geoposition.Longitude > 137.8347) return true; if (geoposition.Latitude < 0.8293 || geoposition.Latitude > 55.8271) return true; return false; }
public static GeoboundingBox GetBounds(this MapControl map, double extraPercentage) { Geopoint topLeft = null; try { map.GetLocationFromOffset(new Point(0, 0), out topLeft); } catch { var topOfMap = new Geopoint(new BasicGeoposition() { Latitude = 85, Longitude = 0 }); Point topPoint; map.GetOffsetFromLocation(topOfMap, out topPoint); map.GetLocationFromOffset(new Point(0, topPoint.Y), out topLeft); } Geopoint bottomRight = null; try { map.GetLocationFromOffset(new Point(map.ActualWidth, map.ActualHeight), out bottomRight); } catch { var bottomOfMap = new Geopoint(new BasicGeoposition() { Latitude = -85, Longitude = 0 }); Point bottomPoint; map.GetOffsetFromLocation(bottomOfMap, out bottomPoint); map.GetLocationFromOffset(new Point(0, bottomPoint.Y), out bottomRight); } if (topLeft != null && bottomRight != null) { var width = Abs(bottomRight.Position.Longitude - topLeft.Position.Longitude); var height = Abs(bottomRight.Position.Latitude - topLeft.Position.Latitude); var adjustedTopLeft = new BasicGeoposition() { Latitude = topLeft.Position.Latitude + extraPercentage * height, Longitude = topLeft.Position.Longitude - extraPercentage * width, }; var adjustedBottomRight = new BasicGeoposition() { Latitude = bottomRight.Position.Latitude - extraPercentage * height, Longitude = bottomRight.Position.Longitude + extraPercentage * width, }; return new GeoboundingBox(adjustedTopLeft, adjustedBottomRight); } return null; }
/// <summary> /// 情報書き込み /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void Button_Click_2(object sender, RoutedEventArgs e) { var cur = Directory.GetCurrentDirectory(); // exeのあるディレクトリ var filepath = cur + @"\ginga.bmp"; // 元の画像 var filepath_out_jpg = cur + @"\ginga_out.jpg"; // jpgとして保存する画像 var filepath_out_bmp = cur + @"\ginga_out_fake.jpg"; // bmpとして保存する画像 using (var fs = new FileStream(filepath, FileMode.Open, FileAccess.ReadWrite)) using (var bmp = new System.Drawing.Bitmap(fs)) { // 元の画像を、jpgとbmpで保存し分ける bmp.Save(filepath_out_jpg, System.Drawing.Imaging.ImageFormat.Jpeg); bmp.Save(filepath_out_bmp, System.Drawing.Imaging.ImageFormat.Bmp); } // GPS値作成 BasicGeoposition bgps = new BasicGeoposition() { Latitude = 3.0, Longitude = 2.0, Altitude = 1.0 }; // GPS値をGeopointにセット Geopoint gps = new Geopoint(bgps); try { // GPS値をjpgファイルに書き込み var stjpg = await Windows.Storage.StorageFile.GetFileFromPathAsync(filepath_out_jpg); await GeotagHelper.SetGeotagAsync(stjpg, gps);// →こっちは問題なくgeotag付与できる var stbmp = await Windows.Storage.StorageFile.GetFileFromPathAsync(filepath_out_bmp); await GeotagHelper.SetGeotagAsync(stbmp, gps);// →こっちは、jpgではないのでgeotag付与時に例外発生 } catch (Exception ex) { Console.WriteLine(ex.Message); } }
protected override void OnElementChanged(ElementChangedEventArgs <Map> e) { base.OnElementChanged(e); if (e.OldElement != null) { nativeMap.MapElementClick -= OnMapElementClick; nativeMap.Children.Clear(); markerWindow = null; nativeMap = null; } if (e.NewElement != null) { this.Pet = (e.NewElement as CustomMap).Pet; var formsMap = (CustomMap)e.NewElement; nativeMap = Control as MapControl; nativeMap.Children.Clear(); nativeMap.MapElementClick += OnMapElementClick; var snPosition = new BasicGeoposition { Latitude = Pet.Latitude, Longitude = Pet.Longitude }; var snPoint = new Geopoint(snPosition); var mapIcon = new MapIcon(); mapIcon.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///pin.png")); //cuando se hace zoom siempre será visible mapIcon.CollisionBehaviorDesired = MapElementCollisionBehavior.RemainVisible; mapIcon.Location = snPoint; //cooirdenadas generadas anteriormente mapIcon.NormalizedAnchorPoint = new Windows.Foundation.Point(0.5, 1.0); //tamaño del icono nativeMap.MapElements.Add(mapIcon); } }
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName.Equals("CustomPins")) { customPins = ((CustomMap)Element).CustomPins; if (customPins != null) { foreach (var pin in customPins) { var snPosition = new BasicGeoposition() { Latitude = pin.Position.Latitude, Longitude = pin.Position.Longitude }; var snPoint = new Geopoint(snPosition); var mapIcon = new MapIcon(); mapIcon.Location = snPoint; nativaMap.MapElements.Add(mapIcon); } } } }
private async void SearchButton_Click(object sender, RoutedEventArgs e) { MapListBoxItem.IsSelected = true; if (!(string.IsNullOrWhiteSpace(SearchTextBox.Text))) { string addressToGeocode = SearchTextBox.Text; MapData mapData = MapData.GetInstance(); // The nearby location to use as a query hint. BasicGeoposition queryHint = new BasicGeoposition { Latitude = 55.753215, Longitude = 37.622504 }; Geopoint hintPoint = new Geopoint(queryHint); MapLocationFinderResult result = await MapLocationFinder.FindLocationsAsync(addressToGeocode, hintPoint, 3); if (result.Status == MapLocationFinderStatus.Success) { try { mapData.Latitude = result.Locations[0].Point.Position.Latitude; mapData.Longitude = result.Locations[0].Point.Position.Longitude; } catch (ArgumentOutOfRangeException) { MessageDialog md = new MessageDialog("По вашему запросу ничего не найдено!"); await md.ShowAsync(); } MyFrame.Navigate(typeof(Map), mapData); } else { MessageDialog md = new MessageDialog("Ничего не найдено! \nПопробуйте еще раз!"); await md.ShowAsync(); } this.SearchTextBox.Text = ""; } }
public async Task <int[]> CalculateSunTime(bool background) { int[] sundate = new int[4]; int[] sun = new int[2]; if (!background) { BasicGeoposition position = await GetUserPosition(); Properties.Settings.Default.LocationLatitude = position.Latitude; Properties.Settings.Default.LocationLongitude = position.Longitude; sun = SunDate.CalculateSunriseSunset(position.Latitude, position.Longitude); } else if (background) { sun = SunDate.CalculateSunriseSunset(Properties.Settings.Default.LocationLatitude, Properties.Settings.Default.LocationLongitude); } sundate[0] = new DateTime(1, 1, 1, sun[0] / 60, sun[0] - (sun[0] / 60) * 60, 0).Hour; //sunrise hour sundate[1] = new DateTime(1, 1, 1, sun[0] / 60, sun[0] - (sun[0] / 60) * 60, 0).Minute; //sunrise minute sundate[2] = new DateTime(1, 1, 1, sun[1] / 60, sun[1] - (sun[1] / 60) * 60, 0).Hour; //sunset hour sundate[3] = new DateTime(1, 1, 1, sun[1] / 60, sun[1] - (sun[1] / 60) * 60, 0).Minute; //sunset minute return(sundate); }
private async void SetGeotagButton_Click() { // Set the approximate position of the observation deck of the Seattle Space Needle. BasicGeoposition position = new BasicGeoposition(); position.Latitude = 47.620491; position.Longitude = -122.349319; position.Altitude = 158.12; Geopoint geopoint = new Geopoint(position); try { await GeotagHelper.SetGeotagAsync(file, geopoint); rootPage.NotifyUser("Geolocation set to Seattle Space Needle", NotifyType.StatusMessage); } catch (Exception ex) { // File I/O errors are reported as exceptions rootPage.NotifyUser("Exception: " + ex.Message, NotifyType.ErrorMessage); } }
public void popuniMapu() { foreach (Model.Parking p in System.parkings) { foreach (Model.Location l in System.locations) { if (l.id == p.pLocation) { BasicGeoposition snPosition = new BasicGeoposition() { Latitude = l.x, Longitude = l.y }; var pk = new ParkingKontrola(p.Name, p.Capacity.ToString(), p.freePlaces.ToString()); mapa.Children.Add(pk); var position = new Geopoint(snPosition); MapControl.SetLocation(pk, position); MapControl.SetNormalizedAnchorPoint(pk, new Point(0.5, 0.5)); } } } }
private async Task SetGeotagAsync() { try { StorageFile file = await KnownFolders.PicturesLibrary.GetFileAsync(filename.Text); BasicGeoposition position = new BasicGeoposition(); position.Latitude = 10.0; // Use latitude 10.0, longitude 20.0 as an example position.Longitude = 20.0; position.Altitude = 0.0; Geopoint geopoint = new Geopoint(position); await GeotagHelper.SetGeotagAsync(file, geopoint); LogStatus("SetGeotagAsync complete"); } catch (Exception e) { // File I/O errors are reported as exceptions LogError("Exception: " + e.Message); } }
private async void AddIcons() { //Query ParseQuery <ParseObject> query = ParseObject.GetQuery("Lugares"); IEnumerable <ParseObject> results = await query.FindAsync(); ParseObject lugar; ParseGeoPoint ubicacion; BasicGeoposition position; Geopoint point; MapIcon mapIcon; // Agregarlos al mapa int tamanio = results.Count <ParseObject>(); for (int i = 0; i < tamanio; i++) { lugar = results.ElementAt <ParseObject>(i); ubicacion = lugar.Get <ParseGeoPoint>("ubicacion"); //Icon position = new BasicGeoposition() { Latitude = ubicacion.Latitude, Longitude = ubicacion.Longitude }; point = new Geopoint(position); // MapIcon mapIcon = new MapIcon(); mapIcon.Location = point; mapIcon.NormalizedAnchorPoint = new Point(0.5, 1.0); mapIcon.Title = lugar.Get <string>("nombre") + " " + lugar.Get <string>("direccion"); mapIcon.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/bus.jpg")); mapIcon.ZIndex = 0; //Añadiendo el Icono mapControl.MapElements.Add(mapIcon); } }
public void Sum_InputTwoVectorsOfOnes_ReturnVectorOfTwos() { var input = new BasicGeoposition() { Latitude = 1, Longitude = 1, Altitude = 1 }; var result = GeoMath.Sum(input, input); var expect = new BasicGeoposition() { Latitude = 2, Longitude = 2, Altitude = 2 }; Assert.AreEqual(expect.Latitude, result.Latitude, 0.000001, $@"Result latitude mismatch. Expected: {expect.Latitude}, Actual: {result.Latitude}"); Assert.AreEqual(expect.Longitude, result.Longitude, 0.000001, $@"Result Longitude mismatch. Expected: {expect.Longitude}, Actual: {result.Longitude}"); Assert.AreEqual(expect.Altitude, result.Altitude, 0.000001, $@"Result Altitude mismatch. Expected: {expect.Altitude}, Actual: {result.Altitude}"); }
public void Difference_InputTwoVectorsOfOnes_ReturnZeroVector() { var input = new BasicGeoposition() { Latitude = 1, Longitude = 1, Altitude = 1 }; var result = GeoMath.Difference(input, input); var expect = new BasicGeoposition() { Latitude = 0, Longitude = 0, Altitude = 0 }; Assert.AreEqual(expect.Latitude, result.Latitude, 0.000001, $@"Result latitude mismatch. Expected: {expect.Latitude}, Actual: {result.Latitude}"); Assert.AreEqual(expect.Longitude, result.Longitude, 0.000001, $@"Result Longitude mismatch. Expected: {expect.Longitude}, Actual: {result.Longitude}"); Assert.AreEqual(expect.Altitude, result.Altitude, 0.000001, $@"Result Altitude mismatch. Expected: {expect.Altitude}, Actual: {result.Altitude}"); }
private void AddStopToMap(BusStop stop) { MapIcon mico = new MapIcon(); mico.ZIndex = 10; mico.Location = new Geopoint(stop.Position); mico.CollisionBehaviorDesired = MapElementCollisionBehavior.RemainVisible; string size = ZoomLevel < StopSizeThreshold ? "20" : "40"; bool visibility = ZoomLevel >= StopVisibilityThreshold; mico.Image = RandomAccessStreamReference.CreateFromUri(new Uri(stop.Direction == StopDirection.Unspecified ? "ms-appx:///Assets/Icons/BusBase" + size + ".png" : "ms-appx:///Assets/Icons/BusDirection" + stop.Direction.ToString() + size + ".png")); mico.NormalizedAnchorPoint = new Point(0.5, 0.5); mico.Visible = visibility; MainMap.MapElements.Add(mico); Stops[mico] = stop; BusStopIcons.Add(mico); polygonCenter = stop.Position; SetPolygonSize(); }
public async Task <object> DistanceMatrix(BasicGeoposition origin, IEnumerable <BasicGeoposition> destinations) { string json = JsonConvert.SerializeObject(new { origins = new[] { new { latitude = origin.Latitude, longitude = origin.Longitude } }, destinations = destinations.Select(dest => new { latitude = dest.Latitude, longitude = dest.Longitude }), travelMode = "driving", timeUnit = "minute" }); using (var httpClient = new HttpClient()) { var responseMessage = await httpClient.PostAsync(new Uri(string.Format(DistanceMatrixEndPoint, _bingMapsKey), UriKind.Absolute), new StringContent(json, Encoding.UTF8, "application/json")); if (responseMessage.IsSuccessStatusCode) { return(await responseMessage.Content.ReadAsStringAsync()); } return(null); } }
public async Task <MapRouteView> GetRouteViewForMap(BasicGeoposition startPos, BasicGeoposition endPos) { // Get the route between the points. MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync( new Geopoint(startPos), new Geopoint(endPos), MapRouteOptimization.Time, MapRouteRestrictions.None); if (routeResult.Status == MapRouteFinderStatus.Success) { // Use the route to initialize a MapRouteView. MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Colors.Yellow; viewOfRoute.OutlineColor = Colors.Black; return(viewOfRoute); } return(null); }
public static async Task <MapAddress> CoordsToAddress(double lat, double lon) { // The location to reverse geocode. BasicGeoposition location = new BasicGeoposition(); location.Latitude = lat; location.Longitude = lon; Geopoint pointToReverseGeocode = new Geopoint(location); // Reverse geocode the specified geographic location. MapLocationFinderResult result = await MapLocationFinder.FindLocationsAtAsync(pointToReverseGeocode); // If the query returns results, display the name of the town // contained in the address of the first result. if (result.Status == MapLocationFinderStatus.Success) { return(result.Locations[0].Address); } return(null); }
private async void MyMap_Loaded(object sender, RoutedEventArgs e) { if (MyMap.Is3DSupported) { MyMap.Style = MapStyle.Aerial3DWithRoads; MyMap.StyleSheet = MapStyleSheet.RoadDark(); BasicGeoposition geoPosition = new BasicGeoposition(); geoPosition.Latitude = 41.790366; geoPosition.Longitude = -6.760116; Geopoint myPoint = new Geopoint(geoPosition); MyMap.Center = myPoint; MyMap.ZoomLevel = 10; MapScene hwScene = MapScene.CreateFromLocationAndRadius(myPoint, 80, 0, 60); await MyMap.TrySetSceneAsync(hwScene, MapAnimationKind.Bow); MapScene mapScene = MapScene.CreateFromLocationAndRadius(new Geopoint(geoPosition), 500, 150, 70); await MyMap.TrySetSceneAsync(mapScene); } }
private async Task DisplayDrivers(BasicGeoposition geoposition, LyftConstants.RideType rideType) { var nearbyDrivers = await AppConstants.ShyftClient.RetrieveNearbyDrivers(geoposition.Latitude, geoposition.Longitude); ClearDriversList(); foreach (var nearbyDriver in nearbyDrivers) { if (nearbyDriver.RideType == rideType) { foreach (var driver in nearbyDriver.Drivers) { driverList.Add(CreatePin(driver.Locations.Last())); } break; } } foreach (var driver in driverList) { map.MapElements.Add(driver); } }
void LoadUserPosition(Geocoordinate userCoordinate, bool center) { var userPosition = new BasicGeoposition { Latitude = userCoordinate.Point.Position.Latitude, Longitude = userCoordinate.Point.Position.Longitude }; var point = new Geopoint(userPosition); if (_userPositionCircle == null) { _userPositionCircle = new Ellipse { Stroke = new SolidColorBrush(Colors.White), Fill = new SolidColorBrush(Colors.Blue), StrokeThickness = 2, Height = 20, Width = 20, Opacity = 50 }; } if (Control.Children.Contains(_userPositionCircle)) { Control.Children.Remove(_userPositionCircle); } MapControl.SetLocation(_userPositionCircle, point); MapControl.SetNormalizedAnchorPoint(_userPositionCircle, new Windows.Foundation.Point(0.5, 0.5)); Control.Children.Add(_userPositionCircle); if (center) { Control.Center = point; Control.ZoomLevel = 13; } }
private void OnMapElementClick(MapControl sender, MapElementClickEventArgs e) { var mapIcon = e.MapElements.FirstOrDefault(x => x is MapIcon) as MapIcon; if (mapIcon != null) { if (!CustomPinControlShown) { var customPin = GetCustomPin(mapIcon.Location.Position); if (customPin == null) { throw new Exception("Custom pin not found"); } customPinControl = new CustomPinControl(customPin); var customPinControls = nativaMap.Children.Where(x => x is CustomPinControl); foreach (var control in customPinControls) { nativaMap.Children.Remove(control); } var snPosition = new BasicGeoposition() { Latitude = customPin.Position.Latitude, Longitude = customPin.Position.Longitude }; var snPoint = new Geopoint(snPosition); nativaMap.Children.Add(customPinControl); MapControl.SetLocation(customPinControl, snPoint); MapControl.SetNormalizedAnchorPoint(customPinControl, new Windows.Foundation.Point(0.5, 1.0)); CustomPinControlShown = true; } else { nativaMap.Children.Remove(customPinControl); CustomPinControlShown = false; } } }
protected async override void OnNavigatedTo(NavigationEventArgs e) { // Replace MAP_SERVICE_TOKEN with token from bing maps dev center MyMap.MapServiceToken = "MAP_SERVICE_TOKEN"; // Use the device's Geolocator to find it's physical location Geopoint myPoint; if (e.Parameter == null) { // Add isViewing = false; var locator = new Geolocator(); locator.DesiredAccuracyInMeters = 50; /* Add Location capability in the Package.appxmanifest file */ var position = await locator.GetGeopositionAsync(); myPoint = position.Coordinate.Point; } else { // View or Delete isViewing = true; mapNote = (MapNote)e.Parameter; titleTextBox.Text = mapNote.Title; noteTextBox.Text = mapNote.Note; addButton.Content = "Delete"; var myPosition = new BasicGeoposition(); myPosition.Latitude = mapNote.Latitude; myPosition.Longitude = mapNote.Longitude; myPoint = new Geopoint(myPosition); } await MyMap.TrySetViewAsync(myPoint, 10D); }
private async void ShowRouteOnMap() { origin = new BasicGeoposition() { Latitude = ViewModel.Flight.Origine.Lattitude, Longitude = ViewModel.Flight.Origine.Longitude }; destination = new BasicGeoposition() { Latitude = ViewModel.Flight.Bestemming.Lattitude, Longitude = ViewModel.Flight.Bestemming.Longitude }; BasicGeoposition middle = new BasicGeoposition() { Latitude = (origin.Latitude + destination.Latitude) / 2, Longitude = (origin.Longitude + destination.Longitude) / 2 }; Geopoint middleGeopoint = new Geopoint(middle); lineTravelled = new MapPolyline(); line = new MapPolyline(); calculatePointBasedOnPercentage(0.20); lineTravelled.Path = new Geopath(new List <BasicGeoposition> { origin, travelled }); lineTravelled.StrokeColor = Colors.Turquoise; lineTravelled.StrokeThickness = 6; map.MapElements.Add(lineTravelled); line.Path = new Geopath(new List <BasicGeoposition> { travelled, destination }); line.StrokeColor = Colors.White; line.StrokeThickness = 5; line.StrokeDashed = true; map.MapElements.Add(line); await map.TrySetViewAsync(middleGeopoint, 4.8, 0, 30, MapAnimationKind.Bow); }
public async Task <string> GetCityName() { BasicGeoposition position = await GetUserPosition(); Geopoint geopoint = new Geopoint(new BasicGeoposition { Latitude = position.Latitude, Longitude = position.Longitude }); var source = new CancellationTokenSource(1500); MapLocationFinderResult result = await MapLocationFinder.FindLocationsAtAsync(geopoint, MapLocationDesiredAccuracy.Low).AsTask(source.Token); if (result.Status == MapLocationFinderStatus.Success) { return(result.Locations[0].Address.Town); } else { return(null); } }
private void OnMapElementClick(MapControl sender, MapElementClickEventArgs args) { var mapIcon = args.MapElements.FirstOrDefault(x => x is MapIcon) as MapIcon; if (mapIcon != null) { if (!xamarinOverlayShown) { var customPin = GetCustomPin(mapIcon.Location.Position); if (customPin == null) { throw new Exception("Custom pin not found"); } if (customPin.Id.ToString() == "Xamarin") { if (mapOverlay == null) { mapOverlay = new XamarinMapOverlay(customPin); } var snPosition = new BasicGeoposition { Latitude = customPin.Position.Latitude, Longitude = customPin.Position.Longitude }; var snPoint = new Geopoint(snPosition); nativeMap.Children.Add(mapOverlay); MapControl.SetLocation(mapOverlay, snPoint); MapControl.SetNormalizedAnchorPoint(mapOverlay, new Windows.Foundation.Point(0.5, 1.0)); xamarinOverlayShown = true; } } else { nativeMap.Children.Remove(mapOverlay); xamarinOverlayShown = false; } } }
/// <summary> /// Afstand ophalen tussen werkgever en werknemer /// </summary> /// <param name="locatie">locatie van vacature</param> /// bron : http://www.codecodex.com/wiki/Calculate_distance_between_two_points_on_a_globe#C.23 /// <returns>double met afstand</returns> public async Task <double> getDistance(string locatie) { //The addresses to geocode. string addressToGeocode = Login.loggedInUser.location; string addressToGeocode2 = locatie; //Query hint BasicGeoposition queryHint = new BasicGeoposition(); queryHint.Latitude = 47.643; queryHint.Longitude = -122.131; Geopoint hintPoint = new Geopoint(queryHint); MapLocationFinderResult result = await MapLocationFinder.FindLocationsAsync( addressToGeocode, hintPoint, 3); MapLocationFinderResult result2 = await MapLocationFinder.FindLocationsAsync( addressToGeocode2, hintPoint, 3); var sCoord = new Position() { Latitude = result.Locations[0].Point.Position.Latitude, Longitude = result.Locations[0].Point.Position.Longitude }; var eCoord = new Position() { Latitude = result2.Locations[0].Point.Position.Latitude, Longitude = result2.Locations[0].Point.Position.Longitude }; var haversine = new Haversine(); double distance = haversine.Distance(sCoord, eCoord, DistanceType.Kilometers); return(distance); }
public void AddPushpin(BasicGeoposition location, string text) { #if WINDOWS_APP var pin = new Pushpin() { Text = text }; MapLayer.SetPosition(pin, location.ToLocation()); _pinLayer.Children.Add(pin); #elif WINDOWS_PHONE_APP var pin = new Grid() { Width = 24, Height = 24, Margin = new Windows.UI.Xaml.Thickness(-12) }; pin.Children.Add(new Ellipse() { Fill = new SolidColorBrush(Colors.DodgerBlue), Stroke = new SolidColorBrush(Colors.White), StrokeThickness = 3, Width = 24, Height = 24 }); pin.Children.Add(new TextBlock() { Text = text, FontSize = 12, Foreground = new SolidColorBrush(Colors.White), HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center, VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center }); MapControl.SetLocation(pin, new Geopoint(location)); _map.Children.Add(pin); #endif }
private void MarcarPosicionActual(CustomMap mapCustom) { try { mapControl.MapElements.Clear(); if (mapCustom.UbicacionActual != null) { BasicGeoposition basicGeoposition = new BasicGeoposition { Latitude = mapCustom.UbicacionActual.Latitud.Value, Longitude = mapCustom.UbicacionActual.Longitud.Value }; Geopoint geopoint = new Geopoint(basicGeoposition); MapIcon mapIcon = new MapIcon(); mapIcon.CollisionBehaviorDesired = MapElementCollisionBehavior.RemainVisible; mapIcon.Location = geopoint; mapIcon.NormalizedAnchorPoint = new Windows.Foundation.Point(0.5, 1.0); mapControl.MapElements.Add(mapIcon); } } catch { } }
private void UpdatePosition(double latitude, double longitude) { try { var position = new BasicGeoposition(); position.Latitude = latitude; position.Longitude = longitude; var location = new Geopoint(position); var mapScene = MapScene.CreateFromLocationAndRadius(location, 500); var trySetSceneAsync = WorldMap.TrySetSceneAsync(mapScene); if (!trySetSceneAsync.GetResults()) { Debug.WriteLine("Set scene failed but that's okay."); } } catch (Exception ex) { Debug.WriteLine(ex); } }
private async void ShowRouteOnMap() { // Start at Microsoft in Redmond, Washington. BasicGeoposition startLocation = new BasicGeoposition() { Latitude = 56.31, Longitude = 44.00 }; // End at the city of Seattle, Washington. BasicGeoposition endLocation = new BasicGeoposition() { Latitude = 56.00, Longitude = 44.00 }; // Get the route between the points. MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync( new Geopoint(startLocation), new Geopoint(endLocation)); if (routeResult.Status == MapRouteFinderStatus.Success) { // Use the route to initialize a MapRouteView. MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Colors.Yellow; viewOfRoute.OutlineColor = Colors.Black; // Add the new MapRouteView to the Routes collection // of the MapControl. myMap.Routes.Add(viewOfRoute); // Fit the MapControl to the route. await myMap.TrySetViewBoundsAsync( routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.None); } }
protected override void OnElementChanged(ElementChangedEventArgs <Map> e) { base.OnElementChanged(e); if (e.OldElement != null) { _nativeMap.MapElementClick -= OnMapElementClick; _nativeMap.Children.Clear(); _nativeMap = null; } if (e.NewElement != null) { var formsMap = (CustomMap)e.NewElement; _nativeMap = Control; _pins = formsMap.Pins.ToList(); _nativeMap.Children.Clear(); _nativeMap.MapElementClick += OnMapElementClick; foreach (var pin in _pins) { var snPosition = new BasicGeoposition { Latitude = pin.Position.Latitude, Longitude = pin.Position.Longitude }; var snPoint = new Geopoint(snPosition); var mapIcon = new MapIcon { Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///ic_coffee_bean.png")), CollisionBehaviorDesired = MapElementCollisionBehavior.RemainVisible, Location = snPoint, NormalizedAnchorPoint = new Windows.Foundation.Point(0.5, 1.0), }; _nativeMap.MapElements.Add(mapIcon); } } }
/*Method gets the users Current location and passes the Long/Lat to the Bing Map showing you your current location */ private async void GetUserLocation() { var accessStatus = await Geolocator.RequestAccessAsync(); switch (accessStatus) { case GeolocationAccessStatus.Allowed: try { Geolocator _geolocator = new Geolocator { DesiredAccuracyInMeters = 10 }; Geoposition pos = await _geolocator.GetGeopositionAsync(); BasicGeoposition geo = new BasicGeoposition(); geo.Latitude = pos.Coordinate.Point.Position.Latitude; geo.Longitude = pos.Coordinate.Point.Position.Longitude; BingMap.Center = new Geopoint(geo); //Center Map on geolocation BingMap.ZoomLevel = 7; //Sets the zoom level on the map } catch (Exception) { } BingMap.Height = SpMap.ActualHeight; //important, sets height to stackpannels height break; case GeolocationAccessStatus.Denied: //Please turn your location on break; case GeolocationAccessStatus.Unspecified: GetUserLocation(); break; } }