创建地图
1. 显示地图
使用MapView渲染地图
在自己创建的activity_main.xml中添加代码
<com.baidu.mapapi.map.MapView
android:id="@+id/bmapView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:clickable="true" />
在MainActivity中添加代码
private MapView mMapView = null;
private BaiduMap mapManager;
……
//获取地图控件引用
mMapView = (MapView) findViewById(R.id.bmapView);
mapManager = mMapView.getMap();
2.切换地图类型
使用BaiduMap中setMapType()方法设置地图类型
MAP_TYPE_NORMAL 普通地图
MAP_TYPE_SATELLITE 卫星图
MAP_TYPE_NONE 空白地图
实时路况图允许在普通地图和卫星地图中叠加
MainActivity.java
·其中对于实时路况图的按钮使用了一个布尔型变量来记录其开关情况
package com.hurricanespace.hurricanespace;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapView;
public class MainActivity extends AppCompatActivity {
private MapView mMapView = null;
private BaiduMap mapManager;
private ImageButton normalbutton;
private ImageButton satellitebutton;
private ImageButton trafficbutton;
private boolean trafficOn = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//在使用SDK各组件之前初始化context信息,传入ApplicationContext
//注意该方法要再setContentView方法之前实现
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
//获取地图控件引用
mMapView = (MapView) findViewById(R.id.bmapView);
mapManager = mMapView.getMap();
mapManager.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
normalbutton = (ImageButton)findViewById(R.id.normalButton);
satellitebutton = (ImageButton)findViewById(R.id.satelliteButton);
trafficbutton = (ImageButton)findViewById(R.id.trafficButton);
findViewById(R.id.normalButton).setOnClickListener(onClickListener);
findViewById(R.id.satelliteButton).setOnClickListener(onClickListener);
findViewById(R.id.trafficButton).setOnClickListener(onClickListener);
}
@Override
protected void onDestroy() {
super.onDestroy();
//在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理
mMapView.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
//在activity执行onResume时执行mMapView. onResume (),实现地图生命周期管理
mMapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
//在activity执行onPause时执行mMapView. onPause (),实现地图生命周期管理
mMapView.onPause();
}
private View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.normalButton:
mapManager.setMapType(BaiduMap.MAP_TYPE_NORMAL);
break;
case R.id.satelliteButton:
mapManager.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
break;
case R.id.trafficButton:
if(trafficOn==false) {
trafficOn=true;
mapManager.setTrafficEnabled(true);
}else {
trafficOn=false;
mapManager.setTrafficEnabled(false);
}
break;
}
}
};
}