在Android谷歌地图中获取当前位置Lat Long为0.0

时间:2013-09-19 15:07:58

标签: android gps google-maps-android-api-2 android-maps-v2

我想要在当前位置的纬度和经度。 它在模拟器上运行,但在移动设备上给出lat / long 0.0。 我的设备是LG 4x高清。 src / .java文件:

private TextView txt_lat,txt_lon,txt_gps;
private LocationManager lm;
double lat, lon;
protected LocationListener locatlist;
Location locat;
GpsStatus.Listener gpslist;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txt_lat= (TextView) findViewById(R.id.textView2);
    txt_lon= (TextView) findViewById(R.id.textView4);
    txt_gps = (TextView) findViewById(R.id.textView5);
            lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
            locat = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if(locat != null) {
                lat = locat.getLatitude();
                lon = locat.getLongitude();
            }
            locatlist = new LocationListener() {

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onProviderEnabled(String provider) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onProviderDisabled(String provider) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onLocationChanged(Location location) {
                    // TODO Auto-generated method stub
                    lat = location.getLatitude();
                    lon = location.getLongitude();
                    txt_lat.setText("lat : "+lat);
                    txt_lon.setText("lon : "+lon);
                }
            };
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locatlist);
            if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
                txt_gps.setText("GPS is started");
            }
            else if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
                txt_gps.setText("GPS is non-start");
            }
            txt_lat.setText("lat : "+lat);
            txt_lon.setText("lon : "+lon);
} 

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

mainfest权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

lat long在设备上永远是0.0,但它可以在模拟器上运行。 它是一个简单的代码,为什么它不工作? 我哪里错了?

1 个答案:

答案 0 :(得分:0)

lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);-->may be here you get null value of location manager replace with this line  
lm = (LocationManager) 
            context.getSystemService(Context.LOCATION_SERVICE);