Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

百度地圖 SDK 實戰:顯示定位、POI 檢索與測距測面積

編輯:關於 Android 程式設計

地圖顯示與定位

對任何一個地圖 SDK 來說,第一步都是把地圖畫出來,然後定位到當前城市。百度地圖與高德地圖在這一段的處理代碼幾乎如出一轍。以下以百度地圖為例:

// 以下主要是定位用到的代碼
private MapView mMapView;
private BaiduMap mMapLayer;
private LocationClient mLocClient;
private boolean isFirstLoc = true; // 是否首次定位

private void initLocation() {
    mMapView = (MapView) findViewById(R.id.bmapView);
    // 先隱藏地圖,定位到當前城市後再顯示
    mMapView.setVisibility(View.INVISIBLE);

    mMapLayer = mMapView.getMap();
    mMapLayer.setOnMapClickListener(this);

    // 開啟定位圖層
    mMapLayer.setMyLocationEnabled(true);

    mLocClient = new LocationClient(this);
    // 設置定位監聽器
    mLocClient.registerLocationListener(new MyLocationListenner());

    LocationClientOption option = new LocationClientOption();
    option.setOpenGps(true);          // 打開 GPS
    option.setCoorType("bd09ll");     // 設置坐標類型
    option.setScanSpan(1000);
    option.setIsNeedAddress(true);    // 設為 true 才能取得詳細地址資訊

    // 設置定位參數
    mLocClient.setLocOption(option);

    // 開始定位
    mLocClient.start();
    // 取得最近一次的位置
    // mLocClient.getLastKnownLocation();
}

public class MyLocationListenner implements BDLocationListener {
    @Override
    public void onReceiveLocation(BDLocation location) {
        // mapView 銷毀後不再處理新接收的位置
        if (location == null || mMapView == null) {
            Log.d(TAG, "location is null or mMapView is null");
            return;
        }

        m_latitude = location.getLatitude();
        m_longitude = location.getLongitude();

        String position = String.format("當前位置:%s|%s|%s|%s|%s|%s|%s",
                location.getProvince(), location.getCity(),
                location.getDistrict(), location.getStreet(),
                location.getStreetNumber(), location.getAddrStr(),
                location.getTime());
        loc_position.setText(position);

        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(location.getRadius())
                // 此處設置開發者獲取到的方向資訊,順時針 0-360
                .direction(100)
                .latitude(m_latitude)
                .longitude(m_longitude)
                .build();
        mMapLayer.setMyLocationData(locData);

        if (isFirstLoc) {
            isFirstLoc = false;
            LatLng ll = new LatLng(m_latitude, m_longitude);
            MapStatusUpdate update = MapStatusUpdateFactory.newLatLngZoom(ll, 14);
            mMapLayer.animateMapStatus(update);
            // 定位到當前城市後再顯示圖層
            mMapView.setVisibility(View.VISIBLE);
        }
    }

    public void onReceivePoi(BDLocation poiLocation) {
    }
}

POI 檢索

POI 是「Point of Interest」的縮寫,即地圖注點:在地圖上標註地點名稱、類別、經度、緯度等資訊。依關鍵字檢索並在地圖上呈現 POI 結果,是智能出行的基礎能力。

檢索結果示意:

以下是百度地圖進行 POI 檢索的程式碼:

// 以下主要是 POI 搜索用到的代碼
private PoiSearch mPoiSearch = null;
private SuggestionSearch mSuggestionSearch = null;
private AutoCompleteTextView mKey = null;
private EditText mScope = null;
private Button btn_search, btn_nextpage, btn_cleardata;
private ArrayAdapter sugAdapter = null;
private int load_Index = 0;

