我打开地图活动后无法立即获取当前位置

时间:2017-07-25 06:57:49

标签: java android google-maps-markers

我打开Goog​​le地图活动后无法立即获取当前位置信息。 虽然它显示带有蓝点标记的当前位置。

我看到一条异常消息:java.lang.NullPointerException:尝试调用虚方法' double android.location.Location.getLatitude()'在空对象引用上

获取坐标需要花费大量时间。为此,我必须移动手机并等待。

这是我的代码:

if (Build.VERSION.SDK_INT < 25) {
        if (ContextCompat.checkSelfPermission(this, 
Manifest.permission.ACCESS_FINE_LOCATION) != 
PackageManager.PERMISSION_GRANTED) {
            // Ask for permission

            ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            if (ContextCompat.checkSelfPermission(this, 
Manifest.permission.ACCESS_FINE_LOCATION) != 
PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            }

        } else {


locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 
0, locationListener);

            lastKnownLocation = 
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try {
pDialog.hide();
locate = new LatLng(lastKnownLocation.getLatitude(), 
lastKnownLocation.getLongitude());

mMap.clear();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(locate, 13));
originMarkers.add(mMap.addMarker(new MarkerOptions()
        .title("Your Location")
        .position(locate)));

origin_lati = "" + lastKnownLocation.getLatitude();
origin_longi = "" + lastKnownLocation.getLongitude();

Log.e("Lati Longi", origin_lati+", "+origin_longi);
}catch (Exception e){
Log.e("Exception", e.toString());
}

        }
    } 

2 个答案:

答案 0 :(得分:0)

使用此:

首先创建Google Api客户端:

/**
     * Builds a GoogleApiClient.
     * Uses the addApi() method to request the Google Places API and the Fused Location Provider.
     */
    private synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */,
                        this /* OnConnectionFailedListener */)
                .addConnectionCallbacks(this)
                .addApi(LocationServices.API)
                .addApi(Places.GEO_DATA_API)
                .addApi(Places.PLACE_DETECTION_API)
                .build();
        createLocationRequest();
    }

 /**
     * Sets up the location request.
     */
    private void createLocationRequest() {
        mLocationRequest = new LocationRequest();

        /*
         * Sets the desired interval for active location updates. This interval is
         * inexact. You may not receive updates at all if no location sources are available, or
         * you may receive them slower than requested. You may also receive updates faster than
         * requested if other applications are requesting location at a faster interval.
         */
        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);

        /*
         * Sets the fastest rate for active location updates. This interval is exact, and your
         * application will never receive updates faster than this value.
         */
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);

        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

然后获取位置:

/**
     * Gets the current location of the device and starts the location update notifications.
     */
    private void getDeviceLocation() {
        /*
         * Request location permission, so that we can get the location of the
         * device. The result of the permission request is handled by a callback,
         * onRequestPermissionsResult.
         */
        if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
                android.Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            mLocationPermissionGranted = true;
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                    PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
        }
        /*
         * Get the best and most recent location of the device, which may be null in rare
         * cases when a location is not available.
         * Also request regular updates about the device location.
         */
        if (mLocationPermissionGranted) {
            mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
                    mLocationRequest, this);
        }
    }



/**
     * Handles the result of the request for location permissions.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[],
                                           @NonNull int[] grantResults) {
        mLocationPermissionGranted = false;
        switch (requestCode) {
            case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mLocationPermissionGranted = true;
                }
            }
        }
    }

现在mCurrentLocation让你当前的位置在任何你想要的地方使用它。

从onCreate构建Api客户端:

// Build the Play services client for use by the Fused Location Provider and the Places API.
        buildGoogleApiClient();
        mGoogleApiClient.connect();

然后在你的onResume:

里面
@Override
    protected void onResume() {
        super.onResume();
        if (mGoogleApiClient.isConnected()) {
            getDeviceLocation();
        }
    }

声明以下全局变量:

// The entry point to Google Play services, used by the Places API and Fused Location Provider.
    private GoogleApiClient mGoogleApiClient;
    // A request object to store parameters for requests to the FusedLocationProviderApi.
    private LocationRequest mLocationRequest;
    // The desired interval for location updates. Inexact. Updates may be more or less frequent.
    private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
    // The fastest rate for active location updates. Exact. Updates will never be more frequent
    // than this value.
    private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
            UPDATE_INTERVAL_IN_MILLISECONDS / 2;
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
    private boolean mLocationPermissionGranted;

    // The geographical location where the device is currently located.
    private Location mCurrentLocation;

答案 1 :(得分:0)

我只需稍加修改就得到了我的解决方案

    String provider;
    provider=locationManager.getProvider(LocationManager.NETWORK_PROVIDER).getName();

            if (Looper.myLooper() == null) {
                Looper.prepare();
            }

            locationManager.requestSingleUpdate(provider, locationListener, Looper.myLooper());

            locationManager.requestLocationUpdates(provider,0,0, locationListener);

            currentLocation = locationManager.getLastKnownLocation(provider);
try {
pDialog.hide();                                                                                     
locate = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());

mMap.clear();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(locate, 13));
originMarkers.add(mMap.addMarker(new MarkerOptions()
        .title("Your Location")
        .position(locate)));

origin_lati = "" + currentLocation.getLatitude();
origin_longi = "" + currentLocation.getLongitude();

Log.e("Lati Longi", origin_lati+", "+origin_longi);
}catch (Exception e){
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
Log.e("Exception", e.toString());
}