在上一章中,我们学习到了如何在地图中添加覆盖物,但是,一张地图上不可能就只有一个覆盖点,有可能根据需要,要添加多个覆盖点。下面,我们就来讲述一下如何在地图中添加多个覆盖物。
我们以标记山东省得三个市来举例子,首先准备好经纬度,济南市(36.665067,116.989145)、滨州市(37.381357,117.964824)、泰安市(36.200005,117.081552)。然后编写一个内部类class ItemizedOver extends ItemizedOverlay <OverlayItem>{}。这三个城市的坐标存储在数组中,这样可以减少我们Activity中得代码,给Activity减少一些负担。
我们贴出这个内部类ItemizedOver的代码:
class ItemizedOver extends ItemizedOverlay<OverlayItem>{ private List<OverlayItem> list = new ArrayList<OverlayItem>(); private double [] mLat = {37.381357,36.665067,36.200005}; private double [] mLon = {117.964824,116.989145,117.081552}; private String [] str = {"滨州市","济南市","泰安市"}; public ItemizedOver(Drawable arg0) { super(arg0); for(int i = 0;i<mLat.length;i++){ GeoPoint geoPoint = new GeoPoint((int)(mLat[i]*1E6),(int)( mLon[i]*1E6)); list.add(new OverlayItem(geoPoint, str[i], str[i])); } mapController.setCenter(new GeoPoint((int)(36.668322*1E6),(int)(117.0145103*1E6))); populate();//刷新地图 } @Override protected OverlayItem createItem(int arg0) { return list.get(arg0); } @Override public int size() { return list.size(); } @Override public boolean onTap(int i) { Toast.makeText(MainActivity.this, list.get(i).getSnippet(), 1).show(); return true; } }
其余的操作和前边的章节相同,如果你不想再重复书写,直接Ctrl+c和Ctrl+v就可以了。
为了方便大家学习,我在将OnCreate()代码贴出来:
public class MainActivity extends MapActivity { private MapView mapview; private BMapManager bMapManager; private String key="544FAA71566C13CF5A3535787F12CE73970F85EA"; private MapController mapController; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mapview = (MapView)this.findViewById(R.id.mapview); bMapManager = new BMapManager(this); bMapManager.init(key, new MKGeneralListener() { @Override public void onGetPermissionState(int arg0) { // TODO Auto-generated method stub if(arg0 == 300){ Toast.makeText(MainActivity.this, "您申请的key有错误!", Toast.LENGTH_LONG); } } @Override public void onGetNetworkState(int arg0) { } }); initMapActivity(bMapManager); mapview.setBuiltInZoomControls(true); mapController = mapview.getController(); mapController.setZoom(7); //设置缩放比例为7 Drawable drawable = getResources().getDrawable(R.drawable.iconmarka); mapview.getOverlays().add(new ItemizedOver(drawable)); }
接下来,就将程序最终的运行效果展示给大家: