2016-03-01 57 views
0

我想从handleNewLocation方法存储在变量中的用户位置,并计算变量x的距离。我一直在寻找全局变量,但似乎没有任何工作。需要帮助计算用户和位置之间的距离android

/* 
* Define a request code to send to Google Play services 
* This code is returned in Activity.onActivityResult 
*/ 
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000; 

private GoogleMap mMap; // Might be null if Google Play services APK is not available 

private GoogleApiClient mGoogleApiClient; 
private LocationRequest mLocationRequest; 

public double currentLatitude; 
public double currentLongitude; 
private LatLng userLocation = new LatLng(currentLatitude,currentLongitude); 
public LatLng Besabella= new LatLng(10.351763, 123.953683); 
private LatLng StPeter= new LatLng(10.351910, 123.952619); 
private double x = CalculationByDistance(userLocation,Besabella); 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_maps); 
    setUpMapIfNeeded(); 

    mGoogleApiClient = new GoogleApiClient.Builder(this) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API) 
      .build(); 

    // Create a LocationRequest object 
    mLocationRequest = LocationRequest.create() 
      .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) 
      .setInterval(10 * 1000)  // 10 seconds, in milliseconds 
      .setFastestInterval(1 * 1000); // 1 second, in milliseconds 
} 

@Override 
protected void onResume() { 
    super.onResume(); 
    setUpMapIfNeeded(); 
    mGoogleApiClient.connect(); 
} 

@Override 
protected void onPause() { 
    super.onPause(); 

    if (mGoogleApiClient.isConnected()) { 
     LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 
     mGoogleApiClient.disconnect(); 
    } 
} 
public double CalculationByDistance(LatLng StartP, LatLng EndP) { 
    int Radius = 6371;// radius of earth in Kilometers 
    double lat1 = StartP.latitude; 
    double lat2 = EndP.latitude; 
    double lon1 = StartP.longitude; 
    double lon2 = EndP.longitude; 
    double dLat = Math.toRadians(lat2 - lat1); 
    double dLon = Math.toRadians(lon2 - lon1); 
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) 
      + Math.cos(Math.toRadians(lat1)) 
      * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon/2) 
      * Math.sin(dLon/2); 
    double c = 2 * Math.asin(Math.sqrt(a)); 
    double valueResult = Radius * c; 
    double km = valueResult/1; 
    DecimalFormat newFormat = new DecimalFormat("####"); 
    int kmInDec = Integer.valueOf(newFormat.format(km)); 
    double meter = valueResult % 1000; 
    int meterInDec = Integer.valueOf(newFormat.format(meter)); 
    Log.i("Radius Value", "" + valueResult + " KM " + kmInDec 
      + " Meter " + meterInDec); 

    return Radius * c; 
} 
private void setUpMapIfNeeded() { 
    // Do a null check to confirm that we have not already instantiated the map. 
    if (mMap == null) { 
     // Try to obtain the map from the SupportMapFragment. 
     mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) 
       .getMap(); 
     // Check if we were successful in obtaining the map. 
     if (mMap != null) { 
      setUpMap(); 
     } 
    } 
} 


private void setUpMap() { 


    mMap.addMarker(new MarkerOptions() 
      .position(new LatLng(10.351763, 123.953683)) 
      .title("Besabella Parking Lot") 
      .snippet("Distance : " + x + " KM ") 
      .icon(BitmapDescriptorFactory.fromBitmap(resizeMapIcons("p_icon", 100, 100)))); 

    mMap.addMarker(new MarkerOptions() 
      .position(new LatLng(10.351910, 123.952619)) 
      .title("St. Peter Agrivet Pay Parking") 
      .icon(BitmapDescriptorFactory.fromBitmap(resizeMapIcons("p_icon",100,100)))); 

    mMap.addMarker(new MarkerOptions() 
      .position(new LatLng(10.352203, 123.957021)) 
      .title("Norbads Parking Lot") 
      .icon(BitmapDescriptorFactory.fromBitmap(resizeMapIcons("p_icon",100,100)))); 

    mMap.addMarker(new MarkerOptions() 
      .position(new LatLng(10.329674, 123.943967)) 
      .title("Accu-Carwash and Pay Parking") 
      .icon(BitmapDescriptorFactory.fromBitmap(resizeMapIcons("p_icon", 100, 100)))); 

    mMap.addMarker(new MarkerOptions() 
      .position(new LatLng(10.340262, 123.941552)) 
      .title("Entica pay parking") 
      .icon(BitmapDescriptorFactory.fromBitmap(resizeMapIcons("p_icon", 100, 100)))); 

    mMap.addMarker(new MarkerOptions() 
      .position(new LatLng(10.345590, 123.959633)) 
      .title("Bongo's pay parking") 
      .icon(BitmapDescriptorFactory.fromBitmap(resizeMapIcons("p_icon", 100, 100)))); 

    mMap.addMarker(new MarkerOptions() 
      .position(new LatLng(10.341577, 123.913261)) 
      .title("EDSHAI HOMEOWNERS") 
      .icon(BitmapDescriptorFactory.fromBitmap(resizeMapIcons("p_icon", 100, 100)))); 

} 

private void handleNewLocation(Location location) { 
    Log.d(TAG, location.toString()); 

    currentLatitude = location.getLatitude(); 
    currentLongitude = location.getLongitude(); 
    LatLng userLocation= new LatLng(currentLatitude, currentLongitude); 


    //mMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Current Location")); 
    MarkerOptions options = new MarkerOptions() 
      .position(userLocation) 
      .title("YOU ARE HERE") 
      .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)); 
    mMap.addMarker(options); 
    // Move the camera instantly to location with a zoom of 15. 
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15)); 

    // Zoom in, animating the camera. 
    mMap.animateCamera(CameraUpdateFactory.zoomTo(14), 2000, null); 

    addCircleToMap(currentLatitude, currentLongitude); 

} 

@Override 
public void onConnected(Bundle bundle) { 
    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
    if (location == null) { 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
    } 
    else { 
     handleNewLocation(location); 
    } 
} 

@Override 
public void onConnectionSuspended(int i) { 

} 

@Override 
public void onConnectionFailed(ConnectionResult connectionResult) { 
    /* 
    * Google Play services can resolve some errors it detects. 
    * If the error has a resolution, try sending an Intent to 
    * start a Google Play services activity that can resolve 
    * error. 
    */ 
    if (connectionResult.hasResolution()) { 
     try { 
      // Start an Activity that tries to resolve the error 
      connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST); 
      /* 
      * Thrown if Google Play services canceled the original 
      * PendingIntent 
      */ 
     } catch (IntentSender.SendIntentException e) { 
      // Log the error 
      e.printStackTrace(); 
     } 
    } else { 
     /* 
     * If no resolution is available, display a dialog to the 
     * user with the error. 
     */ 
     Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode()); 
    } 
} 

@Override 
public void onLocationChanged(Location location) { 
    handleNewLocation(location); 
} 

public void addCircleToMap(double lat, double longi) { 

    // circle settings 
    int radiusM = 1000; // your radius in meters 
    double latitude2 = lat; // your center latitude 
    double longitude2 = longi; // your center longitude 

      LatLng latLng = new LatLng(latitude2,longitude2); 

    // draw circle 
    int d = 500; // diameter 
    Bitmap bm = Bitmap.createBitmap(d, d, Bitmap.Config.ARGB_8888); 
    Canvas c = new Canvas(bm); 
    Paint p = new Paint(); 
    p.setColor(getResources().getColor(R.color.wallet_holo_blue_light)); 
    c.drawCircle(d/2, d/2, d/2, p); 

    // generate BitmapDescriptor from circle Bitmap 
    BitmapDescriptor bmD = BitmapDescriptorFactory.fromBitmap(bm); 

// mapView is the GoogleMap 
    mMap.addGroundOverlay(new GroundOverlayOptions(). 
      image(bmD). 
      position(latLng,radiusM*2,radiusM*2). 
      transparency(0.4f)); 
    } 

} 

回答

0

试试这个。

Location locationA = new Location("point A"); 
    locationA.setLatitude(lat); 
    locationA.setLongitude(lon); 
    Location locationB = new Location("point B"); 
    locationB.setLatitude(Constant.latitude); 
    locationB.setLongitude(Constant.longitude); 
    dist =locationA.distanceTo(locationB) ; 

对于来自谷歌的地方与工作地点参考这里: - http://coderzpassion.com/android-location-using-google-play-services/