百度地图SDK for Android【Demo自定义图层】
今天将和大家分享的是如何构建自定义图层并显示自定义的覆盖物。
首先,我们要构建一个最基本的地图应用,具体介绍请参考:百度地图SDK for Android【Demo地图展示】
在此基础之上,我们对工程文件做一定的修改。
第一步,修改布局文件,添加button控件,用于控制添加自定义覆盖物。代码如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <!-- 放入百度地图的mapview --> <com.baidu.mapapi.map.MapView android:id="@+id/bmapsView"android:layout_width="fill_parent"android:layout_height="fill_parent"android:clickable="true"/> <!-- 添加按钮 --> <Button android:id="@+id/button1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:text="《添加自定义覆盖物》" /></RelativeLayout>
第二步,定义继承自ItemizedOverlay<OverlayItem>的自定义图层。代码如下:
public class MyOverLay extends ItemizedOverlay<OverlayItem> {private List<OverlayItem> GeoList = new ArrayList<OverlayItem>();private Context mContext;private double mLat1 = 39.90923;//39.9022; // point1纬度private double mLon1 = 116.397428;//116.3822; // point1经度private double mLat2 = 39.9022;private double mLon2 = 116.3922;private double mLat3 = 39.917723;private double mLon3 = 116.3722;public MyOverLay(Drawable marker, Context context){super(marker);this.mContext= context;// 用给定的经纬度构造GeoPoint,单位是微度 (度 * 1E6)GeoPoint p1 = new GeoPoint((int)(mLat1 * 1E6), (int)(mLon1 * 1E6));GeoPoint p2 = new GeoPoint((int)(mLat2 * 1E6), (int)(mLon2 * 1E6));GeoPoint p3 = new GeoPoint((int)(mLat3 * 1E6), (int)(mLon3 * 1E6));GeoList.add(new OverlayItem(p1, "P1", "point1"));GeoList.add(new OverlayItem(p2, "P2", "point2"));GeoList.add(new OverlayItem(p3, "P3", "point3"));populate();//createItem(int)方法构造item。一旦有了数据,在调用其它方法前,首先调用这个方法}@Overrideprotected OverlayItem createItem(int i){return GeoList.get(i);}@Overridepublic int size(){return GeoList.size();}@Override// 处理当点击事件protected boolean onTap(int i){Toast.makeText(this.mContext, GeoList.get(i).getSnippet(), Toast.LENGTH_SHORT).show();return true;}}第三步,在主类中定义并初始化button控件,设置相应的点击事件。代码如下:
// 初始化button并设置点击操作事件button = (Button) findViewById(R.id.button1);button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubDrawable marker =getResources().getDrawable(R.drawable.ic_launcher);mapView.getOverlays().add(new MyOverLay(marker, MainActivity.this));mapView.refresh(); }});第四步,运行,显示结果如下:

点击下载原工程文件。