您的位置:首页 > 其它

安卓特色服务之定位服务(百度地图二)

2016-01-30 11:41 399 查看
这篇文章接着上一篇主要实现了自我定位的功能

下面直接粘贴上代码:

public class MainActivity extends ActionBarActivity {
private MapView mapView;
private BaiduMap baiduMap;
private LocationManager locationManager;
private String provider;
private boolean isFirstLocate=true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//在使用SDK各组件之前初始化context信息,传入ApplicationContext
//注意该方法要再setContentView方法之前实现
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.bmapView);
//BaiduMap类是地图的总控制器,调用mapView的getMap()方法就可以获取到BaiduMap
//的实例
baiduMap=mapView.getMap();
baiduMap.setMyLocationEnabled(true);
locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
//获得所有位置提供器
List<String> providerList=locationManager.getProviders(true);
if(providerList.contains(LocationManager.GPS_PROVIDER))
{
provider=LocationManager.GPS_PROVIDER;
}else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {
provider=LocationManager.NETWORK_PROVIDER;
}else {
Toast.makeText(this, "No location provider to use", Toast.LENGTH_SHORT).show();
return ;
}
Location location=locationManager.getLastKnownLocation(provider);
if(location!=null)
{
navigateTo(location);
}
locationManager.requestLocationUpdates(provider, 5000, 1, locationListener);
}
private void navigateTo(Location location)
{
if(isFirstLocate)
{
//存储经度纬度
LatLng ll=new LatLng(location.getLatitude(), location.getLongitude());
MapStatusUpdate update=MapStatusUpdateFactory.newLatLng(ll);

baiduMap.animateMapStatus(update);
//设置地图的缩放级别
update=MapStatusUpdateFactory.zoomTo(19f);
baiduMap.animateMapStatus(update);
isFirstLocate=false;
}
//设置我的位置
MyLocationData.Builder locationBuilder=new MyLocationData.Builder();
locationBuilder.latitude(location.getLatitude());
locationBuilder.longitude(location.getLongitude());
MyLocationData locationData =locationBuilder.build();
baiduMap.setMyLocationData(locationData);
}
LocationListener locationListener=new LocationListener() {

@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {

}

@Override
public void onProviderEnabled(String arg0) {

}

public void onProviderDisabled(String arg0) {

}

public void onLocationChanged(Location location) {
if(location!=null)
{
navigateTo(location);
}
}
};
protected void onDestroy() {
super.onDestroy();
baiduMap.setMyLocationEnabled(false);
//在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理
mapView.onDestroy();
//关闭程序时候将监听器移除
if(locationListener!=null)
{
locationManager.removeUpdates(locationListener);
}
}
@Override
protected void onResume() {
super.onResume();
//在activity执行onResume时执行mMapView. onResume (),实现地图生命周期管理
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
//在activity执行onPause时执行mMapView. onPause (),实现地图生命周期管理
mapView.onPause();
}
}
相关的配置文件以及控件的设置参看百度地图一
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: