我知道之前有人问过这个问题,但所有可用的解决方案都要求我使用 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());
}
}}
这是我用来为我的 map Activity 提供坐标的函数的覆盖。 latitude 和 longitude 是两个 double 类型的变量。在此类中,纬度和经度变量从 0 开始,并且它们保持这种状态,因为 onLocationChanged()
函数仅在我的位置更改时调用。因此我在 map 上看不到我当前的位置。
@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));
}
最佳答案
你应该使用 GooglePlayServices
compile 'com.google.android.gms:play-services-location:7.0.0'
获取位置
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
连接后
public class MainActivity extends ActionBarActivity implements
ConnectionCallbacks, OnConnectionFailedListener {
...
@Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
}
更多详细信息请查看documentation .
关于java - 如何获取当前的 GPS 位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38242917/