2014-12-24 67 views
2

我的代碼是在這裏:難道沒有wifi無法獲得座標嗎?

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    List<String> providers = lm.getProviders(false); 
    Location l = null; 

    for (int i=providers.size()-1; i>=0; i--) { 
      l = lm.getLastKnownLocation(providers.get(i)); 
      if (l != null) break; 
    } 

    double[] gps = new double[2]; 
    if (l != null) { 
      gps[0] = l.getLatitude(); 
      gps[1] = l.getLongitude(); 
    } 
    return gps; 

只得到協調,當我連接到互聯網。

+0

見:http://stackoverflow.com/questions/14499771/how-to-get-the-current-accurate-gps-coordinates-using-gps-provider-in-android –

回答

0

可以使用Android GPS服務來獲取Longitute和Latitute也

添加的權限在AndroidMenifest.xml

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

初始化,

// saving the context for later use 
    private final Context mContext; 

    // if GPS is enabled 
    boolean isGPSEnabled = false; 

    // Location and co-ordinates coordinates 
    Location mLocation; 
    double mLatitude; 
    double mLongitude; 

    // Minimum time fluctuation for next update (in milliseconds) 
    private static final long TIME = 30000; 
    // Minimum distance fluctuation for next update (in meters) 
    private static final long DISTANCE = 20; 

    // Declaring a Location Manager 
    protected LocationManager mLocationManager; 

    // This is constructor to get System Location services, 
    public GPSService(Context context) { 
     this.mContext = context; 
     mLocationManager = (LocationManager) mContext 
       .getSystemService(LOCATION_SERVICE); 

    } 

察看GPS管理,以獲取數據,

try { 

      // Getting GPS status 
      isGPSEnabled = mLocationManager 
        .isProviderEnabled(LocationManager.GPS_PROVIDER); 

      // If GPS enabled, get latitude/longitude using GPS Services 
      if (isGPSEnabled) { 
       mLocationManager.requestLocationUpdates(
         LocationManager.GPS_PROVIDER, TIME, DISTANCE, this); 
       if (mLocationManager != null) { 
        mLocation = mLocationManager 
          .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
        if (mLocation != null) { 
         mLatitude = mLocation.getLatitude(); 
         mLongitude = mLocation.getLongitude(); 
        } 
       } 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     }