Distance calculation : Math « Game « Android

Home
Android
1.2D Graphics
2.Animation
3.Core Class
4.Database
5.Date Type
6.Development
7.File
8.Game
9.Hardware
10.Media
11.Network
12.Security
13.UI
14.User Event
Android » Game » Math 
Distance calculation
    

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;

class DistanceUtil {

  private LocationManager _lm;
  private String _provider;

  public DistanceUtil(Context context) {
    _lm = (LocationManagercontext
        .getSystemService(Context.LOCATION_SERVICE);
    Criteria crit = new Criteria();
    crit.setAccuracy(Criteria.ACCURACY_COARSE);
    if (_lm != null)
      _provider = _lm.getBestProvider(crit, true);
  }

  public static double calculateDistance(double startLat, double startLong,
      double endLat, double endLong) {

    try {
      double theta = startLong - endLong;
      double dist = Math.sin(deg2rad(startLat))
          * Math.sin(deg2rad(endLat)) + Math.cos(deg2rad(startLat))
          * Math.cos(deg2rad(endLat)) * Math.cos(deg2rad(theta));
      dist = Math.acos(dist);
      dist = rad2deg(dist);
      dist = dist * 60 1.1515// in miles
      dist = dist * 1.609344// in kilometers

      return dist;

    catch (Exception e) {
      e.printStackTrace();
    }
    return 0;
  }

  public double calculateDistanceFromActual(double endLat, double endLong) {
    if (_lm != null && _provider != null) {
      Location loc = _lm.getLastKnownLocation(_provider);
      if (loc != null)
        return calculateDistance(loc.getLatitude(), loc.getLongitude(),
            endLat, endLong);
    }

    return 0;
  }
  private static double deg2rad(double deg) {
    return (deg * Math.PI / 180.0);
  }

  private static double rad2deg(double rad) {
    return (rad * 180.0 / Math.PI);
  }

}

   
    
    
    
  
Related examples in the same category
1.Tests if the line segment from (X1, Y1) to (X2, Y2) intersects the line segment from (X3, Y3) to (X4, Y4).
2.Get Angle for two lines
3.Degree To Radian
4.Calculate sin^2(x),cos^2(x),tan^2(x)
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.