Android百度地圖之搜索公交路線

jopen 12年前發布 | 45K 次閱讀 Android Android開發 移動開發

百度SDK提供了查詢公交路線的功能,并且可以瀏覽路線要經過的每一個站,百度Demo代碼如下:

Activity:

package com.home;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.MKMapTouchListener;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.mapapi.map.RouteOverlay;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPoiInfo;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKRoute;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKShareUrlResult;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;

/**
 * 此demo用來展示如何進行公交線路詳情檢索,并使用RouteOverlay在地圖上繪制 同時展示如何瀏覽路線節點并彈出泡泡
 * 
 */
public class BusLineSearchActivity extends Activity {
    // UI相關
    Button mBtnSearch = null;
    Button mBtnNextLine = null;
    // 瀏覽路線節點相關
    Button mBtnPre = null;// 上一個節點
    Button mBtnNext = null;// 下一個節點
    int nodeIndex = -2;// 節點索引,供瀏覽節點時使用
    MKRoute route = null;// 保存駕車/步行路線數據的變量,供瀏覽節點時使用
    private PopupOverlay pop = null;// 彈出泡泡圖層,瀏覽節點時使用
    private TextView popupText = null;// 泡泡view
    private View viewCache = null;
    private List<String> busLineIDList = null;
    int busLineIndex = 0;

    // 地圖相關,使用繼承MapView的MyBusLineMapView目的是重寫touch事件實現泡泡處理
    // 如果不處理touch事件,則無需繼承,直接使用MapView即可
    MapView mMapView = null; // 地圖View
    // 搜索相關
    MKSearch mSearch = null; // 搜索模塊,也可去掉地圖模塊獨立使用

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DemoApplication app = (DemoApplication) this.getApplication();

        setContentView(R.layout.activity_buslinesearch);
        CharSequence titleLable = "公交線路查詢功能";
        setTitle(titleLable);
        // 地圖初始化
        mMapView = (MapView) findViewById(R.id.bmapView);
        mMapView.getController().enableClick(true);
        mMapView.getController().setZoom(12);
        busLineIDList = new ArrayList<String>();
        // 創建 彈出泡泡圖層
        createPaopao();

        // 地圖點擊事件處理
        mMapView.regMapTouchListner(new MKMapTouchListener() {

            @Override
            public void onMapClick(GeoPoint point) {
                // 在此處理地圖點擊事件
                // 消隱pop
                if (pop != null) {
                    pop.hidePop();
                }
            }

            @Override
            public void onMapDoubleClick(GeoPoint point) {

            }

            @Override
            public void onMapLongClick(GeoPoint point) {

            }

        });

