2013-01-24 121 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