2011-08-13 55 views
0

我刚刚在我的应用程序中向用户显示了一张地图。我怎么能把用户的位置放在这张地图上?有点困惑这样做,所以任何帮助将不胜感激!还有:当我设置地图时,我不得不包括:MapView mapView =(MapView)findViewById(R.id.mapview); 为什么你必须包含这个,因为你没有:setContentView(R.layout.main);? - 听起来像一个白痴的问题,但它只是我想知道的事情!Android:在Google地图活动上设置用户位置

回答

0

下面是一个示例代码,可以完成这项工作。简要描述,您首先获得locationService以了解位置,然后使用Criteria API让系统根据您在Criteria中的设置选择最佳提供者,然后获得提供者,从提供者请求位置更新并实现LocationListener接口,获取缓存的最后位置打电话getLastKnownLocation但我不会对计数可能会导致过时的或无效的结果

 String contenxt = Context.LOCATION_SERVICE; 
     locationManager = (LocationManager) getSystemService(contenxt); 

     /* 
     * trying to get the best provider 
     * with given conditions 
     */ 
     Criteria criteria = new Criteria(); 
     criteria.setAccuracy(Criteria.ACCURACY_FINE); 
     criteria.setAltitudeRequired(false); 
     criteria.setCostAllowed(true); 
     criteria.setSpeedRequired(false); 
     criteria.setBearingRequired(false); 
     criteria.setPowerRequirement(Criteria.POWER_LOW); 

     String provider = locationManager.getBestProvider(criteria, true); 
     Log.d(GAL, provider); 

     locationManager.requestLocationUpdates(provider, 3000, 30, locationListener); 
     location = locationManager.getLastKnownLocation(provider); 

注意:不要忘记实现位置监听器

答案要注意:您不包括与findViewById(R.id的MapView。它已经包含在你的xml中,所以在你的布局中。你只是参考mapView使用内置的方法,如setZoom,animateTo等

1

我会建议使用MyLocationOverlay。这将获得用户的当前位置并通过蓝点显示在地图上。你可以用类似这样的方法来实现:

List<Overlay> overlays = mMaps.getOverlays(); 
overlays.clear(); 

MyLocationOverlay myLocOverlay = new MyLocationOverlay(this, mMaps); 
myLocOverlay.enableMyLocation(); 
overlays.add(myLocOverlay); 
myLocOverlay.runOnFirstFix(new Runnable() { public void run() { 
    mMaps.getController().animateTo(myLocOverlay.getMyLocation()); 
}});