谷歌位置API无法准确显示当前位置

时间:2015-11-18 11:30:14

标签: android-activity android-location

当我运行此代码时,它在我点击button_currentlocation后给出当前位置。但是当我检查准确度时,它的准确度非常低(有时候是5000米)。但我需要以高精度(大约10米)获得当前位置一次 如果有人可以帮助我纠正我的编码,那将对我的研究有很大的帮助。

我的措辞如下

在我的清单

 uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"

LocationProvider Class

public class LocationProvider implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

public abstract interface LocationCallback {
    public void handleNewLocation(Location location);
}

public static final String TAG = LocationProvider.class.getSimpleName();

/*
 * 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 LocationCallback mLocationCallback;
private Context mContext;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;

public LocationProvider(Context context, LocationCallback callback) {
    mGoogleApiClient = new GoogleApiClient.Builder(context)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    mLocationCallback = callback;

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

    mContext = context;
}

public void connect() {
    mGoogleApiClient.connect();
}

public void disconnect() {
    if (mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();
    }
}

@Override
public void onConnected(Bundle bundle) {
    Log.i(TAG, "Location services connected.");

    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (location == null) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
    else {
        mLocationCallback.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() && mContext instanceof Activity) {
        try {
            Activity activity = (Activity)mContext;
            // Start an Activity that tries to resolve the error
            connectionResult.startResolutionForResult(activity, 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) {
    mLocationCallback.handleNewLocation(location);
}
}

在HomePage类

package com.ksfr.finaltest01;


import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.android.gms.maps.model.LatLng;

public class HomePage extends Activity implements  AdapterView.OnItemSelectedListener,LocationProvider.LocationCallback {

public static final String TAG = HomePage.class.getSimpleName();

Button button_disFinder;
private LocationProvider locationProvider;
String Provider,Str_endLocation;
double cur_latitude, cur_longitude,cur_accuracy, end_latitude, end_longitude;
float distance_cur_to_end;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home_page);

    locationProvider = new LocationProvider(this,this);

    Spinner spinner = (Spinner) findViewById(R.id.spinner_schools);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.school_array, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });


}

  public void CurrentLocationClicked(View view) {
    if (cur_latitude!=0&&cur_longitude != 0 ){
        Spinner spinner = (Spinner) findViewById(R.id.spinner_schools);
        spinner.setClickable(true);
        String message= String.format("Current Location\n" + "Latitude  :" + cur_latitude + "\nLongitude :" + cur_longitude+"\nAccuracy :"+cur_accuracy+"\nProvider :"+Provider);
        Toast.makeText(HomePage.this, message, Toast.LENGTH_LONG).show();
    }
    else{
        String message= String.format("Location services disconnected.\nSwich ON Location Service to work App.");
        Toast.makeText(HomePage.this, message, Toast.LENGTH_LONG).show();
        //System.exit(0);

    }
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    if(position!= 0) {
        Str_endLocation=String.valueOf(parent.getItemAtPosition(position));
        Toast.makeText(getApplicationContext(), Str_endLocation + " Selected", Toast.LENGTH_SHORT).show();
        switch (Str_endLocation){
                //end location latitude and logitude will be taken from here.
                case "Kahagolla National School":
                end_latitude = 6.816703;end_longitude = 80.9637076;
                break;
        }

        String message3= String.format("End Location\n"+"Latitude  :"+end_latitude+"\nLongitude :"+end_longitude);//For Testing
        Toast.makeText(HomePage.this, message3, Toast.LENGTH_LONG).show();//For Testing
    }
}

@Override
public void onNothingSelected(AdapterView<?> parent) {
}

  public void FindDistanceClicked (View view){
    Location curlocation = new Location("");
    curlocation.setLatitude(cur_latitude);
    curlocation.setLongitude(cur_longitude);

    Location endlocation = new Location("");
    endlocation.setLatitude(end_latitude);
    endlocation.setLongitude(end_longitude);
    distance_cur_to_end = curlocation.distanceTo(endlocation)/1000;

    String message5= String.format("Distance from current location to\n" + Str_endLocation + "  :" + String.format("%.3g%n", distance_cur_to_end)+"km");//For testing
    Toast.makeText(HomePage.this, message5, Toast.LENGTH_LONG).show();//For testing

}


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

    cur_latitude = location.getLatitude();
    cur_longitude = location.getLongitude();
    cur_accuracy = location.getAccuracy();
    Provider = location.getProvider();


    LatLng cur_latLng = new LatLng(cur_latitude, cur_longitude);

}

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

@Override
protected void onPause() {
    super.onPause();
    locationProvider.disconnect();
}

public  void ClearClicked (View view){

}

}

2 个答案:

答案 0 :(得分:0)

尝试撤消onConnected方法位置代码。 首先尝试获取当前位置,如果不可用,请尝试获取lastKnown位置。 像这样的事情

if(location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    if(locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                        if(location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }

答案 1 :(得分:0)

我最后纠正了我的问题, 从这个方法我得到3米准确度的位置,我想要。

这是代码 DistanceFinderActivity.java

private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 5*1000; // in Milliseconds

protected LocationManager locationManager;


double cur_latitude, cur_longitude,cur_accuracy, end_latitude, end_longitude;
float distance_cur_to_end;
public LatLng cur_latLng,end_latLng;
MyLocationListener myLocationListener =new MyLocationListener();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_distance_finder);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    locationManager.requestLocationUpdates(
            GPS_PROVIDER,
            MINIMUM_TIME_BETWEEN_UPDATES,
            MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
            myLocationListener
    );
//......
}

protected void showCurrentLocation() {

    Location location = locationManager.getLastKnownLocation(GPS_PROVIDER);
    if (location != null) {
        cur_latitude = location.getLatitude();
        cur_longitude = location.getLongitude();
        cur_accuracy = location.getAccuracy();
        Provider = location.getProvider();
        DecimalFormat df = new DecimalFormat("#.###");
        df.setMinimumFractionDigits(2);
        String message = String.format(
                "Current Location \nLatitude: %1$s\nLongitude: %2$s\nAccuracy: %3$s\n" +
                        " Provider: %4$s\nWait until new location capture",
                cur_latitude, cur_longitude,String.valueOf(df.format(cur_accuracy)),Provider.toUpperCase()
        );
        Toast.makeText(MainDistanceFinderActivity.this, message,
                Toast.LENGTH_LONG).show();
    }

}

private class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
        cur_latitude = location.getLatitude();
        cur_longitude = location.getLongitude();
        cur_accuracy = location.getAccuracy();
        Provider = location.getProvider();
        DecimalFormat df = new DecimalFormat("#.###");
        df.setMinimumFractionDigits(2);
        String message = String.format(
                "New Location Captured. \nLatitude: %1$s\nLongitude: %2$s\nAccuracy: %3$s\n" +
                        " Provider: %4$s",
                cur_latitude, cur_longitude,String.valueOf(df.format(cur_accuracy)), Provider.toUpperCase()
        );
        Toast.makeText(MainDistanceFinderActivity.this, message, Toast.LENGTH_LONG).show();
    }

    public void onStatusChanged(String s, int i, Bundle b) {
        Toast.makeText(MainDistanceFinderActivity.this, "Provider status changed",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderDisabled(String s) {
        Toast.makeText(MainDistanceFinderActivity.this,
                "Provider disabled by the user. GPS turned off",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderEnabled(String s) {
        Toast.makeText(MainDistanceFinderActivity.this,
                "Provider enabled by the user. GPS turned on",
                Toast.LENGTH_LONG).show();
    }

}