简体   繁体   中英

Calculating distance from GPS coordinates

I have an app with a start and a stop button. When the user hits start, it turns on GPS. When the user hits stop, it turns off GPS. I want to calculate the distance the user traveled from start to stop.

This is the code I have so far but it's not working.

I'm printing GPS coordinates for Point 1 and Point 2 rounded to 4 decimal places. It's entering the if-statement in Update() even though it's printing the same GPS coordinates for Point 1 and Point 2.

Another issue is that it says I've traveled ~1200 km as soon as I hit the start button even though I haven't moved.

public double long1 = 0;
public double lat1 = 0;

public double long2 = 0;
public double lat2 = 0;

void Start ()
{
    distance_label = distanceObject.GetComponent<Text> ();

    // *** DELETE WHEN DONE - text labels for testing
    testP1 = p1Object.GetComponent<Text> ();
    testP2 = p2Object.GetComponent<Text> ();
    testMsg = test.GetComponent<Text> ();

    distance_label.text = "You and your blobs have walked " + distanceWalked + " km.";
}


void Update ()
{

    GetCurrentLocation ();

    double latRounded1 = Math.Round (lat1, 4);
    double longRounded1 = Math.Round (long1, 4);
    double latRounded2 = Math.Round (lat2, 4);
    double longRounded2 = Math.Round (long2, 4);

    testP1.text = "<Point 1 Coordinates> Lat: " + latRounded1 + ", Long: " + longRounded1;
    testP2.text = "<Point 2 Coordinates> Lat: " + latRounded2 + ", Long: " + longRounded2;

    // Compare GPS coordinates rounded to 4 decimal places
    if (latRounded1 != latRounded2 || longRounded1 != longRounded2) {
        testMsg.text = "Lat/Long don't match.";
        distanceWalked += CalculateDistance (longRounded1, latRounded1, longRounded2, latRounded2);
        distance_label.text = "You and your blobs have walked " + distanceWalked + " km.";
        long1 = long2;
        lat1 = lat2;
    }
}

/// <summary>
/// Makes a call to start GPS service when Start button is clicked.
/// </summary>
public void StartButtonClicked ()
{
    Debug.Log ("Start button clicked...");
    StartCoroutine (StartLocationService ());
}

/// <summary>
/// Stops GPS service when Stop button is clicked.
/// </summary>

public void StopButtonClicked ()
{
    Debug.Log ("Stop button clicked...");
    Input.location.Stop ();
    distance_label.text = "Stopped.";
}

public void ResetButtonClicked()
{
    Debug.Log("Reset button clicked...");
    distanceWalked = 0;
    Input.location.Stop ();

    Debug.Log ("distanceWalked after reset: " + distanceWalked);
}

public void GetCurrentLocation()
{
    if (Input.location.status == LocationServiceStatus.Running) {
        long2 = Input.location.lastData.longitude;
        lat2 = Input.location.lastData.latitude;
    }
}

/// <summary>
/// Starts the location service.
/// </summary>

IEnumerator StartLocationService ()
{
    // First, check if user has location service enabled
    if (!Input.location.isEnabledByUser)
        //yield break;
        distance_label.text = "Not initialized";

    // Start service before querying location
    Input.location.Start (0.5f);    // accuracy = 0.5m


    // Wait until service initializes
    int maxWait = 20;
    while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0) {
        yield return new WaitForSeconds (1);
        maxWait--;
    }

    // Service didn't initialize in 20 seconds
    if (maxWait < 1) {
        distance_label.text = "Timed out";
        yield break;
    }

    // Connection has failed
    if (Input.location.status == LocationServiceStatus.Failed) {
        distance_label.text = "Unable to determine device location";
        yield break;
    } else {
        long1 = long2 = Input.location.lastData.longitude;
        lat1 = lat2 = Input.location.lastData.latitude;

        // Access granted and location value could be retrieved
        // distance_label.text = "Location: " + Input.location.lastData.latitude + " " +
        // Input.location.lastData.longitude + " " +
        // Input.location.lastData.altitude;

    }

    // Stop service if there is no need to query location updates continuously
    //Input.location.Stop ();
}

/// <summary>
/// Calculate distance traveled given two points.
/// </summary>
/// <param name="longitude1"> Longitude coordinate of point 1</param>
/// <param name="latitude1"> Latitude coordinate of point 1</param>
/// <param name="longitude2"> Longitude coordinate of point 2</param>
/// <param name="latitude2"> Latitude coordinate of point 2</param>
public double CalculateDistance (double longitude1, double latitude1, double longitude2, double latitude2)
{
    double radiansOverDegrees = (Math.PI / 180.0);
    double EARTH_MEAN_RADIUS = 6371;    // in km

    double radiansLong1 = longitude1 * radiansOverDegrees;
    double radiansLat1 = latitude1 * radiansOverDegrees;

    double radiansLong2 = longitude2 * radiansOverDegrees;
    double radiansLat2 = latitude2 * radiansOverDegrees;

    double dLong = radiansLong2 - radiansLong1;
    double dLat = radiansLat2 - radiansLat1;

    double dist1 = Math.Pow (Math.Sin (dLat / 2.0), 2.0) +
        Math.Cos (radiansLat1) * Math.Cos (radiansLat2) *
        Math.Pow (Math.Sin (dLong / 2.0), 2.0);

    double dist2 = EARTH_MEAN_RADIUS * 2.0 * Math.Atan2 (Math.Sqrt (dist1), Math.Sqrt (1.0 - dist1));

    return dist2;
}

Use SphericalUtil which in com.google.maps.android package.

public static double getDistance(LatLng origin, LatLng destination) {
            return SphericalUtil.computeDistanceBetween(origin, destination);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM