【问题标题】:Getting Initial Coordinates at onMayReady() in Android Google Map API在 Android Google Map API 中的 onMayReady() 处获取初始坐标
【发布时间】:2019-12-14 05:09:54
【问题描述】:

我正在实施 Google Maps api,我试图在 onMapReady() 开始时获取初始位置。

mCurrentLocation 应该是存储位置的变量,所以我尝试在onMapReady() 的日志中输出它,但一开始mCurrentLocationnull,所以首先我必须请求一个位置。我对api不熟悉。我猜了一下,把startLocationUpdates(this)放在前面。

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.getUiSettings().setZoomControlsEnabled(true);
    mMap.setMyLocationEnabled(true);

    LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 14.0f));

    // Start the update??
    startLocationUpdates(this);
    // This is where I want to retrieve the location coordinates
    Log.w("Location", "Current reading: " + mCurrentLocation.toString());
}

没有用。在堆栈跟踪中它说java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.location.Location.toString()' on a null object reference。我也试过initLocation()之类的其他方法,也没用。

这是剩下的代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    initLocations();
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case ACCESS_FINE_LOCATION: {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                mFusedLocationClient.requestLocationUpdates(mLocationRequest,
                        mLocationCallback, null /* Looper */);
            }
            return;
        }
    }
}

private void initLocations() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    ACCESS_FINE_LOCATION);
        }
        return;
    }
}

private void startLocationUpdates(Context context) {
    Intent intent = new Intent(context, LocationService.class);
    mLocationPendingIntent = PendingIntent.getService(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        Task<Void> locationTask = mFusedLocationClient.requestLocationUpdates(mLocationRequest,
                mLocationPendingIntent);
        if (locationTask != null) {
            locationTask.addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    if (e instanceof ApiException) {
                        Log.w("Main2Activity", ((ApiException) e).getStatusMessage());
                    } else {
                        Log.w("Main2Activity", e.getMessage());
                    }
                }
            });

            locationTask.addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    Log.d("Main2Activity", "restarting gps successful!");
                }
            });


        }
    }
}

private void stopLocationUpdates(){
    mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}

@Override
protected void onResume() {
    super.onResume();
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(5000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    accelerometer.startAccelerometerRecording();

}

private Location mCurrentLocation;
private String mLastUpdateTime;
LocationCallback mLocationCallback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        super.onLocationResult(locationResult);
        mCurrentLocation = locationResult.getLastLocation();
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        Log.i("MAP", "new location " + mCurrentLocation.toString());
        if (mMap != null)
            mMap.addMarker(new MarkerOptions().position(new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()))
                    .title(mLastUpdateTime));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()), 14.0f));
    }
};

请求位置的正确方法是什么?

【问题讨论】:

  • 调用startLocationUpdates()方法后,返回实际位置有一段延迟。这个过程是异步的。因此,如果您尝试立即记录该位置,则不会记录任何值。

标签: java android google-maps location-services


【解决方案1】:

我总是使用 LocationManager 来获取当前位置,同时确保您当前的 gps 已打开。

final LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
locationManager.requestSingleUpdate(criteria, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    // this is where you get the location location.getLatitude(), location.getLongitude()
                }

                @Override public void onStatusChanged(String provider, int status, Bundle extras) { }
                @Override public void onProviderEnabled(String provider) { }
                @Override public void onProviderDisabled(String provider) { }
            }, null);

【讨论】:

  • 谢谢你,Miftahun,虽然很奇怪,我已经导入了类,并且标准被实例化,就像你的代码和标准中的“setAccuracy”一样。setAccuarcy(Criteria.ACCURACY_FINE);为红色,返回错误“无法解析符号”。
  • 你确定你导入了正确的import android.location.Criteria;还是把代码放在方法里?
【解决方案2】:

您可以使用这种方法:

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tracking_order);

    mService = Common.geoCodeService();

    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

    mapFrag = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
    mapFrag.getMapAsync(this);
}

   public void onMapReady(GoogleMap googleMap)
{
    mMap=googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(120000); // two minute interval
    mLocationRequest.setFastestInterval(120000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            //Location Permission already granted
            mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
            mMap.setMyLocationEnabled(true);
        } else {
            //Request Location Permission
            checkLocationPermission();
        }
    }
    else {
        mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
        mMap.setMyLocationEnabled(true);
    }
}

LocationCallback mLocationCallback = new LocationCallback(){
    @Override
    public void onLocationResult(LocationResult locationResult) {
        for (Location location : locationResult.getLocations()) {
            Log.i("MapsActivity", "Location: " + location.getLatitude() + " " + location.getLongitude());
            mLastLocation = location;
            if (mCurrLocationMarker != null) {
                mCurrLocationMarker.remove();
            }

            //Place current location marker
            LatLng yourLocation = new LatLng(location.getLatitude(), location.getLongitude());
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(yourLocation);
            markerOptions.title("Current Position");
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
            mCurrLocationMarker = mMap.addMarker(markerOptions);

            //move map camera
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(yourLocation, 11));

            //after add marker for your location add marker for this order

            drawRoute(yourLocation,Common.currentRequest.getAddress());

        }


    }

};

【讨论】:

  • 谢谢!但是恐怕它还没有工作。 mService前面应该放什么类型?
猜你喜欢
  • 2015-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-04
  • 2013-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多