private void initMap() {
    mPoiSearch = PoiSearch.newInstance();
    mPoiSearch.setOnGetPoiSearchResultListener(this);

    mSuggestionSearch = SuggestionSearch.newInstance();
    mSuggestionSearch.setOnGetSuggestionResultListener(this);

    mScope = (EditText) findViewById(R.id.poi_city);
    mKey = (AutoCompleteTextView) findViewById(R.id.poi_searchkey);
    btn_search = (Button) findViewById(R.id.search);
    btn_nextpage = (Button) findViewById(R.id.map_next_data);
    btn_cleardata = (Button) findViewById(R.id.map_clear_data);

    btn_search.setOnClickListener(this);
    btn_nextpage.setOnClickListener(this);
    btn_cleardata.setOnClickListener(this);

    sugAdapter = new ArrayAdapter(this, R.layout.spinner_dropdown_item);
    mKey.setAdapter(sugAdapter);

    // 關鍵字變化時,動態更新建議列表
    mKey.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable arg0) {
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
            if (cs.length() <= 0) {
                return;
            }
            String city = mScope.getText().toString();
            // 使用建議搜索服務取得建議列表,結果在 onGetSuggestionResult 中更新
            mSuggestionSearch.requestSuggestion((new SuggestionSearchOption())
                    .keyword(cs.toString()).city(city));
        }
    });
}

@Override
public void onGetSuggestionResult(SuggestionResult res) {
    if (res == null || res.getAllSuggestions() == null) {
        return;
    } else {
        sugAdapter.clear();
        for (SuggestionResult.SuggestionInfo info : res.getAllSuggestions()) {
            if (info.key != null) {
                sugAdapter.add(info.key);
            }
        }
        sugAdapter.notifyDataSetChanged();
    }
}

// 搜索按鈕的點擊事件
public void searchButtonProcess(View v) {
    Log.d(TAG, "editCity=" + mScope.getText().toString()
            + ", editSearchKey=" + mKey.getText().toString()
            + ", load_Index=" + load_Index);

    String keyword = mKey.getText().toString();
    if (search_method == SEARCH_CITY) {
        String city = mScope.getText().toString();
        mPoiSearch.searchInCity((new PoiCitySearchOption()).city(city)
                .keyword(keyword).pageNum(load_Index));
    } else if (search_method == SEARCH_NEARBY) {
        LatLng position = new LatLng(m_latitude, m_longitude);
        int radius = Integer.parseInt(mScope.getText().toString());
        mPoiSearch.searchNearby((new PoiNearbySearchOption())
                .location(position).keyword(keyword).radius(radius)
                .pageNum(load_Index));
    }
}

public void goToNextPage(View v) {
    load_Index++;
    searchButtonProcess(null);
}

