2013-01-24 146 views
1

我正在使用適用於Android v2的Google地圖。我想顯示當前的用戶位置並放大。 這裏是在FragmentActivity代碼:放大顯示當前用戶位置

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.map_activity); 

    mMap = ((SupportMapFragment) getSupportFragmentManager() 
      .findFragmentById(R.id.mapFragment_mapActivity)).getMap(); 
    if (mMap == null) { 
     Toast.makeText(this, R.string.mapCreationProblem, Toast.LENGTH_LONG) 
       .show(); 
     finish(); 
     return; 
    } 
    mMap.setMyLocationEnabled(true); 
    Location currentLocation = mMap.getMyLocation(); 
    if(currentLocation!=null){ 
     LatLng currentCoordinates = new LatLng(
          currentLocation.getLatitude(), 
          currentLocation.getLongitude()); 
     mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentCoordinates, 10)); 
    } 
} 

地圖工作正常,並就當前位置作品的藍點。但似乎currentLocation始終爲空。所以我無法放大當前位置。

任何人知道爲什麼,請嗎?

回答

8

這裏是getMyLocation與尋找的人的位置額外保護()的實現。我只是在管理地圖片段的活動中有這個。

private Location getMyLocation() { 
    // Get location from GPS if it's available 
    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 

    // Location wasn't found, check the next most accurate place for the current location 
    if (myLocation == null) { 
     Criteria criteria = new Criteria(); 
     criteria.setAccuracy(Criteria.ACCURACY_COARSE); 
     // Finds a provider that matches the criteria 
     String provider = lm.getBestProvider(criteria, true); 
     // Use the provider to get the last known location 
     myLocation = lm.getLastKnownLocation(provider); 
    } 

    return myLocation; 
} 

感謝, DMAN

+0

非常感謝! –

+0

@DanieleVitali很高興能幫到你! – DMCApps

+0

仍然變爲空。但是我的當前位置顯示在地圖上 –

1

嘗試使用的LocationManager:

LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
Location currentLocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
+0

是的,我想過這個問題。但我想知道爲什麼getMyLocation()返回null。 –

+1

@DanieleVitali由這個http://stackoverflow.com/a/13830598/845038看起來已經有報道反對這個不斷返回null。位置經理似乎是你最好的選擇。我已經發布了getMyLocation()的實現,它與上面的基本相同,並具有輕微的故障保護功能。 – DMCApps