private async void SaveTheCar() { Car.Geo = UserCurrentPosition; this.OnUiThread(() => { CarPosition = UserCurrentPosition; PushpinVisibility = "Visible"; }); // Perform the reverse geocode query var query = new ReverseGeocodeQuery() { GeoCoordinate = UserCurrentPosition }; var geoCodeResults = await query.GetMapLocationsAsync(); var address = geoCodeResults.First().Information.Address; Car.Address = FormatAddress(address); IsolatedStorageSettings.ApplicationSettings["car"] = Car; IsolatedStorageSettings.ApplicationSettings.Save(); updateLiveTile(); Messenger.Default.Send <String>("CarPositionChanged"); }
public async void GetPhoneLocation() { try { _geolocator.DesiredAccuracyInMeters = 10; //_geolocator.DesiredAccuracy = PositionAccuracy.High; Geoposition geoposition = null; try { geoposition = await _geolocator.GetGeopositionAsync(maximumAge : TimeSpan.FromMinutes(5), timeout : TimeSpan.FromSeconds(10)); } catch (Exception ex) { throw ex; } ReverseGeocodeQuery myReverseGeocodeQuery = new ReverseGeocodeQuery(); myReverseGeocodeQuery.GeoCoordinate = new GeoCoordinate(geoposition.Coordinate.Latitude, geoposition.Coordinate.Longitude); IList <MapLocation> locations = await myReverseGeocodeQuery.GetMapLocationsAsync(); if (LocationRetrieved != null) { LocationRetrieved(this, locations.FirstOrDefault()); } } catch (Exception ex) { throw ex; } }
private async void GetLocation_Click_1(object sender, RoutedEventArgs e) { try { //Get the current position var geolocator = new Geolocator() { DesiredAccuracyInMeters = 10 }; var geoposition = await geolocator.GetGeopositionAsync( maximumAge: TimeSpan.FromMinutes(5), timeout: TimeSpan.FromSeconds(10)); //Perform the reverse geocode query var query = new ReverseGeocodeQuery() { GeoCoordinate = geoposition.Coordinate.ToGeoCoordinate() }; var geoCodeResults = await query.GetMapLocationsAsync(); var address = geoCodeResults.First().Information.Address; //Print all Coordinates.Text = FormatCoordinates(geoposition); Address.Text = FormatAddress(address); } catch (Exception ex) { if ((uint)ex.HResult == 0x80004004) { //Location services turned off, ask user to turn it on. AskUserToTurnOnLocationServices(); } else { MessageBox.Show("Unable to get location"); } } }
/// <summary> /// Event handler called when the user tap and hold in the map /// </summary> /// <param name="sender">Sender of the event</param> /// <param name="e">Event arguments</param> private async void OnMapHold(object sender, System.Windows.Input.GestureEventArgs e) { ReverseGeocodeQuery query; List <MapLocation> mapLocations; string pushpinContent; MapLocation mapLocation; query = new ReverseGeocodeQuery(); query.GeoCoordinate = this.Map.ConvertViewportPointToGeoCoordinate(e.GetPosition(this.Map)); mapLocations = (List <MapLocation>) await query.GetMapLocationsAsync(); mapLocation = mapLocations.FirstOrDefault(); if (mapLocation != null) { this.RouteDirectionsPushPin.GeoCoordinate = mapLocation.GeoCoordinate; pushpinContent = mapLocation.Information.Name; pushpinContent = string.IsNullOrEmpty(pushpinContent) ? mapLocation.Information.Description : null; pushpinContent = string.IsNullOrEmpty(pushpinContent) ? string.Format("{0} {1}", mapLocation.Information.Address.Street, mapLocation.Information.Address.City) : null; this.RouteDirectionsPushPin.Content = pushpinContent.Trim(); this.RouteDirectionsPushPin.Visibility = Visibility.Visible; } }
private async void centromapa() { geolocator.DesiredAccuracyInMeters = 50; try { SetProgressindicator(true); SystemTray.ProgressIndicator.Text = "Obteniendo datos del GPS"; Geoposition geoposition = await geolocator.GetGeopositionAsync (maximumAge : TimeSpan.FromMinutes(5), timeout : TimeSpan.FromSeconds(10)); SystemTray.ProgressIndicator.Text = "Localizacion obtenida"; mapacentral.Center.Latitude = geoposition.Coordinate.Latitude; mapacentral.Center.Longitude = geoposition.Coordinate.Longitude; centrox = geoposition.Coordinate.Latitude; centroy = geoposition.Coordinate.Longitude; ReverseGeocodeQuery query = new ReverseGeocodeQuery(); query.GeoCoordinate = new GeoCoordinate(geoposition.Coordinate.Latitude, geoposition.Coordinate.Longitude); query.QueryCompleted += (s, e) => { if (e.Error == null && e.Result.Count > 0) { listacercanos.Header = e.Result.ToString(); } }; query.QueryAsync(); track(); pinchosmapa(); } catch (UnauthorizedAccessException) { // the app does not have the right capability or the location master switch is off listacercanos.Header = "location is disabled in phone settings."; } }
public async void GetPhoneLocation() { try { _geolocator.DesiredAccuracyInMeters = 10; //_geolocator.DesiredAccuracy = PositionAccuracy.High; Geoposition geoposition = null; try { geoposition = await _geolocator.GetGeopositionAsync(maximumAge: TimeSpan.FromMinutes(5), timeout: TimeSpan.FromSeconds(10)); } catch (Exception ex) { throw ex; } ReverseGeocodeQuery myReverseGeocodeQuery = new ReverseGeocodeQuery(); myReverseGeocodeQuery.GeoCoordinate = new GeoCoordinate(geoposition.Coordinate.Latitude, geoposition.Coordinate.Longitude); IList<MapLocation> locations = await myReverseGeocodeQuery.GetMapLocationsAsync(); if (LocationRetrieved != null) { LocationRetrieved(this, locations.FirstOrDefault()); } } catch (Exception ex) { throw ex; } }
public static async Task GetAddress(double latitude, double longtitude) { var locationAddress = new LocationAddress(); try { var myReverseGeocodeQuery = new ReverseGeocodeQuery { GeoCoordinate = new GeoCoordinate(latitude, longtitude) }; IList<MapLocation> locations = await myReverseGeocodeQuery.GetMapLocationsAsync(); if (locations.Count > 0) { var address = locations.First().Information.Address; locationAddress = new LocationAddress { Street = address.Street, HouseNumber = address.HouseNumber, PostalCode = address.PostalCode, City = address.City, District = address.District, State = address.State, Country = address.Country }; } } catch (Exception ex) { BugSenseHandler.Instance.LogException(ex); } App.ViewModel.CurrentAddress = locationAddress; }
public Task <IEnumerable <string> > GetAddress(double lat, double lng) { var taskCompletion = new TaskCompletionSource <IEnumerable <string> >(); EventHandler <QueryCompletedEventArgs <IList <MapLocation> > > handler = null; var reverseGeocode = new ReverseGeocodeQuery(); reverseGeocode.GeoCoordinate = new GeoCoordinate(lat, lng); handler = (s, e) => { reverseGeocode.QueryCompleted -= handler; if (e.Cancelled) { taskCompletion.SetCanceled(); } else if (e.Error != null) { taskCompletion.SetException(e.Error); } else { var addresses = e.Result.Select(m => AddressToString(m.Information.Address)); taskCompletion.SetResult(addresses); } }; reverseGeocode.QueryCompleted += handler; reverseGeocode.QueryAsync(); return(taskCompletion.Task); }
private async void GetCurrentCoordinate() { LocationProgressBar.Visibility = System.Windows.Visibility.Visible; textBoxPostalCode.Text = ""; Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracy = PositionAccuracy.High; try { Geoposition currentPosition = await geolocator.GetGeopositionAsync(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10)); _accuracy = currentPosition.Coordinate.Accuracy; MyCoordinate = new GeoCoordinate(currentPosition.Coordinate.Latitude, currentPosition.Coordinate.Longitude); if (MyReverseGeocodeQuery == null || !MyReverseGeocodeQuery.IsBusy) { MyReverseGeocodeQuery = new ReverseGeocodeQuery(); MyReverseGeocodeQuery.GeoCoordinate = new GeoCoordinate(MyCoordinate.Latitude, MyCoordinate.Longitude); MyReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted; MyReverseGeocodeQuery.QueryAsync(); } } catch (Exception) { invalidMessage.Text = "Unable to find Valid Postal Code"; } }
private async void mapControl_Hold(object sender, System.Windows.Input.GestureEventArgs e) { status.Text = "querying for address..."; var point = e.GetPosition(mapControl); var coordinate = mapControl.ConvertViewportPointToGeoCoordinate(point); var pushpin = new Pushpin { GeoCoordinate = coordinate, Content = ++pinNumber, }; MapExtensions.GetChildren(mapControl).Add(pushpin); position.Text = string.Format("Latitude: {0}\nLongitude: {1}\n", FormatCoordinate(coordinate.Latitude, 'N', 'S'), FormatCoordinate(coordinate.Longitude, 'E', 'W')); ReverseGeocodeQuery query = new ReverseGeocodeQuery { GeoCoordinate = coordinate }; IList <MapLocation> results = await query.GetMapLocationsAsync(); position.Text += string.Format("{0} locations found.\n", results.Count); MapLocation location = results.FirstOrDefault(); if (location != null) { position.Text += FormatAddress(location.Information.Address); } status.Text += "complete"; }
public static async Task <string> GetAddressAsync(Geoposition position) { var reverseGeocodeQuery = new ReverseGeocodeQuery(); reverseGeocodeQuery.GeoCoordinate = position.Coordinate.ToGeoCoordinate(); var locations = await reverseGeocodeQuery.GetMapLocationsAsync(); if (locations != null && locations.Count > 0) { var location = locations.FirstOrDefault(); if (location.Information != null && location.Information.Address != null) { var address = location.Information.Address; string streetAddress = string.Format("{0} {1}", address.Street, address.HouseNumber).Trim(); string cityAddress = string.Format("{0} {1}", address.PostalCode, address.City).Trim(); string countryAddress = address.Country; return(string.Format("{0}, {1}, {2}", streetAddress, cityAddress, countryAddress) .Trim(new char[] { ' ', ',' })); } } return(null); }
protected bool Equals(ReverseGeocodeQuery other) { return(Latitude.Equals(other.Latitude) && Longitude.Equals(other.Longitude) && Limit == other.Limit && Radius == other.Radius && WideSearch.Equals(other.WideSearch)); }
//METODOS DE LOCALIZACION Y MAPA //busca la ubicacion, situa al usuario y al mapa, e inicia el seguimiento private async void iniciamapa() { geolocator.DesiredAccuracyInMeters = DesiredAccuracyInMeters; geolocator.DesiredAccuracy = PositionAccuracy.High; try { prog.IsVisible = true; prog.Text = "Obteniendo localización"; IAsyncOperation <Geoposition> locationTask = null; try { locationTask = geolocator.GetGeopositionAsync(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(15)); Geoposition position = await locationTask; Geocoordinate myGeocoordinate = position.Coordinate; GeoCoordinate myGeoCoordinate = ConvertGeocoordinate(myGeocoordinate); centro = myGeoCoordinate; prog.Text = "Localización obtenida"; this.mapacentral.Center = myGeoCoordinate; usuariocordx = position.Coordinate.Latitude; usuariocordy = position.Coordinate.Longitude; setPosition(position.Coordinate.Latitude, position.Coordinate.Longitude); ReverseGeocodeQuery query = new ReverseGeocodeQuery(); query.GeoCoordinate = new GeoCoordinate(position.Coordinate.Latitude, position.Coordinate.Longitude); query.QueryCompleted += ReverseGeocodeQuery_QueryCompleted; query.QueryAsync(); localespincho(position.Coordinate.Latitude, position.Coordinate.Longitude); Uri url = new Uri("http://produccion.rl2012alc.com/api/index.php/setPosition "); objetoslistas.getByCoord paquete = new objetoslistas.getByCoord(); paquete.latitude = position.Coordinate.Latitude; paquete.longitude = position.Coordinate.Longitude; string respuesta = await metodosJson.jsonPOST(url, paquete); if (listapinchos.Count > 0) { checklocal(); } } finally { if (locationTask != null) { if (locationTask.Status == AsyncStatus.Started) { locationTask.Cancel(); } locationTask.Close(); } } } catch (Exception) { // the app does not have the right capability or the location master switch is off MessageBoxResult result = MessageBox.Show("Location is disabled in phone settings", "ERROR", MessageBoxButton.OK); } }
private void Marker_Click(object sender, EventArgs e) { Polygon p = (Polygon)sender; GeoCoordinate geoCoordinate = (GeoCoordinate)p.Tag; MyReverseGeocodeQuery = new ReverseGeocodeQuery(); MyReverseGeocodeQuery.GeoCoordinate = new GeoCoordinate(geoCoordinate.Latitude, geoCoordinate.Longitude); MyReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted; MyReverseGeocodeQuery.QueryAsync(); }
private void map_Hold(object sender, System.Windows.Input.GestureEventArgs e) { g = map.ConvertViewportPointToGeoCoordinate(e.GetPosition(map)); ReverseGeocodeQuery MyGeocodeQuery = new ReverseGeocodeQuery(); MyGeocodeQuery.GeoCoordinate = g; MyGeocodeQuery.QueryCompleted += MyGeocodeQuery_QueryCompleted; MyGeocodeQuery.QueryAsync(); }
public void Similar_instances_should_be_considered_equal() { var q1 = new ReverseGeocodeQuery { Latitude = 51.2452924089757, Longitude = -0.58231794275613 }; var q2 = new ReverseGeocodeQuery { Latitude = 51.2452924089757, Longitude = -0.58231794275613 }; Assert.AreEqual(q1, q2); }
public void Similar_queries_but_with_different_radius_should_not_be_considered_equal() { var q1 = new ReverseGeocodeQuery { Latitude = 51.2452924089757, Longitude = -0.58231794275613 }; var q2 = new ReverseGeocodeQuery { Latitude = 51.2452924089757, Longitude = -0.58231794275613, Radius = 1 }; Assert.AreNotEqual(q1, q2); }
public void Different_instances_should_not_be_considered_equal() { var q1 = new ReverseGeocodeQuery { Latitude = 51.2452924089757, Longitude = -0.58231794275613 }; var q2 = new ReverseGeocodeQuery { Latitude = 51.2571984465953, Longitude = -0.567549033067429 }; Assert.AreNotEqual(q1, q2); }
public static async void GetCurrentDeviceGeoLocation() { Geocoordinate GeoCorResult = await GetCurrentGeoPosition(); CurrentCity = new City(); CurrentCity.Latitude = GeoCorResult.Latitude; CurrentCity.Longitude = GeoCorResult.Longitude; ReverseGeocodeQuery RGeoQ = new ReverseGeocodeQuery(); RGeoQ.GeoCoordinate = new GeoCoordinate(GeoCorResult.Latitude, GeoCorResult.Longitude); RGeoQ.QueryCompleted += reverseGeocode_QueryCompleted; RGeoQ.QueryAsync(); }
// Constructor public MainPage() { InitializeComponent(); AddResultToMap("GC", map1.Center); map1.CenterChanged += map1_CenterChanged; geoQ = new ReverseGeocodeQuery(); geoQ.QueryCompleted += geoQ_QueryCompleted; Debug.WriteLine("All construction done for GeoCoding"); }
async void connectionManager_MessageReceived(string message) { Debug.WriteLine("Message received:" + message); //string[] messageArray = message.Split(':'); //switch (messageArray[0]) switch (message) { case "f": // send emergency alert Dispatcher.BeginInvoke(delegate() { // find GPS location - continuous // find address - Reverse Geocoding ReverseGeocodeQuery query = new ReverseGeocodeQuery() { GeoCoordinate = new GeoCoordinate(Lat, Long) }; query.QueryCompleted += query_QueryCompleted; query.QueryAsync(); }); break; case "s": //reduce life life--; Dispatcher.BeginInvoke(delegate() { // make ui changes Life.Text = life.ToString(); if (life <= 0) Life.Text = "Lost"; }); break; default : //if (float.Parse(message) > 0.0 && float.Parse(message) < 99.0) //{ // Temp.Text = message; //} Dispatcher.BeginInvoke(delegate() { // make ui changes Temp.Text = message; }); break; } }
// Constructor public MainPage() { InitializeComponent(); System.Windows.Input.Touch.FrameReported += Touch_FrameReported; map1.ZoomLevelChanged += map1_ZoomLevelChanged; AddResultToMap(new GeoCoordinate(60.17040395, 24.94121572), new GeoCoordinate(60.29143956, 24.96187636)); geoRev = new ReverseGeocodeQuery(); geoRev.QueryCompleted += geoRev_QueryCompleted; }
void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args) { Dispatcher.BeginInvoke(() => { mapacentral.Center = new GeoCoordinate(args.Position.Coordinate.Latitude, args.Position.Coordinate.Longitude); centrox = args.Position.Coordinate.Latitude; centroy = args.Position.Coordinate.Longitude; pinchosmapa(); ReverseGeocodeQuery query = new ReverseGeocodeQuery(); query.GeoCoordinate = new GeoCoordinate(args.Position.Coordinate.Latitude, args.Position.Coordinate.Longitude); query.QueryCompleted += ReverseGeocodeQuery_QueryCompleted; query.QueryAsync(); }); }
private async void GetCurrentCoordinate() { Geolocator locator = new Geolocator(); locator.DesiredAccuracy = PositionAccuracy.High; Geoposition position = await locator.GetGeopositionAsync(); GeoCoordinate coordinate = new GeoCoordinate(position.Coordinate.Latitude, position.Coordinate.Longitude); ReverseGeocodeQuery query = new ReverseGeocodeQuery(); query.GeoCoordinate = coordinate; query.QueryAsync(); query.QueryCompleted += Query_QueryCompleted; }
static Task <IEnumerable <string> > GetAddressesForPositionAsync(Position position) { var source = new TaskCompletionSource <IEnumerable <string> >(); var query = new ReverseGeocodeQuery { GeoCoordinate = new GeoCoordinate(position.Latitude, position.Longitude) }; query.QueryCompleted += (sender, args) => source.SetResult(args.Result.Select(r => AddressToString(r.Information.Address)).ToArray()); query.QueryAsync(); return(source.Task); }
private void ShowLocationInfo() { var position = CurrentPosition; var query = new ReverseGeocodeQuery() { GeoCoordinate = new GeoCoordinate(position.Latitude, position.Longitude) }; query.QueryCompleted += OnQueryCompleted; _systemTrayService.Show("Retrieving current location info..."); query.QueryAsync(); }
public SearchPage() { InitializeComponent(); LoadSettings(); if (tracking) { InitializeGPS(); } MyReverseGeocodeQuery = new ReverseGeocodeQuery(); MyReverseGeocodeQuery.QueryCompleted += MyReverseGeocodeQuery_QueryCompleted; mapLayerVertical = new MapLayer(); VerticalMap.Layers.Add(mapLayerVertical); mapLayerHorizontal = new MapLayer(); HorizontalMap.Layers.Add(mapLayerHorizontal); LoadSearch(); }
private void Start_ReverseGeocodeQuery() { reverseGeocodeQuery = new ReverseGeocodeQuery() { GeoCoordinate = new GeoCoordinate(latitude, longitude) }; spinnerSP.SetValue(Grid.RowProperty, 2); spinnerSP.SetValue(Grid.RowSpanProperty, 1); myMap.Center = reverseGeocodeQuery.GeoCoordinate; myMap.Visibility = Visibility.Visible; reverseGeocodeQuery.QueryCompleted += reverseGeocodeQuery_QueryCompleted; reverseGeocodeQuery.QueryAsync(); }
private void GetNearbyArtists() { try { if (reverseGeocode == null || !reverseGeocode.IsBusy) { reverseGeocode = new ReverseGeocodeQuery(); reverseGeocode.GeoCoordinate = new GeoCoordinate(Map.Center.Latitude, Map.Center.Longitude); reverseGeocode.QueryCompleted += reverseGeocode_QueryCompleted; reverseGeocode.QueryAsync(); } } catch (Exception /*ex*/) { MessageBox.Show("Something went wrong"); } }
public PostItinerary() { InitializeComponent(); mapPostItinerary.IsEnabled = false; //this.Cursor = Cursors.Wait; //RevCode for current Location and show on Start TextBox geoQ = new ReverseGeocodeQuery(); geoQ.QueryCompleted += geoQ_QueryCompleted; if (geoQ.IsBusy == true) { geoQ.CancelAsync(); } // Set the geo coordinate for the query InitCurrentLocationInfo(); }
public static Task <Location> ReverseGeocode(double lat, double lon) { TaskCompletionSource <Location> completionSource = new TaskCompletionSource <Location>(); var geocodeQuery = new ReverseGeocodeQuery(); geocodeQuery.GeoCoordinate = new GeoCoordinate(lat, lon); EventHandler <QueryCompletedEventArgs <IList <MapLocation> > > query = null; query = (sender, args) => { geocodeQuery.QueryCompleted -= query; MapLocation mapLocation = args.Result.FirstOrDefault(); var location = Location.FromMapLocation(mapLocation); completionSource.SetResult(location); }; geocodeQuery.QueryCompleted += query; geocodeQuery.QueryAsync(); }
public MapPage() { this.InitializeComponent(); this.DataContext = App.DataContext; Touch.FrameReported += this.Touch_FrameReported; this.map1.ZoomLevelChanged += this.map1_ZoomLevelChanged; this.geoRev = new ReverseGeocodeQuery(); this.geoRev.QueryCompleted += this.geoRev_QueryCompleted; this.geoQ = new RouteQuery(); this.geoQ.QueryCompleted += this.geoQ_QueryCompleted; this.markerLayer = new MapLayer(); this.map1.Layers.Add(this.markerLayer); this.AddPlusMinusButtons(); }
/// <summary> /// Retrieve addresses for position. /// </summary> /// <param name="position">Desired position (latitude and longitude)</param> /// <returns>Addresses of the desired position</returns> public Task <IEnumerable <Address> > GetAddressesForPositionAsync(Position position) { if (position == null) { return(null); } var source = new TaskCompletionSource <IEnumerable <Address> >(); var query = new ReverseGeocodeQuery { GeoCoordinate = new GeoCoordinate(position.Latitude, position.Longitude) }; query.QueryCompleted += (sender, args) => source.SetResult(args.Result.ToAddresses()); query.QueryAsync(); return(source.Task); }
//metodo que se lanza cada vez que la posicion del gps cambia, almacena la posicion del usuario //y lanza una actualizacion del centro del mapa y de la direccion postal private void Watcher_PositionChanged(object sender, GeoPositionChangedEventArgs <GeoCoordinate> e) { usuariocordx = e.Position.Location.Latitude; usuariocordy = e.Position.Location.Longitude; centro = new GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude); mapacentral.SetView(centro, mapacentral.ZoomLevel); mapacentral.Layers.Clear(); localespincho(e.Position.Location.Latitude, e.Position.Location.Longitude); MapLayer mapLayer = new MapLayer(); DrawMapMarker(centro, Colors.Purple, mapLayer); mapacentral.Layers.Add(mapLayer); ReverseGeocodeQuery query = new ReverseGeocodeQuery(); query.GeoCoordinate = new GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude); query.QueryCompleted += ReverseGeocodeQuery_QueryCompleted; query.QueryAsync(); }
public Task <string> GetAddress(double latitude, double longitude) { string Address = ""; var tcs = new TaskCompletionSource <string>(); System.EventHandler <Microsoft.Phone.Maps.Services.QueryCompletedEventArgs <System.Collections.Generic.IList <Microsoft.Phone.Maps.Services.MapLocation> > > handler = null; var reverseGeocode = new ReverseGeocodeQuery(); handler = (sender, args) => { foreach (var address in args.Result.Select(adrInfo => adrInfo.Information.Address)) { ; if (address.Street != "" && address.HouseNumber != "") { Address += address.Street + " "; Address += address.HouseNumber + ",\n"; } else { if (address.Street != "" && address.HouseNumber == "") { Address += address.Street + " "; } } Address += address.City + ", "; Address += address.Country; } if (Address == "") { Address = latitude + ",\n" + longitude; } reverseGeocode.QueryCompleted -= handler; tcs.SetResult(Address); }; reverseGeocode.GeoCoordinate = new GeoCoordinate(latitude, longitude); reverseGeocode.QueryCompleted += handler; reverseGeocode.QueryAsync(); return(tcs.Task); }
private void mipos_Click(object sender, RoutedEventArgs e) { try { speechSynth.CancelAll(); ReverseGeocodeQuery query = new ReverseGeocodeQuery() { GeoCoordinate = new GeoCoordinate(lat, lon) }; query.QueryCompleted += query_QueryCompleted; query.QueryAsync(); } catch { error2(); } }
/// <summary> /// Get a city name from given coordinates. /// </summary> /// <param name="latitude"></param> /// <param name="longitude"></param> /// <returns></returns> public Task <string> GetCityFromLocation(double latitude, double longitude) { TaskCompletionSource <string> taskComplete = new TaskCompletionSource <string>(); ReverseGeocodeQuery query = new ReverseGeocodeQuery() { GeoCoordinate = new GeoCoordinate(latitude, longitude) }; query.QueryCompleted += (s, e) => { if (e.Error == null) { taskComplete.SetResult(e.Result.First().Information.Address.City); } }; query.QueryAsync(); return(taskComplete.Task); }
public static void AddToMap(Map myMap, GeoCoordinate coord, TextBox textBox, bool reverse) { Query<System.Collections.Generic.IList<MapLocation>> query = null; if (reverse) { query = new ReverseGeocodeQuery() { GeoCoordinate = coord, }; } else { query = new GeocodeQuery() { GeoCoordinate = new GeoCoordinate(0, 0), SearchTerm = textBox.Text }; } query.QueryCompleted += query_QueryCompleted; query.QueryAsync(); }
// When the page is loaded, make sure that you have obtained the users consent to use their location protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { string sLatitude = "0.0"; string sLongitude = "0.0"; string sName = ""; if (NavigationContext.QueryString.TryGetValue("Latitude", out sLatitude)) { } if (NavigationContext.QueryString.TryGetValue("Longitude", out sLongitude)) { } if (NavigationContext.QueryString.TryGetValue("Name", out sName)) { } if ((sName + sLongitude + sLatitude) != "") { RouteLocation = new GeoCoordinate(); RouteLocation.Latitude = double.Parse(sLatitude); RouteLocation.Longitude = double.Parse(sLongitude); RouteLocation.Altitude = 0.00; RouteAddress = new Address(); RouteAddress.Latitude = RouteLocation.Latitude; RouteAddress.Longitude = RouteLocation.Longitude; RouteAddress.Address1 = sName; Destination.GeoCoordinate = RouteLocation; reverseQuery = new ReverseGeocodeQuery(); reverseQuery.GeoCoordinate = RouteLocation; reverseQuery.QueryCompleted += reverseQuery_QueryCompleted; reverseQuery.QueryAsync(); currentPoint = 0; } }
void speakInfoAboutLocation(GeoCoordinate geocord) { ReverseGeocodeQuery query = new ReverseGeocodeQuery(); query.GeoCoordinate = geocord; query.QueryCompleted += query_QueryCompleted; query.QueryAsync(); }
private async void Locate_Click(object sender, EventArgs e) { positionLoaded = false; Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracyInMeters = 10; try { gPos = await geolocator.GetGeopositionAsync( maximumAge: TimeSpan.FromSeconds(5), timeout: TimeSpan.FromSeconds(10) ); dlat = gPos.Coordinate.Latitude; dlong = gPos.Coordinate.Longitude; LatitudeTextBlock.Text = "Latitude: " + gPos.Coordinate.Latitude.ToString("0.000000"); //geoposition.Coordinate.Latitude.ToString("0.00"); // LongitudeTextBlock.Text = "Longitude: " + gPos.Coordinate.Longitude.ToString("0.000000");//geoposition.Coordinate.Longitude.ToString("0.00"); // //Storing in static variables for access in other pages of app Booking.DestinationLat = gPos.Coordinate.Latitude.ToString("0.000000"); Booking.DestinationLong = gPos.Coordinate.Longitude.ToString("0.000000"); ReverseGeocodeQuery getAddress = new ReverseGeocodeQuery(); GeoCoordinate geo = new GeoCoordinate(); geo.Latitude = gPos.Coordinate.Latitude; geo.Longitude = gPos.Coordinate.Longitude; googlemap.Center = geo; googlemap.ZoomLevel = 16; string url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + geo.Latitude + "," + geo.Longitude + "&sensor=true"; var client = new WebClient(); string response = await client.DownloadStringTaskAsync(new Uri(url)); JObject root = JObject.Parse(response); JArray items = (JArray)root["results"]; JObject item; JToken jtoken; item = (JObject)items[0]; JArray add_comp = (JArray)item["address_components"]; string address = null; string[] add_types = { "street_number", "route", "neighborhood", "locality", "city", "country" }; foreach (var comp in add_comp) { if (add_types.Any(comp["types"].ToString().Contains)) { address += comp["long_name"].ToString() + ", "; if (comp["types"].ToString().Contains("city") | comp["types"].ToString().Contains("country")) { address += "\n"; } } } ///////////////////////////////////////////////////////////////////////////////////////// // Address From Google /////////////////////////////////////////////////////////////End Google Code (ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = true; (ApplicationBar.Buttons[1] as ApplicationBarIconButton).IsEnabled = true; (ApplicationBar.Buttons[2] as ApplicationBarIconButton).IsEnabled = true; (ApplicationBar.Buttons[3] as ApplicationBarIconButton).IsEnabled = true; zzoom.IsEnabled = true; positionLoaded = true; Microsoft.Phone.Controls.Maps.Pushpin new_pushpin = new Microsoft.Phone.Controls.Maps.Pushpin(); new_pushpin.Location = geo; googlemap.Children.Remove(pushPinLayer); pushPinLayer = new MapLayer(); new_pushpin.Content = address; Address.Text = address; new_pushpin.Visibility = Visibility.Visible; googlemap.Children.Add(pushPinLayer); pushPinLayer.AddChild(new_pushpin, geo, PositionOrigin.BottomLeft); MainPage.bookingData.set_current_location_attributes(address,geo); } catch (Exception ex) { if ((uint)ex.HResult == 0x80004004) { // the application does not have the right capability or the location master switch is off MessageBox.Show("location is disabled in phone settings"); } //else { // something else happened acquring the location } } }
/// <summary> /// Gets current geocoordinate for use with MixRadio API. /// </summary> private async void GetCurrentCoordinate() { Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracy = PositionAccuracy.Default; try { Geoposition currentPosition = await geolocator.GetGeopositionAsync( TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10)); Dispatcher.BeginInvoke(() => { GeoCoordinate coordinate = new GeoCoordinate( currentPosition.Coordinate.Latitude, currentPosition.Coordinate.Longitude); ReverseGeocodeQuery reverseGeocodeQuery = new ReverseGeocodeQuery(); reverseGeocodeQuery.GeoCoordinate = new GeoCoordinate( coordinate.Latitude, coordinate.Longitude); reverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted; reverseGeocodeQuery.QueryAsync(); }); } catch (Exception /*ex*/) { // Couldn't get current location. Location may be disabled. // Region info from the device is used as a fallback. MessageBox.Show("Current location cannot be obtained. It is " + "recommended that location service is turned " + "on in phone settings when using Music Explorer." + "\n\nUsing region info from phone settings instead."); InitializeMixRadioApi(null); } }
public static async Task AddLocation(Microsoft.Phone.Maps.Controls.Map myMap, Microsoft.Phone.Controls.PhoneTextBox myTextBox, System.Windows.Input.GestureEventArgs e, double latitude, double longitude, bool completeAddress = false, string pinContent = "") { ReverseGeocodeQuery query; List<MapLocation> mapLocations; string pushpinContent = ""; MapLocation mapLocation; query = new ReverseGeocodeQuery(); if (e != null) query.GeoCoordinate = myMap.ConvertViewportPointToGeoCoordinate(e.GetPosition(myMap)); else query.GeoCoordinate = new GeoCoordinate(latitude, longitude); mapLocations = (List<MapLocation>)await query.GetMapLocationsAsync(); mapLocation = mapLocations.FirstOrDefault(); if (mapLocation != null && !String.IsNullOrEmpty(mapLocation.Information.Address.Country)) { MapLayer pinLayout = new MapLayer(); Pushpin MyPushpin = new Pushpin(); MapOverlay pinOverlay = new MapOverlay(); if (myMap.Layers.Count > 0) { myMap.Layers.RemoveAt(myMap.Layers.Count - 1); } myMap.Layers.Add(pinLayout); MyPushpin.GeoCoordinate = mapLocation.GeoCoordinate; pinOverlay.Content = MyPushpin; pinOverlay.GeoCoordinate = mapLocation.GeoCoordinate; pinOverlay.PositionOrigin = new Point(0, 1); pinLayout.Add(pinOverlay); if (!completeAddress) pushpinContent = getAddress(mapLocation); else pushpinContent = getCompleteAddress(mapLocation); if (!string.IsNullOrEmpty(pinContent)) pushpinContent = pinContent; MyPushpin.Content = pushpinContent.Trim(); if (myTextBox != null) myTextBox.Text = MyPushpin.Content.ToString(); } }
public async Task<String> getCurrentLocation() { Debug.WriteLine("getCurrentLocation():- 1> Start"); Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracyInMeters = 50; try { Debug.WriteLine("getCurrentLocation():- 1> await for current latlong"); Geoposition geoposition = await geolocator.GetGeopositionAsync( maximumAge: TimeSpan.FromMinutes(0.5), timeout: TimeSpan.FromSeconds(5) ); Debug.WriteLine("getCurrentLocation():- 1> got the current latlong"); // txtBlockLocation.Text = "Latitude:" + geoposition.Coordinate.Latitude.ToString("0.00") + " Longitude:" + geoposition.Coordinate.Longitude.ToString("0.00"); LocationResult = new GeoCoordinate(geoposition.Coordinate.Latitude, geoposition.Coordinate.Longitude); if (MyReverseGeocodeQuery == null || !MyReverseGeocodeQuery.IsBusy) { MyReverseGeocodeQuery = new ReverseGeocodeQuery(); MyReverseGeocodeQuery.GeoCoordinate = new GeoCoordinate(LocationResult.Latitude, LocationResult.Longitude); MyReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted; Debug.WriteLine("getCurrentLocation():- 1> Start Reverse Geocoding"); MyReverseGeocodeQuery.QueryAsync(); Debug.WriteLine("getCurrentLocation():- 1> Completed Reverse Geocoding"); } } catch (Exception ex) { if ((uint)ex.HResult == 0x80004004) { // the application does not have the right capability or the location master switch is off txtBlockLocation.Text = txtBlockLocation.Text + "Status: " + "Location is disabled in phone settings"; } } return ""; }
private async void mapControl_Hold(object sender, System.Windows.Input.GestureEventArgs e) { status.Text = "querying for address..."; var point = e.GetPosition(mapControl); var coordinate = mapControl.ConvertViewportPointToGeoCoordinate(point); var pushpin = new Pushpin { GeoCoordinate = coordinate, Content = ++pinNumber, }; MapExtensions.GetChildren(mapControl).Add(pushpin); position.Text = string.Format("Latitude: {0}\nLongitude: {1}\n", FormatCoordinate(coordinate.Latitude, 'N', 'S'), FormatCoordinate(coordinate.Longitude, 'E', 'W')); ReverseGeocodeQuery query = new ReverseGeocodeQuery { GeoCoordinate = coordinate }; IList<MapLocation> results = await query.GetMapLocationsAsync(); position.Text += string.Format("{0} locations found.\n", results.Count); MapLocation location = results.FirstOrDefault(); if (location != null) { position.Text += FormatAddress(location.Information.Address); } status.Text += "complete"; }
/// <summary> /// Event handler for clicking a map marker. /// Initiates reverse geocode query. /// </summary> private void Marker_Click(object sender, EventArgs e) { Polygon p = (Polygon)sender; GeoCoordinate geoCoordinate = (GeoCoordinate)p.Tag; if (MyReverseGeocodeQuery == null || !MyReverseGeocodeQuery.IsBusy) { MyReverseGeocodeQuery = new ReverseGeocodeQuery(); MyReverseGeocodeQuery.GeoCoordinate = new GeoCoordinate(geoCoordinate.Latitude, geoCoordinate.Longitude); MyReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted; MyReverseGeocodeQuery.QueryAsync(); } }
/// <summary> /// Event handler called when the user tap and hold in the map /// </summary> /// <param name="sender">Sender of the event</param> /// <param name="e">Event arguments</param> private async void OnMapHold(object sender, System.Windows.Input.GestureEventArgs e) { ReverseGeocodeQuery query; List<MapLocation> mapLocations; string pushpinContent; MapLocation mapLocation; query = new ReverseGeocodeQuery(); query.GeoCoordinate = this.Map.ConvertViewportPointToGeoCoordinate(e.GetPosition(this.Map)); mapLocations = (List<MapLocation>)await query.GetMapLocationsAsync(); mapLocation = mapLocations.FirstOrDefault(); if (mapLocation != null) { this.RouteDirectionsPushPin.GeoCoordinate = mapLocation.GeoCoordinate; pushpinContent = mapLocation.Information.Name; pushpinContent = string.IsNullOrEmpty(pushpinContent) ? mapLocation.Information.Description : null; pushpinContent = string.IsNullOrEmpty(pushpinContent) ? string.Format("{0} {1}", mapLocation.Information.Address.Street, mapLocation.Information.Address.City) : null; this.RouteDirectionsPushPin.Content = pushpinContent.Trim(); this.RouteDirectionsPushPin.Visibility = Visibility.Visible; } }
private void btnSelect_Click(object sender, EventArgs e) { if (selectedAddress == "") { ShowProgressIndicator("Getting address..."); ReverseGeocodeQuery query = new ReverseGeocodeQuery() { GeoCoordinate = selectedGeocoordinate }; query.QueryCompleted += query_QueryCompleted; query.QueryAsync(); } else { PhoneApplicationService.Current.State["location"] = selectedGeocoordinate; PhoneApplicationService.Current.State["address"] = selectedAddress; NavigationService.GoBack(); } }
private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e) { ReverseGeocodeQuery query = new ReverseGeocodeQuery(); query.GeoCoordinate = new GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude); query.QueryCompleted += (s, ee) => { txtAddress.Visibility = System.Windows.Visibility.Visible; LayoutRoot.Opacity = 1; pgrAddress.Visibility = System.Windows.Visibility.Collapsed; if (ee.Error == null && ee.Result.Count > 0) { txtAddress.Text = AppResources.PhotoPage_Address + " " + ee.Result.First().Information.Address.District + " - " + ee.Result.First().Information.Address.City; } else { txtAddress.Text = AppResources.PhotoPage_Address_Error; } }; query.QueryAsync(); watcher.Dispose(); }
//Events private void GetLocationAddress(double latitude, double longitude) //Returns the users current location as a civic address { if (MyReverseGeocodeQueryOrigin == null || !MyReverseGeocodeQueryOrigin.IsBusy) { //progressBar.Visibility = Visibility.Visible; MyReverseGeocodeQueryOrigin = new ReverseGeocodeQuery(); MyReverseGeocodeQueryOrigin.GeoCoordinate = new GeoCoordinate(latitude, longitude); MyReverseGeocodeQueryOrigin.QueryCompleted += CurrentLocationReverseGeocodeQuery_QC; MyReverseGeocodeQueryOrigin.QueryAsync(); } }
private void ReverseGeocodeMyLocation() { if (MyCoordinate != null) { if (MyReverseGeocodeQuery == null || !MyReverseGeocodeQuery.IsBusy) { MyReverseGeocodeQuery = new ReverseGeocodeQuery(); MyReverseGeocodeQuery.GeoCoordinate = new GeoCoordinate(MyCoordinate.Latitude, MyCoordinate.Latitude); MyReverseGeocodeQuery.QueryCompleted += MyReverseGeoCodeQueryCompleted; MyReverseGeocodeQuery.QueryAsync(); } } }
private async void FSLocationButton_Click(object sender, System.Windows.Input.GestureEventArgs e) { //Check for the user agreement in use his position. If not, method returns. if ((bool)IsolatedStorageSettings.ApplicationSettings["LocationConsent"] != true) { // The user has opted out of Location. return; } //Declare and Inizialize a Geolocator object Geolocator geolocator = new Geolocator(); //Set his accuracy in Meters geolocator.DesiredAccuracyInMeters = 50; //Let's get the position of the user. Since there is the possibility of getting an Exception, this method is called inside a try block try { textBlock1.Text = "searching..."; //The await guarantee the calls to be returned on the thread from which they were called //Since it is call directly from the UI thread, the code is able to access and modify the UI directly when the call returns. Geoposition geoposition = await geolocator.GetGeopositionAsync( maximumAge: TimeSpan.FromMinutes(5), timeout: TimeSpan.FromSeconds(10) ); //With this 2 lines of code, the app is able to write on a Text Label the Latitude and the Longitude, given by Geoposition MyCoordinate.Latitude = geoposition.Coordinate.Latitude; MyCoordinate.Longitude = geoposition.Coordinate.Longitude; ShowMyLocationOnTheMap(); if (MyReverseGeocodeQuery == null || !MyReverseGeocodeQuery.IsBusy) { MyReverseGeocodeQuery = new ReverseGeocodeQuery(); MyReverseGeocodeQuery.GeoCoordinate = new GeoCoordinate(MyCoordinate.Latitude, MyCoordinate.Longitude); MyReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted; MyReverseGeocodeQuery.QueryAsync(); } //StatusTextBlock.Text = "Status = This is your position :)"; } //If an error is catch 2 are the main causes: the first is that you forgot to includ ID_CAP_LOCATION in your app manifest. //The second is that the user doesn't turned on the Location Services catch (Exception ex) { if ((uint)ex.HResult == 0x80004004) { //StatusTextBlock.Text = "Status= Location is disabled in phone settings."; } //else { // something else happened during the acquisition of the location } } }
private void XAMLMap_Tap(object sender, System.Windows.Input.GestureEventArgs e) { /* if (!isMapFocused) { XAMLMap.Height = 525; XAMLMap.Margin = new Thickness(0, -130, 0, 0); isMapFocused = true; } */ XAMLMap.Focus(); MyCoordinates[1] = XAMLMap.ConvertViewportPointToGeoCoordinate(e.GetPosition(XAMLMap)); DrawMapMarkers(); distanceLeft = MyCoordinates[0].GetDistanceTo(MyCoordinates[1]) * 0.000621371; // distance calculator in meters, converted to miles DistanceLeftDistanceTextBlock.Text = distanceLeft.ToString("0.00"); ReverseGeocodeQuery query = new ReverseGeocodeQuery() { GeoCoordinate = MyCoordinates[1] }; query.QueryCompleted += query_QueryCompleted; query.QueryAsync(); }