2012-09-12 83 views
3

我正在使用这篇文章:What is the simplest and most robust way to get the user's current location on Android?来获取设备的当前位置。而我的代码是:在android地图上获取当前位置

locationResult = new LocationResult() { 

     @Override 
     public void gotLocation(Location location) { 
      if (location != null) { 
       latitude = location.getLatitude(); 
       longitude = location.getLongitude(); 
      } 

     } 
    }; 

    myLocation = new MyLocation(); 
    myLocation.getLocation(this, locationResult); 
    mapController = mapView.getController(); 
    point = new GeoPoint((int) (latitude * 1E6), (int) (longitude * 1E6)); 
    mapController.animateTo(point); 
    Toast.makeText(getApplicationContext(), ("Latitude = "+latitude+" Longitude = "+longitude), Toast.LENGTH_SHORT).show(); 
    mapController.setZoom(17); 
    mapView.invalidate(); 

纬度经度&宣布为全球双型的变量。但是,运行应用程序后,我得到了蓝屏。我认为,问题是我的代码没有能力获得经度的纬度值&。任何人都可以帮我吗?谢谢 。

回答

4

你的问题没有意识到你的代码有什么问题,但是如果你真的需要做的就是获得设备的当前位置,我可以给你一个提示。

提示:尝试使用位置监听器,如果设备位置发生变化,它会为您提供经纬度值。

代码:

你的活动

LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    LocationListener mlocListener = new MyLocationListener(); 
    mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener); 

监听器类

@Override 
     public void onLocationChanged(Location loc){ 
     //you are getting values 
     loc.getLatitude(); 
     loc.getLongitude(); 
     } 

清单许可

<uses-permission android:name="android.permission.ACCESS_GPS"></uses-permission> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 
+0

我想你忘了这permiss离子'<使用权限android:name =“android.permission.ACCESS_GPS”>' – Lucifer

+0

对不起,我已编辑答案。 –

+0

好吧,+1吧:) – Lucifer