【发布时间】:2017-09-22 09:29:58
【问题描述】:
我正在研究谷歌地图。我想获取用户位置并在地图上显示他。我写了一个 Locationlistener 来获取用户的位置。
public Location getUserLocation(){
try {
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
return null;
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,DISTANCE_CALC,TIME_UPDATE, this);
Log.d("Network", "Network Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,DISTANCE_CALC,TIME_UPDATE, this);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
getUserLocation() 是LocationListener 中的功能之一,它将通过 GPS 或网络返回用户位置。我正在从这样的片段中调用此函数。
if (Build.VERSION.SDK_INT >= 23){
if (checkPermission()) {
location = locHandler.getUserLocation();
if(location!=null)
showTheMaps(location);
else
AlertBuilder(title,body);
}else {
requestPermission();
}
}else {
//The build is less than marshmellow so no need for permission
location = locHandler.getUserLocation();
try {
// double d = location.getLatitude();
showTheMaps(location);
}catch (NullPointerException e){
AlertBuilder(title, body);
}
}
public void showTheMaps(Location location){
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),location.getLongitude()), DataModel.zoomlevel);
googleMap.animateCamera(cameraUpdate);
}
AlertBuilder 函数将显示一个带有按钮的警报框,单击该按钮会关闭应用程序。
从屏幕截图中可以看出,GPS 已启用,但返回给我的位置为空,并且应用程序在显示警报对话框后关闭。 可能是什么问题呢?为什么打开 GPS 后位置仍返回 null?
【问题讨论】:
-
在您询问位置时 GPS 是否已经定位?
-
我不知道..图标出现后会有延迟..你的意思是@Carcigenicate..对话框出现在图标出现在顶部之前
-
requestLocationUpdates()仅启动获取位置的(异步)过程。如果您在此之后立即致电getLastKnownLocation(),则该位置尚不可用。你的类应该实现一个位置监听器并在onLocationChanged()回调中接收位置。 Stack Overflow上有很多例子。 -
@Tyson 在尝试获取位置之前检查修复的准确性。 3 年前,当我使用 Python Android api 与 GPS 一起工作时,我似乎记得需要等待让它找到我的位置,然后再询问。如果您尝试在 GPS 修复之前获取位置,请查看 API 文档,了解会发生什么情况。
-
Only use
getLastKnownLocation()as an optimization。您的代码需要能够处理通过onLocationChanged()接收位置除了可能从getLastKnownLocation()获取位置。
标签: android gps location google-maps-android-api-2