【发布时间】:2016-07-07 10:14:49
【问题描述】:
我知道以前有人问过这个问题,但所有可用的解决方案都要求我使用 onLocationChanged() 方法,因此我可以使用 getLatitude() 和 getLongitude() 方法来获取坐标。
但是当我的设备位置改变时,onLocationChanged() 会被调用。因此,为了获得我当前的位置,我必须移动我的设备。
但我想在不移动设备的情况下获取当前坐标。此外,我在某处读到我可以手动调用onLocationChanged() 方法,我可以再次获得最后一个已知位置。难道最后一个已知位置不是我当前的位置吗?还是可以使用最后一个已知的位置解决方案?
这是我用来实现 LocationListener 的类的一部分。
public class MyLocListener extends MapsActivity implements LocationListener {
public void onLocationChanged(Location location)
{
if(location!=null)
{
MapsActivity.setLatitude(location.getLatitude());
MapsActivity.setLongitude(location.getLongitude());
}
}}
这是我用来为我的地图活动提供坐标的函数的覆盖。纬度和经度是两个双精度类型变量。在此类中,纬度和经度变量以 0 开头,并且它们保持不变,因为仅在我的位置更改时才调用 onLocationChanged() 函数。因此我在地图上看不到我当前的位置。
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LocationManager myLocManager;
myLocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
MyLocListener loc = new MyLocListener();
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) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
myLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, loc);
LatLng sydney = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
【问题讨论】:
-
如果你在网上搜索“android 当前位置”你会找到developer.android.com/training/location/retrieve-current.html
-
看看答案一步一步代码stackoverflow.com/a/38397092/5955362