Xamarin Android - Get GPS date

1

I have a question to ask. I have an app that works as a work attendance clock, and when making the entry or exit, I get the GPS data, these are:

  • Latitude
  • Length
  • Date and time.

The detail I have is that if you change the time of the device I get that time and not the actual time. The question is, how would you get the correct GPS date?

So far I have this:

public void OnLocationChanged(GPS.Location location)
    {

        if (location != null)
        {
            longitudval = location.Longitude;
            latitudval = location.Latitude;
            date= Helpers.HelpMethods.GetLocalDateTime(location.Time);
            i++;
            if (i == 2)
            {
                decimal longitude = decimal.Parse(longitudval.ToString());
                decimal latitude = decimal.Parse(latitudval.ToString());
                catStores = db.GetStores(longitude, latitude);
            }
        }
    }

My method to obtain the date is this:

public static DateTime GetLocalDateTime(long fromGPSMiliseconds)
    {
        DateTime dateTime = new DateTime();
        var startdate = DateTimeOffset.FromUnixTimeMilliseconds(fromGPSMiliseconds);
        dateTime = Convert.ToDateTime(startdate.ToLocalTime().ToString());
        return dateTime;
    }

Thank you very much for your support.

    
asked by Marco Luna 13.04.2018 в 00:49
source

1 answer

1

Use the Time Zone API (from Google Maps) to get the current time of a geographical coordinate (known its latitude and longitude). When consulting the service, you will get a JSON, which interests you 2 properties: dstOffset and rawOffset . You can both use them to calculate the time of that location with a mathematical formula.

As a reference, use this link , but if you want some code, it would be something like this:

 var latitud = 49.22645;
 var longitud = 17.67065;
 var timestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

 var timeRequestUrl = $"https://maps.googleapis.com/maps/api/timezone/json?location={latitud},{longitud}&timestamp={timestamp}&key={apiKey}";
 var timeJsonResponse = await HttpClient.GetStringAsync(timeRequestUrl);
 var timeObject = JsonConvert.DeserializeObject<TimeRootObject>(timeJsonResponse);

 var newTimestamp = timestamp + timeObject.dstOffset + timeObject.rawOffset;
 var localDate = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(newTimestamp);

NOTE 1: apiKey is the key to the service you get when you sign up and of course, localDate is the time at the location of the coordinates.

NOTE 2: TimeRootObject is the class that models the JSON obtained

public class TimeRootObject
{
    public int dstOffset { get; set; }
    public int rawOffset { get; set; }
    public string status { get; set; }
    public string timeZoneId { get; set; }
    public string timeZoneName { get; set; }
}

Review it and tell me.

    
answered by 15.04.2018 в 02:44