从GPS提供商明确获取坐标

时间:2013-12-10 13:51:56

标签: android gps

我想要实现一些我虽然很简单的东西,但现在我最终感到有些困惑。 我希望以这种方式获得用户的坐标

  • 是否有GPS提供商?
    • 如果是,请从gps
    • 获取坐标
    • 否则,如果有网络提供商从那里获取

我同时使用了locationManageronLocationChange()以及使用locationClient的新API,但我无法通过网络获取设备GPS的坐标。

这是locationManager

的那个
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use default
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);

// Initialize the location fields
if (location != null) {
    System.out.println("Provider " + provider + " has been selected.");
    // new AlertDialog.Builder(v.getContext()).setMessage("Provider " + provider + " has been selected.").show();
    onLocationChanged(location);   
    System.out.println(location.getLatitude());
    Intent intent = new Intent(getApplicationContext(),DriveMeActivity.class);
    intent.putExtra("monument", monument);
    intent.putExtra("latitude", location.getLatitude());
    intent.putExtra("longitude",location.getLongitude());
    startActivity(intent);
} else {
    new AlertDialog.Builder(con).setMessage("Location not available").show();
    System.out.println("Location not available");
    System.out.println("Location not available");
}

这是locationClient

的那个
GooglePlayServicesUtil.isGooglePlayServicesAvailable(v.getContext())
if(mLocationClient.getLastLocation()!=null)
    Toast.makeText(getApplicationContext(),
        mLocationClient.getLastLocation().getLongitude()+ "|" + 
        mLocationClient.getLastLocation().getLatitude() ,
        Toast.LENGTH_SHORT).show();

3 个答案:

答案 0 :(得分:2)

这是找到最佳可用提供商的完整代码,无论是gps还是network,还是显示settings menu以启用location services

    public class DSLVFragmentClicks extends Activity implements LocationListener {
private final int BESTAVAILABLEPROVIDERCODE = 1;
private final int BESTPROVIDERCODE = 2;
LocationManager locationManager;
String bestProvider;
String bestAvailableProvider;

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == BESTPROVIDERCODE) {
        if (requestCode != Activity.RESULT_OK || locationManager.isProviderEnabled(bestProvider)) {
            Toast.makeText(getActivity(), "Error! Location Service " + bestProvider + " not Enabled", Toast.LENGTH_LONG).show();

        } else {
            getLocation(bestProvider);
        }
    } else {
        if (requestCode != Activity.RESULT_OK || locationManager.isProviderEnabled(bestAvailableProvider)) {
            Toast.makeText(getActivity(), "Error! Location Service " + bestAvailableProvider + " not Enabled", Toast.LENGTH_LONG).show();

        } else {
            getLocation(bestAvailableProvider);
        }
    }
}

public void getLocation(String usedLocationService) {
    Toast.makeText(getActivity(), "getting Location", Toast.LENGTH_SHORT).show();
    long updateTime = 0;
    float updateDistance = 0;
    // finding the current location 
    locationManager.requestLocationUpdates(usedLocationService, updateTime, updateDistance, this);

}


@Override
public void onCreate(Bundle savedState) {
    super.onCreate(savedState);
    setContentView(R.layout.main);
    // set a Criteria specifying things you want from a particular Location Service
            Criteria criteria = new Criteria();
            criteria.setSpeedRequired(false);
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            criteria.setCostAllowed(true);
            criteria.setBearingAccuracy(Criteria.ACCURACY_HIGH);
            criteria.setAltitudeRequired(false);

            locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
            // finding best provider without fulfilling the criteria
            bestProvider = locationManager.getBestProvider(criteria, false);
            // finding best provider which fulfills the criteria
            bestAvailableProvider = locationManager.getBestProvider(criteria, true);
            String toastMessage = null;
            if (bestProvider == null) {
                toastMessage = "NO best Provider Found";
            } else if (bestAvailableProvider != null && bestAvailableProvider.equals(bestAvailableProvider)) {
                boolean enabled = locationManager.isProviderEnabled(bestAvailableProvider);
                if (!enabled) {
                    Toast.makeText(getActivity(), " Please enable " + bestAvailableProvider + " to find your location", Toast.LENGTH_LONG).show();
// show settings menu to start gps or network location service
                    Intent mainIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(mainIntent, BESTAVAILABLEPROVIDERCODE);
                } else {
                    getLocation(bestAvailableProvider);
                }
                toastMessage = bestAvailableProvider + " used for getting your current location";
            } else {
                boolean enabled = locationManager.isProviderEnabled(bestProvider);
                if (!enabled) {
                    Toast.makeText(getActivity(), " Please enable " + bestProvider + " to find your location", Toast.LENGTH_LONG).show();
                    Intent mainIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(mainIntent, BESTPROVIDERCODE);
                } else {
                    getLocation(bestProvider);
                }
                toastMessage = bestProvider + " is used to get your current location";

            }
            Toast.makeText(getActivity(), toastMessage, Toast.LENGTH_LONG).show();
            return true;
        }
    });
}

@Override
public void onLocationChanged(Location location) {
    Log.d("Location Found", location.getLatitude() + " " + location.getLongitude());
    // getting the street address from longitute and latitude
    Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
    String addressString = "not found !!";
    try {
        List<Address> addressList = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        StringBuilder stringBuilder = new StringBuilder();
        if (addressList.size() > 0) {
            Address address = addressList.get(0);
            for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                stringBuilder.append(address.getAddressLine(i)).append("\n");
                stringBuilder.append(address.getLocality()).append("\n");
                stringBuilder.append(address.getPostalCode()).append("\n");
                stringBuilder.append(address.getCountryName()).append("\n");
            }

            addressString = stringBuilder.toString();
            locationManager.removeUpdates(this);
        }
    } catch (IOException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }
    Toast.makeText(getActivity(), " Your Location is " + addressString, Toast.LENGTH_LONG).show();
}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
    //To change body of implemented methods use File | Settings | File Templates.
}

@Override
public void onProviderEnabled(String s) {
    //To change body of implemented methods use File | Settings | File Templates.
}

@Override
public void onProviderDisabled(String s) {
    //To change body of implemented methods use File | Settings | File Templates.
}
}

我已经在评论中解释了很多,但如果你仍然不明白,那么随便问一下。

答案 1 :(得分:1)

我希望你在设备上尝试它并且你已经在开放时尝试过。在大多数情况下,在你离开之前,你不会得到gps坐标。

答案 2 :(得分:1)

很可能您没有位置修复和GPS locationProvider需要时间才能获得与网络位置提供商相比的位置修复。

您可以做的是可以使用上次已知的位置修复。

String locationProvider = LocationManager.GPS_PROVIDER;
// Or use LocationManager.NETWORK_PROVIDER
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);

但进一步的问题是您可能有旧的位置修复,网络提供商可以为您提供更好的位置。

Android拥有非常好的文档和示例代码,以找到最知名的位置。 http://developer.android.com/guide/topics/location/strategies.html