        // 初始化搜索模塊,注冊事件監聽
        mSearch = new MKSearch();
        mSearch.init(app.mBMapManager, new MKSearchListener() {

            @Override
            public void onGetPoiDetailSearchResult(int type, int error) {
            }

            public void onGetPoiResult(MKPoiResult res, int type, int error) {
                // 錯誤號可參考MKEvent中的定義
                if (error != 0 || res == null) {
                    Toast.makeText(BusLineSearchActivity.this, "抱歉,未找到結果",
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                // 找到公交路線poi node
                MKPoiInfo curPoi = null;
                int totalPoiNum = res.getCurrentNumPois();
                // 遍歷所有poi,找到類型為公交線路的poi
                busLineIDList.clear();
                for (int idx = 0; idx < totalPoiNum; idx++) {
                    if (2 == res.getPoi(idx).ePoiType) {
                        // poi類型,0:普通點,1:公交站,2:公交線路,3:地鐵站,4:地鐵線路
                        curPoi = res.getPoi(idx);
                        // 使用poi的uid發起公交詳情檢索
                        busLineIDList.add(curPoi.uid);
                        System.out.println(curPoi.uid);

                    }
                }
                SearchNextBusline();

                // 沒有找到公交信息
                if (curPoi == null) {
                    Toast.makeText(BusLineSearchActivity.this, "抱歉,未找到結果",
                            Toast.LENGTH_LONG).show();
                    return;
                }
                route = null;
            }

            public void onGetDrivingRouteResult(MKDrivingRouteResult res,
                    int error) {
            }

            public void onGetTransitRouteResult(MKTransitRouteResult res,
                    int error) {
            }

            public void onGetWalkingRouteResult(MKWalkingRouteResult res,
                    int error) {
            }

            public void onGetAddrResult(MKAddrInfo res, int error) {
            }

            /**
             * 獲取公交路線結果,展示公交線路
             */
            public void onGetBusDetailResult(MKBusLineResult result, int iError) {
                if (iError != 0 || result == null) {
                    Toast.makeText(BusLineSearchActivity.this, "抱歉,未找到結果",
                            Toast.LENGTH_LONG).show();
                    return;
                }

                RouteOverlay routeOverlay = new RouteOverlay(
                        BusLineSearchActivity.this, mMapView);
                // 此處僅展示一個方案作為示例
                routeOverlay.setData(result.getBusRoute());
                // 清除其他圖層
                mMapView.getOverlays().clear();
                // 添加路線圖層
                mMapView.getOverlays().add(routeOverlay);
                // 刷新地圖使生效
                mMapView.refresh();
                // 移動地圖到起點
                mMapView.getController().animateTo(
                        result.getBusRoute().getStart());
                // 將路線數據保存給全局變量
                route = result.getBusRoute();
                // 重置路線節點索引,節點瀏覽時使用
                nodeIndex = -1;
                mBtnPre.setVisibility(View.VISIBLE);
                mBtnNext.setVisibility(View.VISIBLE);
                Toast.makeText(BusLineSearchActivity.this, result.getBusName(),
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onGetSuggestionResult(MKSuggestionResult res, int arg1) {
            }

            @Override
            public void onGetShareUrlResult(MKShareUrlResult result, int type,
                    int error) {
            }

        });

        // 設定搜索按鈕的響應
        mBtnSearch = (Button) findViewById(R.id.search);
        mBtnNextLine = (Button) findViewById(R.id.nextline);
        mBtnPre = (Button) findViewById(R.id.pre);
        mBtnNext = (Button) findViewById(R.id.next);
        mBtnPre.setVisibility(View.INVISIBLE);
        mBtnNext.setVisibility(View.INVISIBLE);

        OnClickListener clickListener = new OnClickListener() {
            public void onClick(View v) {
                // 發起搜索
                SearchButtonProcess(v);
            }
        };
        OnClickListener nextLineClickListener = new OnClickListener() {
            public void onClick(View v) {
                // 搜索下一條公交線
                SearchNextBusline();
            }
        };
        OnClickListener nodeClickListener = new OnClickListener() {
            public void onClick(View v) {
                // 瀏覽路線節點
                nodeClick(v);
            }
        };
        mBtnSearch.setOnClickListener(clickListener);
        mBtnNextLine.setOnClickListener(nextLineClickListener);
        mBtnPre.setOnClickListener(nodeClickListener);
        mBtnNext.setOnClickListener(nodeClickListener);
    }

    /**
     * 發起檢索
     * 
     * @param v
     */
    void SearchButtonProcess(View v) {
        busLineIDList.clear();
        busLineIndex = 0;
        mBtnPre.setVisibility(View.INVISIBLE);
        mBtnNext.setVisibility(View.INVISIBLE);
        if (mBtnSearch.equals(v)) {
            EditText editCity = (EditText) findViewById(R.id.city);
            EditText editSearchKey = (EditText) findViewById(R.id.searchkey);
            // 發起poi檢索,從得到所有poi中找到公交線路類型的poi,再使用該poi的id進行公交詳情搜索
            mSearch.poiSearchInCity(editCity.getText().toString(),
                    editSearchKey.getText().toString());
        }

    }

    void SearchNextBusline() {
        if (busLineIndex >= busLineIDList.size()) {
            busLineIndex = 0;
        }
        if (busLineIndex >= 0 && busLineIndex < busLineIDList.size()
                && busLineIDList.size() > 0) {
            mSearch.busLineSearch(((EditText) findViewById(R.id.city))
                    .getText().toString(), busLineIDList.get(busLineIndex));
            busLineIndex++;
        }

    }

    /**
     * 創建彈出泡泡圖層
     */
    public void createPaopao() {
        viewCache = getLayoutInflater()
                .inflate(R.layout.custom_text_view, null);
        popupText = (TextView) viewCache.findViewById(R.id.textcache);
        // 泡泡點擊響應回調
        PopupClickListener popListener = new PopupClickListener() {
            @Override
            public void onClickedPopup(int index) {
                Log.v("click", "clickapoapo");
            }
        };
        pop = new PopupOverlay(mMapView, popListener);
    }

    /**
     * 節點瀏覽示例
     * 
     * @param v
     */
    public void nodeClick(View v) {

        if (nodeIndex < -1 || route == null || nodeIndex >= route.getNumSteps())
            return;
        viewCache = getLayoutInflater()
                .inflate(R.layout.custom_text_view, null);
        popupText = (TextView) viewCache.findViewById(R.id.textcache);
        // 上一個節點
        if (mBtnPre.equals(v) && nodeIndex > 0) {
            // 索引減
            nodeIndex--;
            // 移動到指定索引的坐標
            mMapView.getController().animateTo(
                    route.getStep(nodeIndex).getPoint());
            // 彈出泡泡
            popupText.setText(route.getStep(nodeIndex).getContent());
            popupText.setBackgroundResource(R.drawable.popup);
            pop.showPopup(BMapUtil.getBitmapFromView(popupText),
                    route.getStep(nodeIndex).getPoint(), 5);
        }
        // 下一個節點
        if (mBtnNext.equals(v) && nodeIndex < (route.getNumSteps() - 1)) {
            // 索引加
            nodeIndex++;
            // 移動到指定索引的坐標
            mMapView.getController().animateTo(
                    route.getStep(nodeIndex).getPoint());
            // 彈出泡泡
            popupText.setText(route.getStep(nodeIndex).getContent());
            popupText.setBackgroundDrawable(getResources().getDrawable(
                    R.drawable.popup));
            pop.showPopup(BMapUtil.getBitmapFromView(popupText),
                    route.getStep(nodeIndex).getPoint(), 5);
        }
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        mMapView.destroy();
        super.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mMapView.onRestoreInstanceState(savedInstanceState);
    }
}

布局XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="在" />

        <EditText
            android:id="@+id/city"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="北京" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="市內找" />

        <EditText
            android:id="@+id/searchkey"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="717" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="公交車" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/search"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="2dip"
                android:layout_marginRight="2dip"
                android:layout_weight="1"
                android:background="@drawable/button_style"
                android:text="開始" />

            <Button
                android:id="@+id/nextline"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="2dip"
                android:layout_marginRight="2dip"
                android:layout_weight="1"
                android:background="@drawable/button_style"
                android:text="下一條" />
        </LinearLayout>
    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <com.baidu.mapapi.map.MapView
            android:id="@+id/bmapView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clickable="true" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignWithParentIfMissing="false"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="false"
            android:layout_marginBottom="10dip" >

            <Button
                android:id="@+id/pre"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="2dip"
                android:layout_marginRight="2dip"
                android:layout_weight="1.0"
                android:background="@drawable/pre_" />

            <Button
                android:id="@+id/next"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="2dip"
                android:layout_marginRight="2dip"
                android:layout_weight="1.0"
                android:background="@drawable/next_" />
        </LinearLayout>
    </RelativeLayout>

</LinearLayout>

配置文件和Application類同上文

附上圖片效果:

d1.png

來自:http://blog.csdn.net/u010142437/article/details/11581555

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!