【发布时间】:2018-04-01 17:57:47
【问题描述】:
我正在尝试为我的天气应用程序获取用户的当前位置,但我得到了一些“美国”区域的位置。我尝试了多个教程,但未能获得正确的当前位置。
它返回我:
纬度:37.421998333333335
经度:-122.08400000000002
地点是“Mountain View,CA,US”
我使用的代码如下:
GpsTracker.java
public class GpsTracker implements LocationListener {
Context context;
public GpsTracker(Context c)
{
context = c;
}
public Location getLocation()
{
if(ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
Toast.makeText(context,"Permission not granted",Toast.LENGTH_SHORT).show();
return null;
}
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isGpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(isGpsEnabled)
{
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this);
Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return l;
}
else{
Toast.makeText(context,"Enable GPS",Toast.LENGTH_SHORT).show();
}
return null;
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}
在我的主课中,我得到这样的位置:
public void getLocation()
{
gpsTracker = new GpsTracker(getApplicationContext());
Location l = gpsTracker.getLocation();
if(l != null)
{
lat = l.getLatitude();
lon = l.getLongitude();
}
Log.d("User's location","Latitude"+lat);
Log.d("User's location","Longitude"+lon);
}
【问题讨论】:
-
使用
FusedLocationProviderClient -
你能提供一些链接或一些代码吗?我不熟悉这个
标签: java android android-location