使用Google Maps API在Android中查找设备当前位置的纬度和经度值。

huangapple go评论79阅读模式
英文:

Finding the latitude and longitude values for the device's current location in Android with Google Maps API

问题

所以有很多类似的问题是基于这个提出的,我也找到了一个可行的解决方案。然而,这似乎只在我的物理Android设备上运行。如果我在模拟器上使用它,该方法将返回一个空值,我不知道为什么。许多来源提到有一个更好的替代方案,但他们没有具体说明是什么/如何。这是我用来获取我的设备当前位置的代码:

@SuppressWarnings("MissingPermission")
private LatLng getCurrentLocation() {
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    String locationProvider = LocationManager.NETWORK_PROVIDER;
    assert locationManager != null;
    android.location.Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
    return new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
}

我也不喜欢我不得不抑制警告的事实。我查看过的一些来源包括:

https://developer.android.com/training/location/retrieve-current.html#java

https://stackoverflow.com/questions/3145089/what-is-the-simplest-and-most-robust-way-to-get-the-users-current-location-on-a/3145655#3145655

第一个不起作用,我得到一个空值。第二个看起来对于我寻求的简单结果来说过于复杂。

英文:

So there are many similar questions asked based on this, and I have also got a working solution. However, this seems to only work on my physical Android device. If I were to use it with the emulator, the method returns a null value and I don't know why. Many sources mention that there is a better alternative to the code that I am currently using but they don't mention what/how exactly. This is the code that I am using to get the current location of my device:

@SuppressWarnings("MissingPermission")
    private LatLng getCurrentLocation() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        String locationProvider = LocationManager.NETWORK_PROVIDER;
        assert locationManager != null;
        android.location.Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
        return new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
    }

I also don't like the fact that I have to suppress warnings. Sources that I have looked at include:

https://developer.android.com/training/location/retrieve-current.html#java

https://stackoverflow.com/questions/3145089/what-is-the-simplest-and-most-robust-way-to-get-the-users-current-location-on-a/3145655#3145655

The first one doesn't work, I get a null value. The second one looks overly complicated for a simple result that I am seeking.

答案1

得分: 1

以下是翻译好的部分:

这段代码在我的一个项目中正常运行:

public class LocationManager {
    private static LocationManager requestManager;
    private FusedLocationProviderClient mLocationProviderClient;
    private Location mLocation;
    private Location mMyCurrentLocation;
    private locationSuccessListener mListener;

    public Location getLocation() {
        return mLocation;
    }

    public void setLocation(Location location) {
        mLocation = location;
    }

    private LocationManager(FusedLocationProviderClient fusedLocationProviderClient) {
        this.mLocationProviderClient = fusedLocationProviderClient;
    }

    public static LocationManager createInstance(FusedLocationProviderClient fusedLocationProviderClient) {
        if (requestManager != null) {
            return requestManager;
        } else {
            return requestManager = new LocationManager(fusedLocationProviderClient);
        }
    }

    public static LocationManager getInstance() {
        return requestManager;
    }

    public void setLocation(Activity activity) {
        mListener = (locationSuccessListener) activity;
        LocationCallback callback = new LocationCallback();
        LocationRequest locationRequest = new LocationRequest();
        Task<Void> r = mLocationProviderClient.requestLocationUpdates(locationRequest, callback, Looper.getMainLooper());
        r.addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                mLocationProviderClient.getLastLocation().addOnSuccessListener(activity, new OnSuccessListener<Location>() {
                    @Override
                    public void onSuccess(Location location) {
                        mMyCurrentLocation = location;
                        mLocation = location;
                        if (location != null) {
                            mListener.onLocationReceived();
                            mLocationProviderClient.removeLocationUpdates(callback);
                        }
                    }
                });
            }
        });
    }

    public Location getMyCurrentLocation() {
        return mMyCurrentLocation;
    }

    public interface locationSuccessListener {
        void onLocationReceived();
    }
}

你需要像这样做:

public class PlacesActivity extends SingleFragmentActivity implements NavigationView.OnNavigationItemSelectedListener, LocationManager.locationSuccessListener

然后在你的活动中你将获得这个:

@Override
public void onLocationReceived() {
    Location l = LocationManager.getInstance().getMyCurrentLocation();
    if (l == null) {
        Toast.makeText(this, "无法获取位置", Toast.LENGTH_SHORT).show();
    }
}

要获取权限,你应该这样做:

if (ContextCompat.checkSelfPermission(Objects.requireNonNull(getActivity()), Manifest.permission.ACCESS_FINE_LOCATION)
        != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(getActivity(),
            new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
            0);
}
英文:

This code works just fine in one of my projects:

public class LocationManager {
private static LocationManager requestManager;
private FusedLocationProviderClient mLocationProviderClient;
private Location mLocation;
private Location mMyCurrentLocation;
private locationSuccessListener mListener;
public Location getLocation() {
return mLocation;
}
public void setLocation(Location location) {
mLocation = location;
}
private LocationManager(FusedLocationProviderClient fusedLocationProviderClient) {
this.mLocationProviderClient = fusedLocationProviderClient;
}
public static LocationManager createInstance(FusedLocationProviderClient fusedLocationProviderClient) {
if (requestManager != null) {
return requestManager;
} else {
return requestManager = new LocationManager(fusedLocationProviderClient);
}
}
public static LocationManager getInstance() {
return requestManager;
}
public void setLocation(Activity activity) {
mListener = (locationSuccessListener) activity;
LocationCallback callback = new LocationCallback();
LocationRequest locationRequest = new LocationRequest();
Task&lt;Void&gt; r = mLocationProviderClient.requestLocationUpdates(locationRequest, callback, Looper.getMainLooper());
r.addOnSuccessListener(new OnSuccessListener&lt;Void&gt;() {
@Override
public void onSuccess(Void aVoid) {
mLocationProviderClient.getLastLocation().addOnSuccessListener(activity, new OnSuccessListener&lt;Location&gt;() {
@Override
public void onSuccess(Location location) {
mMyCurrentLocation = location;
mLocation = location;
if (location != null) {
mListener.onLocationReceived();
mLocationProviderClient.removeLocationUpdates(callback);
}
}
});
}
});
}
public Location getMyCurrentLocation() {
return mMyCurrentLocation;
}
public interface locationSuccessListener {
void onLocationReceived();
}

You need to do something like that:

public class PlacesActivity extends SingleFragmentActivity implements NavigationView.OnNavigationItemSelectedListener, LocationManager.locationSuccessListener

and then in your activity you will get this:

@Override
public void onLocationReceived() {
Location l = LocationManager.getInstance().getMyCurrentLocation();
if (l==null){
Toast.makeText(this, &quot;unable to get location&quot;, Toast.LENGTH_SHORT).show();
}
}

to get permission you suppose to do something like this:

if (ContextCompat.checkSelfPermission(Objects.requireNonNull(getActivity()), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
0);

huangapple
  • 本文由 发表于 2020年8月7日 21:15:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63302633.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定