public void onGetPoiResult(PoiResult result) {
    if (result == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
        Toast.makeText(this, "未找到結果", Toast.LENGTH_LONG).show();
        return;
    } else if (result.error == SearchResult.ERRORNO.NO_ERROR) {
        mMapLayer.clear();
        PoiOverlay overlay = new MyPoiOverlay(mMapLayer);
        mMapLayer.setOnMarkerClickListener(overlay);
        List poiList = result.getAllPoi();
        overlay.setData(result);
        overlay.addToMap();
        overlay.zoomToSpan();
        // 也可以自行遍歷取欄位
        // for (PoiInfo poi : poiList) {
        //     String detail = String.format(
        //         "uid=%s, city=%s, name=%s, phone=%s, address=%s", poi.uid,
        //         poi.city, poi.name, poi.phoneNum, poi.address);
        //     Log.d(TAG, detail); // 坐標為 poi.location(LatLng 結構)
        // }
    } else if (result.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {
        // 本市沒找到、但在其他城市找到時,會回傳包含該關鍵字的城市列表
        String strInfo = "在";
        for (CityInfo cityInfo : result.getSuggestCityList()) {
            strInfo += cityInfo.city + ",";
        }
        strInfo += "找到結果";
        Toast.makeText(this, strInfo, Toast.LENGTH_LONG).show();
    }
}

public void onGetPoiDetailResult(PoiDetailResult result) {
    if (result.error != SearchResult.ERRORNO.NO_ERROR) {
        Toast.makeText(this, "抱歉,未找到結果", Toast.LENGTH_SHORT).show();
    } else {
        Log.d(TAG, "name=" + result.getName()
                + ", address=" + result.getAddress()
                + ", detail_url=" + result.getDetailUrl()
                + ", shop_hours=" + result.getShopHours()
                + ", telephone=" + result.getTelephone()
                + ", price=" + result.getPrice()
                + ", type=" + result.getType()
                + ", tag=" + result.getTag());
        Toast.makeText(this, result.getName() + ":" + result.getAddress(),
                Toast.LENGTH_SHORT).show();
    }
}

private class MyPoiOverlay extends PoiOverlay {
    public MyPoiOverlay(BaiduMap baiduMap) {
        super(baiduMap);
    }

    @Override
    public boolean onPoiClick(int index) {
        super.onPoiClick(index);
        PoiInfo poi = getPoiResult().getAllPoi().get(index);
        mPoiSearch.searchPoiDetail((new PoiDetailSearchOption()).poiUid(poi.uid));
        return true;
    }
}

測距與測面積

測量距離與面積是地圖 SDK 的另一類應用。除了在地圖上標註,本質上就是兩個數學公式。

測距用勾股定理(又名商高定理):直角三角形兩直角邊的平方和等於斜邊的平方。若兩直角邊為 a、b,斜邊為 c,則 a*a + b*b = c*c。

測面積用海倫公式(又名秦九韶公式):S = √p(p-a)(p-b)(p-c)。以此為基礎,可推出依多邊形各邊長求面積的公式:S = 0.5 * ((x0*y1 - x1*y0) + (x1*y2 - x2*y1) + ... + (xn*y0 - x0*yn))。

兩種 SDK 在測量上的數學原理相同,差異只在地圖標註的繪製方式。以下為測量效果示意:

以百度地圖為例的繪圖與測量程式碼:

// 下面是在地圖上添加繪圖操作
private static int lineColor = 0x55FF0000;
private static int arcColor = 0xbb00FFFF;
private static int textColor = 0x990000FF;
private static int polygonColor = 0x77FFFF00;
private static int radius = 100;

private ArrayList posArray = new ArrayList();
boolean is_polygon = false;

private void addDot(LatLng pos) {
    if (is_polygon == true && posArray.size() > 1
            && MapUtil.isInsidePolygon(pos, posArray) == true) {
        Log.d(TAG, "isInsidePolygon");
        LatLng centerPos = MapUtil.getCenterPos(posArray);
        OverlayOptions ooText = new TextOptions().bgColor(0x00ffffff)
                .fontSize(26).fontColor(textColor).text("標題")
                // .rotate(-30)
                .position(centerPos);
        mMapLayer.addOverlay(ooText);
        return;
    }

    if (is_polygon == true) {
        Log.d(TAG, "is_polygon==true");
        posArray.clear();
        is_polygon = false;
    }

    boolean is_first = false;
    LatLng thisPos = pos;

    if (posArray.size() > 0) {
        LatLng firstPos = posArray.get(0);
        int distance = (int) Math.round(MapUtil.getShortDistance(
                thisPos.longitude, thisPos.latitude,
                firstPos.longitude, firstPos.latitude));

        // 多次點擊起點要忽略
        if (posArray.size() == 1 && distance <= 0) {
            return;
        } else if (posArray.size() > 1) {
            LatLng lastPos = posArray.get(posArray.size() - 1);
            int lastDistance = (int) Math.round(MapUtil.getShortDistance(
                    thisPos.longitude, thisPos.latitude,
                    lastPos.longitude, lastPos.latitude));
            // 重複點擊當前位置也要忽略
            if (lastDistance <= 0) {
                return;
            }
        }

        if (distance radius = 100;  // 觸發首尾閉合,回到起點
            thisPos = firstPos;
            is_first = true;
        }

        Log.d(TAG, "distance=" + distance + ", radius=" + radius + ", is_first=" + is_first);

        // 畫直線
        LatLng lastPos = posArray.get(posArray.size() - 1);
        List points = new ArrayList();
        points.add(lastPos);
        points.add(thisPos);
        OverlayOptions ooPolyline = new PolylineOptions().width(2)
                .color(lineColor).points(points);
        mMapLayer.addOverlay(ooPolyline);

        // 計算兩點之間距離
        distance = (int) Math.round(MapUtil.getShortDistance(
                thisPos.longitude, thisPos.latitude,
                lastPos.longitude, lastPos.latitude));

        String disText = "";
        if (distance > 1000) {
            disText = Math.round(distance * 10 / 1000) / 10d + " 公裡";
        } else {
            disText = distance + " 米";
        }

        LatLng llText = new LatLng(
                (thisPos.latitude + lastPos.latitude) / 2,
                (thisPos.longitude + lastPos.longitude) / 2);
        OverlayOptions ooText = new TextOptions().bgColor(0x00ffffff)
                .fontSize(24).fontColor(textColor).text(disText)
                // .rotate(-30)
                .position(llText);
        mMapLayer.addOverlay(ooText);
    }

    if (is_first != true) {
        // 畫圓圈
        OverlayOptions ooCircle = new CircleOptions().fillColor(lineColor)
                .center(thisPos).stroke(new Stroke(2, 0xAAFF0000)).radius(radius);
        mMapLayer.addOverlay(ooCircle);

        // 畫圖片標記
        BitmapDescriptor bitmapDesc = BitmapDescriptorFactory.fromResource(R.drawable.icon_geo);
        OverlayOptions ooMarker = new MarkerOptions().draggable(false)
                .visible(true).icon(bitmapDesc).position(thisPos);
        mMapLayer.addOverlay(ooMarker);

        mMapLayer.setOnMarkerClickListener(new OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                LatLng markPos = marker.getPosition();
                addDot(markPos);
                return true;
            }
        });
    } else {
        Log.d(TAG, "posArray.size()=" + posArray.size());

        // 可能存在地圖與標記同時響應點擊的情況
        if (posArray.size() < 3) {
            posArray.clear();
            is_polygon = false;
            return;
        }

        // 畫多邊形
        OverlayOptions ooPolygon = new PolygonOptions().points(posArray)
                .stroke(new Stroke(1, 0xFF00FF00))
                .fillColor(polygonColor);
        mMapLayer.addOverlay(ooPolygon);
        is_polygon = true;

        // 計算多邊形面積
        LatLng centerPos = MapUtil.getCenterPos(posArray);
        double area = Math.round(MapUtil.getArea(posArray));

        String areaText = "";
        if (area > 1000000) {
            areaText = Math.round(area * 100 / 1000000) / 100d + " 平方公裡";
        } else {
            areaText = (int) area + " 平方米";
        }

        OverlayOptions ooText = new TextOptions().bgColor(0x00ffffff)
                .fontSize(26).fontColor(textColor).text(areaText)
                // .rotate(-30)
                .position(centerPos);
        mMapLayer.addOverlay(ooText);
    }

    posArray.add(thisPos);

    if (posArray.size() >= 3) {
        // 畫弧線
        OverlayOptions ooArc = new ArcOptions()
                .color(arcColor)
                .width(2)
                .points(posArray.get(posArray.size() - 1),
                        posArray.get(posArray.size() - 2),
                        posArray.get(posArray.size() - 3));
        mMapLayer.addOverlay(ooArc);
    }
}

@Override
public void onMapClick(LatLng arg0) {
    addDot(arg0);
}

@Override
public boolean onMapPoiClick(MapPoi arg0) {
    addDot(arg0.getPosition());
    return false;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved