current I use this code to get GPS:
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.Default;
geolocator.DesiredAccuracyInMeters = 50;
try
{
Geoposition currentPosition = await geolocator.GetGeopositionAsync(TimeSpan.FromSeconds(120), TimeSpan.FromSeconds(30));
MyCoordinate = new GeoCoordinate(currentPosition.Coordinate.Latitude, currentPosition.Coordinate.Longitude);
}
catch (Exception ex)
{
if (ex.Message.Contains("This operation returned because the timeout period expired."))
{
MessageBox.Show("GPS is taking too long too complete. Pleaes try again.");
this.SetProgressIndicator(false);
RadBusyIndicator.IsRunning = false;
return;
}
else
{
this.SetProgressIndicator(false);
RadBusyIndicator.IsRunning = false;
return;
}
};
But it always takes too long to complete, as you can see I set timeout 30s but not sure why
it doesn't show timeout exception when took more than 30s.
I'm getting stuck on this issue. Does anyone have any idea?
Make sure the wifi or cellphone device is on, this enables the fallback methods to be used when the GPS device can't find a signal.
Someone with more or less the same problem made another thread in here:
GetGeopositionAsync does not return
More information on the GeoLocator class:
http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.geolocation.geolocator#properties
I don't know why too, but TimeSpanis realy slow, but doing it with ReportInterval works fine:
geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.ReportInterval = 2000;
geolocator.PositionChanged += geolocator_PositionChanged;
private void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
try
{
Dispatcher.BeginInvoke(() =>
{
myPosition = args.Position.Coordinate.ToGeoCoordinate();
});
}
catch(Exception ex)
{
if (ex.Data == null) throw;
else MessageBox.Show("Exception while Tracking: " + ex.InnerException.ToString());
}
}
Related
I'm developing an app based in GPS services and i must track the location of the user continuously, like HERE Maps, and I'm using the code bellow:
geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.MovementThreshold = 20; //Doesn't matter the value I put here, it won't work
geolocator.PositionChanged += geolocator_PositionChanged;
void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
Dispatcher.BeginInvoke(() =>
{
if(args.Position != null)
{
myPosition = args.Position.Coordinate.ToGeoCoordinate();
UpDateData();
}
});
}
The problem is: I got a System.Reflection.TargetInvocationException
Do you have any solutuon for that kind of problem ?
try
{
geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.ReportInterval = 2000;
geolocator.PositionChanged += geolocator_PositionChanged;
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Location is Disabled in Phone Settings.");
}
private void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
try
{
Dispatcher.BeginInvoke(() =>
{
if (args.Position != null && args.Position.Coordinate.ToGeoCoordinate() != myPosition)
{
if(args.Position.Coordinate.Accuracy <= 1500)
{
myPosition = args.Position.Coordinate.ToGeoCoordinate();
UpDateMyPositionCircle(args.Position.Coordinate.Accuracy);
}
}
});
}
catch (TargetInvocationException tie)
{
if (tie.Data == null) throw;
else MessageBox.Show("TargetInvocationException while Tracking: " + tie.InnerException.ToString());
}
catch(SystemException se)
{
if (se.Data == null) throw;
else MessageBox.Show("SystemException while Tracking: " + se.InnerException.ToString());
}
catch(Exception ex)
{
if (ex.Data == null) throw;
else MessageBox.Show("Exception while Tracking: " + ex.InnerException.ToString());
}
}
Most likely this error is causes by the location not being marked as on in your application manifest file
As #Stuart mentioned make sure that you've ticked the ID_CAP_LOCATION from your AppManifest file. If you don’t do this your app will throw an exception and when you try deploy it during development and will cause your app to fail.
How to continuously track the phone's location for Windows Phone 8
I'm developing an app based in GPS services and i must track the location of the user continuously, like HERE Maps.
geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.MovementThreshold = 20; //Doesn't matter the value I put here, it won't work
geolocator.PositionChanged += geolocator_PositionChanged;
void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
Dispatcher.BeginInvoke(() =>
{
if(args.Position != null)
{
myPosition = args.Position.Coordinate.ToGeoCoordinate();
UpDateData();
}
});
}
(I've tried with GeoCoordinateWatcher but i got nothing).
These functions work perfectly when i'm standing at the same place or moving very slowly, but if i enter in a car and start to drive the app crashes after few seconds, and I don't know WHY.
I've searched a lot of codes with the same finality and all of them don't work.
Do you know any other solution for that problem or have already found yourselves in the same position as mine ?
try
{
geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.ReportInterval = 2000;
geolocator.PositionChanged += geolocator_PositionChanged;
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Location is Disabled in Phone Settings.");
}
private void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
try
{
Dispatcher.BeginInvoke(() =>
{
if (args.Position != null && args.Position.Coordinate.ToGeoCoordinate() != myPosition)
{
if(args.Position.Coordinate.Accuracy <= 1500)
{
myPosition = args.Position.Coordinate.ToGeoCoordinate();
UpDateMyPositionCircle(args.Position.Coordinate.Accuracy);
}
}
});
}
catch (TargetInvocationException tie)
{
if (tie.Data == null) throw;
else MessageBox.Show("TargetInvocationException while Tracking: " + tie.InnerException.ToString());
}
catch(SystemException se)
{
if (se.Data == null) throw;
else MessageBox.Show("SystemException while Tracking: " + se.InnerException.ToString());
}
catch(Exception ex)
{
if (ex.Data == null) throw;
else MessageBox.Show("Exception while Tracking: " + ex.InnerException.ToString());
}
}
I try activate a progressbar, while the app is searching for the location (after pressing a button)
how can i solve it the best way?
the best would somehow to get an if else in there, wheater i got (the rigth) data from the geolocator and check that.
private async void Ellipse_Tap (object sender, System.Windows.Input.GestureEventArgs e)
{
Geolocator geolocator = new Geolocator();
//Set his accuracy in Meters
geolocator.DesiredAccuracyInMeters = 50;
try
{
//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)
);
//Relativer Nullpunkt
delta_y = geoposition.Coordinate.Latitude - y;
delta_x = geoposition.Coordinate.Longitude - x;
Path.Visibility = Visibility.Visible;
}
//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)
{
MessageBox.Show("Location is disabled in phone settings.");
return;
//Application.Current.Terminate();
}
//else
{
// something else happened during the acquisition of the location
}
}
}
Assuming you are using the ProgressIndicator in the SystemTry, Add the following to the OnNavigatedTo Method
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
SystemTray.ProgressIndicator = new ProgressIndicator();
}
Then create this method to set the ProgressIndicator.
private void DisplayProgressIndicator(bool isvisible, string message = "")
{
SystemTray.ProgressIndicator.Text = message;
SystemTray.ProgressIndicator.IsIndeterminate = isvisible;
SystemTray.ProgressIndicator.IsVisible = isvisible;
}
Then use the method created in the Eclips_Tap method.
private async void Ellipse_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracyInMeters = 50;
try
{
DisplayProgressIndicator(true, "Finding current location..."); // < SET THE PROGRESS INDICATOR
Geoposition geoposition = await geolocator.GetGeopositionAsync(
maximumAge: TimeSpan.FromMinutes(5),
timeout: TimeSpan.FromSeconds(10)
);
delta_y = geoposition.Coordinate.Latitude - y;
delta_x = geoposition.Coordinate.Longitude - x;
Path.Visibility = Visibility.Visible;
DisplayProgressIndicator(false); // << UNSET PROGRESS INDICATOR
}
catch (Exception ex)
{
if ((uint)ex.HResult == 0x80004004)
{
MessageBox.Show("Location is disabled in phone settings.");
return;
}
}
}
Hope this helps..
I developing windows phone 8 application
I need to get the user current location city and state name on page load (Application start)
I tryed with following code
public SplashPage()
{
InitializeComponent();
GetCurrentCoordinate();
}
private async void GetCurrentCoordinate()
{
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 += MyReverseGeocodeQuery_QueryCompleted;
MyReverseGeocodeQuery.QueryAsync();
}
}
catch (Exception ex)
{
}
}
private void MyReverseGeocodeQuery_QueryCompleted(object sender, QueryCompletedEventArgs<IList<Microsoft.Phone.Maps.Services.MapLocation>> e)
{
if (e.Error == null)
{
if (e.Result.Count > 0)
{
MapAddress address = e.Result[0].Information.Address;
CurrentLocTextBlock.Text = "Current Location: " + address.City + ", " + address.State;
}
}
}
if i run the above code it's come to try block and not move to next line
MyCoordinate = new GeoCoordinate(currentPosition.Coordinate.Latitude, currentPosition.Coordinate.Longitude);"
some times code move to next line and result come. but most of time it's not go to next line.
how to overcome this. why this problem occur?
you need to add a timeout procedure by your self.
Geolocator geolocator = new Geolocator();
// get the async task
var asyncResult = geolocator.GetGeopositionAsync();
var task = asyncResult.AsTask();
// add a race condition - task vs timeout task
var readyTask = await Task.WhenAny(task, Task.Delay(10000));
if (readyTask != task) // timeout wins
throw new TimeoutException();
// position found within timeout
var pos = await task;
return pos;
Refered from GEOLOCATOR.GETGEOPOSITIONASYNC WITH CORRECT TIMEOUT
You missed a word "GeoCoordinate" at the beginning of current line
GeoCoordinate MyCoordinate = new GeoCoordinate
After you get your current position (GeoCoordinate), do this:
private void findAddress(GeoCoordinate myCoordinate)
{
if (reverseGeocode != null) reverseGeocode = null;
reverseGeocode = new ReverseGeocodeQuery();
reverseGeocode.GeoCoordinate = myCoordinate;
reverseGeocode.QueryCompleted += reverseGeocode_QueryCompleted;
reverseGeocode.QueryAsync();
}
void reverseGeocode_QueryCompleted(object sender, QueryCompletedEventArgs<IList<MapLocation>> e)
{
if (e.Error == null && e.Result.Count > 0)
{
//Here you got all information about your current coordinate/position
MapAddress myPositionAddress = null;
myPositionAddress = e.Result.FirstOrDefault().Information.Address;
}
}
For the purposes of this question I'm including a class of mine in its entirety:
public class SerialPortConnection
{
private SerialPort serialPort;
private string ping;
double failOut;
bool isReceiving;
public SerialPortConnection(string comPort = "Com1", int baud = 9600, System.IO.Ports.Parity parity = System.IO.Ports.Parity.None, int dataBits = 8, System.IO.Ports.StopBits stopBits = System.IO.Ports.StopBits.One, string ping = "*IDN?", double failOut = 2)
{
this.ping = ping;
this.failOut = failOut * 1000;
try
{
serialPort = new SerialPort(comPort, baud, parity, dataBits, stopBits);
}
catch (Exception e)
{
throw e;
}
}
//Open Serial Connection. Returns False If Unable To Open.
public bool OpenSerialConnection()
{
//Opens Initial Connection:
try
{
serialPort.Open();
serialPort.Write("REMOTE\r");
}
catch (Exception e)
{
throw e;
}
serialPort.Write(ping + "\r");
var testReceived = "";
isReceiving = true;
Timer StopWatch = new Timer(failOut);
StopWatch.Elapsed += new ElapsedEventHandler(OnTimedEvent);
StopWatch.Interval = failOut;
StopWatch.Enabled = true;
while (isReceiving == true)
{
try
{
testReceived += serialPort.ReadExisting();
}
catch (Exception e)
{
throw e;
}
}
StopWatch.Dispose();
if (testReceived.Contains('>'))
{
return true;
}
else
{
return false;
}
}
public string WriteSerialConnection(string SerialCommand)
{
try
{
serialPort.Write(String.Format(SerialCommand + "\r"));
var received = "";
bool isReceiving = true;
Timer StopWatch = new Timer(failOut);
StopWatch.Elapsed += new ElapsedEventHandler(OnTimedEvent);
StopWatch.Interval = failOut;
StopWatch.Enabled = true;
while (isReceiving == true)
{
try
{
received += serialPort.ReadExisting();
}
catch (Exception e)
{
throw e;
}
}
if (received.Contains('>'))
{
return received;
}
else
{
received = "Error: No Data Received From Device";
return received;
}
StopWatch.Dispose();
}
catch (Exception e)
{
throw e;
}
}
//Closes Serial Connection. Returns False If Unable To Close.
public bool CloseSerialConnection()
{
try
{
serialPort.Write("LOCAL\r");
serialPort.Close();
return true;
}
catch (Exception e)
{
throw e;
}
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
isReceiving = false;
}
}
What I'm attempting to do here is keep a loop running for a set amount of time (two seconds in this case) because the device connected to the serial port I'm working with is unpredictable. I don't know what data I will receive from it and I don't know how long it will take. That can't be fixed and is something I have to work with. My best option, currently, is to wait a set amount of time and check the data I've received for an end token (">"). I've tried wiring up a timer even in the class like so:
Timer StopWatch = new Timer(failOut * 1000);
StopWatch.Elapsed += new ElapsedEventHandler(OnTimedEvent);
StopWatch.Interval = failOut;
StopWatch.Enabled = true;
But it doesn't appear to work. The event itself looks like so:
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
isReceiving = false;
}
My objective is to cut the loop isReceiving is tied to:
(while isReceiving == true)
{
//Do Something
}
But it doesn't appear to work. I assume I've completely misunderstood the function of the timer but I've had suggestions before to implement it. What am I doing wrong? If I'm just completely misusing it, what can I use instead of a timer? As I've said, I've no choice but to wait a set amount of time and check what I've received. That can't be avoided or handled in any way other than waiting and hoping I get something.
EDIT:
Maybe it's best I clarify this. The OnTimedEvent event is firing and the variable is set to false but it doesn't cut the loop as isReceiving isn't getting set to false.
EDIT 2:
Mr. Passant's answer works beautifully barring a strange error I'm encountering. As I don't believe it's a problem within his answer, it's more likely that it's a hardware flaw, or something else strange and obscure along those lines, I'm leaving his answer marked as accepted. I recommend anyone that chooses to implement his answer also view the question I have submitted here:
Apparent IO.Ports.SerialPort Flaw in C# or Possible Hardware Flaw
You are making it too difficult on yourself. Simply change the SerialPort.NewLine property to ">". And use SerialPort.ReadLine() to read the response. You can still use a timeout if you need it, assign the SerialPort.ReadTimeout property and be prepared to catch the TimeoutException.