该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
package com.example.baidumaptest;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;
public class MainActivity extends Activity {
private MapView mapView;
private BaiduMap baiduMap;
private LocationManager locationManager;
private String provider;
private boolean isFirstLocate=true;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//调用SDKInitializer.initialize()方法进行初始化操作
//initialize()接收一个Context参数并传入,这里我们获取一个全局的Context参数并传入
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
//4qUkoS3wd1dpcqdoMIl6TeEz
mapView=(MapView) findViewById(R.id.map_view);
//它是地图的总控制器,有了BaiduMap就能设置地图的缩放级别以及将地图定位到某一个经纬度上
baiduMap=mapView.getMap();
locationManager=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
//获取可用的位置提供器 getProviders(true);
List 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(MainActivity.this, "No location provider to use", Toast.LENGTH_LONG).show();
return;
}
//将选好的位置提供器传入到getLastKnownLocation()就可以得到一个Location对象
Location location=locationManager.getLastKnownLocation(provider);
if(location!=null){
navigateTo(location);
}
locationManager.requestLocationUpdates(provider, 5000, 1, locationListener);
}
private void navigateTo(Location location) {
if(isFirstLocate){
//借助LatLng类让地图定位到某一个经纬度
LatLng ll=new LatLng(location.getLatitude(), location.getAltitude());
MapStatusUpdate update=MapStatusUpdateFactory.newLatLng(ll);
baiduMap.animateMapStatus(update);
//地图缩放级别取值的范围限定在3到19之间,值越大,地图显示的信息就越精细
update=MapStatusUpdateFactory.zoomTo(16f);
baiduMap.animateMapStatus(update);
isFirstLocate=false;
}
}
LocationListener locationListener=new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
public void onLocationChanged(Location location) {
//更新当前设备的信息
navigateTo(location);
}
};
protected void onResume() {
super.onResume();
mapView.onResume();
}
protected void onPause() {
super.onPause();
mapView.onPause();
}
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
if(locationManager != null){
//关闭程序时将监听移除
locationManager.removeUpdates(locationListener);
}
}
}