无法获取当前位置Google Map Android

时间:2016-05-10 04:23:27

标签: android google-maps

我知道这个问题与其他问题类似,但我无法理解在谷歌地图中获取我的位置的过程。我尝试过很多教程,但我觉得我错过了一些东西。

我在我的主要课程中使用以下代码:

 LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    //I am getting bestProvider = gps here 
    String bestProvider = locationManager.getBestProvider(criteria, true);
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
       //getting location null here 
        Location location = locationManager.getLastKnownLocation(bestProvider);

        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
    }else if((ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)){
  //getting location null here 
        Location location = locationManager.getLastKnownLocation(bestProvider);
        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
    }
}

@Override
public void onLocationChanged(Location location) {
    TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
    double latitude = location.getLatitude();
    double longitude = location.getLongitude();
    LatLng latLng = new LatLng(latitude, longitude);
    googleMap.addMarker(new MarkerOptions().position(latLng));
    googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
    locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}

2 个答案:

答案 0 :(得分:2)

在这里,您可以在应用程序中使用以下代码示例:

public class CurrentLocation {
Timer timer;
LocationManager locationManager;
LocationResult locationResult;
boolean gpsEnabled=false;
boolean networkEnabled=false;

public boolean getLocation(Context context, LocationResult result)
{
    //I use LocationResult callback class to pass location value from MyLocation to user code.
    locationResult=result;
    if(locationManager ==null)
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    //exceptions will be thrown if provider is not permitted.
    try{
        gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
    try{
        networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

    //don't start listeners if no provider is enabled
    if(!gpsEnabled && !networkEnabled)
        return false;

    if(gpsEnabled)
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
    if(networkEnabled)
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
    timer =new Timer();
    timer.schedule(new GetLastLocation(), 20000);
    return true;
}

LocationListener locationListenerGps = new LocationListener() {
    public void onLocationChanged(Location location) {
        timer.cancel();
        locationResult.gotLocation(location);
        locationManager.removeUpdates(this);
        locationManager.removeUpdates(locationListenerNetwork);
    }
    public void onProviderDisabled(String provider) {}
    public void onProviderEnabled(String provider) {}
    public void onStatusChanged(String provider, int status, Bundle extras) {}
};

LocationListener locationListenerNetwork = new LocationListener() {
    public void onLocationChanged(Location location) {
        timer.cancel();
        locationResult.gotLocation(location);
        locationManager.removeUpdates(this);
        locationManager.removeUpdates(locationListenerGps);
    }
    public void onProviderDisabled(String provider) {}
    public void onProviderEnabled(String provider) {}
    public void onStatusChanged(String provider, int status, Bundle extras) {}
};

class GetLastLocation extends TimerTask {
    @Override
    public void run() {
        locationManager.removeUpdates(locationListenerGps);
        locationManager.removeUpdates(locationListenerNetwork);

        Location net_loc=null, gps_loc=null;
        if(gpsEnabled)
            gps_loc= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if(networkEnabled)
            net_loc= locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

        //if there are both values use the latest one
        if(gps_loc!=null && net_loc!=null){
            if(gps_loc.getTime()>net_loc.getTime())
                locationResult.gotLocation(gps_loc);
            else
                locationResult.gotLocation(net_loc);
            return;
        }

        if(gps_loc!=null){
            locationResult.gotLocation(gps_loc);
            return;
        }
        if(net_loc!=null){
            locationResult.gotLocation(net_loc);
            return;
        }
        locationResult.gotLocation(null);
    }
}

}

答案 1 :(得分:0)

使用此代码获取GPS提供商或网络提供商的当前位置

if (locationManager == null) {
                locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            }
            if (locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER)) {
                isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                isNetworkProviderEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                if (isGPSEnabled) {
                    location = getLastLocationByProvider(locationManager, LocationManager.GPS_PROVIDER, getApplicationContext());
                } else if (isNetworkProviderEnabled) {
                    location = getLastLocationByProvider(locationManager, LocationManager.NETWORK_PROVIDER, getApplicationContext());
                }
                if (location != null) {
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                } else {
                    if (isNetworkProviderEnabled) {
                        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100000, 1, this);
                        provider_info = LocationManager.NETWORK_PROVIDER;
                    } else if (isGPSEnabled) {
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100000, 1, this);
                        provider_info = LocationManager.GPS_PROVIDER;
                    } else {

                        alertDialog = Util.showOkDialog(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (Env.currentActivity != null) {
                                    if (Env.currentActivity instanceof LocationActivity) {
                                        try {
                                            gotoSettings();
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }

                                }
                                if (alertDialog != null) {
                                    alertDialog.dismiss();
                                    alertDialog = null;
                                }

                            }
                        }, this.getResources().getString(R.string.location_service_validation));

                    }

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