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

Android 高德地圖完整實戰:從顯示地圖到定位、標記與 POI 檢索

編輯:關於 Android 程式設計

要在 App 裡嵌入地圖、做定位與周邊搜尋,高德(AMap)SDK 是國內開發者的常見選擇。本文把接入高德地圖的核心步驟系統性地整理了一遍,從權限配置一路講到進階的傳感器羅盤效果。

配置資訊:AndroidManifest.xml

接入高德前,先在清單檔案裡聲明所需權限並填入你的 API Key:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />

<meta-data
    android:name="com.amap.api.v2.apikey"
    android:value="你的APIKEY" />

1. 基本地圖顯示

核心由兩部分組成:MapView 是承載地圖的容器,AMap 則負責地圖控制,包括顯示交通、定位圖層的開關與配置。使用時先初始化容器 MapView,再取得配置物件:

private void init() {
    if (aMap == null) {
        aMap = mapView.getMap();
    }
}

2. 顯示實時交通

aMap.setTrafficEnabled(true);

3. Location 定位功能

先設定當前位置的樣式:

private void setUpMap() {
    MyLocationStyle locationStyle = new MyLocationStyle();
    locationStyle.strokeColor(Color.BLACK);
    locationStyle.strokeWidth(1.0f);
    locationStyle.radiusFillColor(0x8333);
    locationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.location_marker));
    aMap.setMyLocationStyle(locationStyle); // 設置定位點樣式
    aMap.setLocationSource(this);           // 設置監聽
    aMap.setMyLocationEnabled(true);        // 啟動定位圖層
}

接著繼承 LocationSource,處理定位監聽的開始與結束:

@Override
public void activate(OnLocationChangedListener arg0) {
    mLocationChangedListener = arg0;
    if (mLocationManager == null) {
        mLocationManager = LocationManagerProxy.getInstance(this);
        // 每 2 秒更新一次,最後一個參數 AMapNetwork 是定位模式
        mLocationManager.requestLocationUpdates(LocationProviderProxy.AMapNetwork, 2000, 10, this);
    }
}

@Override
public void deactivate() {
    mLocationChangedListener = null;
    if (mLocationManager != null) {
        mLocationManager.removeUpdates(this);
        mLocationManager.destroy();
        mLocationManager = null;
    }
}

再繼承 AMapLocationListener,重點實作 onLocationChanged 來更新位置:

@Override
public void onLocationChanged(AMapLocation arg0) {
    if (mLocationChangedListener != null && arg0 != null) {
        mLocationChangedListener.onLocationChanged(arg0);
    }
}

4. 定位時即時轉向(羅盤效果)

系統默認的定位只是一個靜態圖標,並不含方向資訊。想要做出「跟著手機朝向旋轉」的效果,思路是:添加一個 Marker,再用方向傳感器即時修改它的旋轉角度。

先初始化傳感器:

mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);

初始化 Marker:

private void setUpMap() {
    mGPSMarker = aMap.addMarker(new MarkerOptions()
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.location_marker))
        .anchor(0.5f, 0.5f));
    aMap.setLocationSource(this);
    aMap.setMyLocationEnabled(true);
}

在啟動位置監聽時註冊傳感器,關閉時註銷:

@Override
public void activate(OnLocationChangedListener arg0) {
    // ...
    mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
}

@Override
public void deactivate() {
    // ...
    mSensorManager.unregisterListener(this, mSensor);
}

位置移動時更新 Marker 座標:

@Override
public void onLocationChanged(AMapLocation arg0) {
    if (mLocationChangedListener != null && arg0 != null) {
        mLocationChangedListener.onLocationChanged(arg0);
        mGPSMarker.setPosition(new LatLng(arg0.getLatitude(), arg0.getLongitude()));
    }
}

方向變化時更新 Marker 角度,這裡還需要換算螢幕旋轉角度:

@Override
public void onSensorChanged(SensorEvent event) {
    if (System.currentTimeMillis() - lastTime < TIME_SENSOR) {
        return;
    }
    switch (event.sensor.getType()) {
        case Sensor.TYPE_ORIENTATION: {
            float x = event.values[0];
            x += getScreenRotationOnPhone(this);
            x %= 360.0F;
            if (x > 180.0F) x -= 360.0F;
            else if (x < -180.0F) x += 360.0F;
            if (Math.abs(mAngle - 90 + x) < 3.0f) {
                break;
            }
            mAngle = x;
            if (mGPSMarker != null) {
                mGPSMarker.setRotateAngle(-mAngle);
                aMap.invalidate();
            }
            lastTime = System.currentTimeMillis();
        }
    }
}

/**
 * 獲取當前螢幕旋轉角度
 * @return 0 表示直式; 90 表示左橫式; 180 表示反向直式; 270 表示右橫式
 */
public static int getScreenRotationOnPhone(Context context) {
    final Display display = ((WindowManager) context
        .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    switch (display.getRotation()) {
        case Surface.ROTATION_0:   return 0;
        case Surface.ROTATION_90:  return 90;
        case Surface.ROTATION_180: return 180;
        case Surface.ROTATION_270: return -90;
    }
    return 0;
}

5. 設置縮放與顯示位置

LatLngBounds bounds = new LatLngBounds.Builder()
    .include(new LatLng(22.117719, 112.323274))
    .include(new LatLng(22.117719, 114.323274))
    .include(new LatLng(24.117719, 112.323274))
    .include(new LatLng(24.117719, 114.323274))
    .build();
aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 10));
aMap.moveCamera(CameraUpdateFactory.zoomBy(8));
aMap.setOnMapLoadedListener(this); // 設置地圖顯示監聽器

6. 設置標記

ArrayList<BitmapDescriptor> icons = new ArrayList<BitmapDescriptor>();
icons.add(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
// ...
aMap.addMarker(new MarkerOptions()
    .icons(icons)                       // 顯示多圖片
    .period(2)                          // 變化週期
    .position(new LatLng(23.118674, 113.321614))
    .anchor(0.5f, 0.5f)                 // 錨點位置
    .title("fuliyinkai")                // 點擊顯示文字
).showInfoWindow();                     // 默認顯示
aMap.setInfoWindowAdapter(this);        // 點擊標記顯示自定義浮動 View

7. 設置圓形

aMap.addCircle(new CircleOptions()
    .center(new LatLng(23.118674, 113.321614))
    .fillColor(0x88888888)
    .strokeColor(Color.BLACK)
    .strokeWidth(5)
    .radius(400));

8. 周邊關鍵字查詢

文字提示查詢:

Inputtips inputtips = new Inputtips(this, new InputtipsListener() {
    @Override
    public void onGetInputtips(List<Tip> tips, int arg1) {
        tips.get(0).getName(); // 獲取匹配的單個資料名稱
    }
});
try {
    inputtips.requestInputtips(content, city);
} catch (AMapException e) {
    e.printStackTrace();
}

POI 檢索:

// 第一個參數是關鍵字,第二個是 POI 類型,第三個是檢索區域(空字串代表全國)
query = new PoiSearch.Query(keyWord, "", editCity.getText().toString());
query.setPageSize(10);          // 每頁最多返回多少條 poiitem
query.setPageNum(currentPage);  // 檢索第幾頁
poiSearch = new PoiSearch(this, query);
poiSearch.setOnPoiSearchListener(this); // 主要執行 onPoiSearched()
poiSearch.searchPOIAsyn();

@Override
public void onPoiSearched(PoiResult result, int rCode) {
    dismissProgressDialog(); // 隱藏對話框
    if (rCode == 0) {
        if (result != null && result.getQuery() != null) {
            if (result.getQuery().equals(query)) {
                poiResult = result;
                List<PoiItem> poiItems = poiResult.getPois();
                List<SuggestionCity> suggestionCities = poiResult.getSearchSuggestionCitys();
                if (poiItems != null && poiItems.size() > 0) {
                    aMap.clear();
                    PoiOverlay poiOverlay = new PoiOverlay(aMap, poiItems);
                    poiOverlay.removeFromMap();
                    poiOverlay.addToMap();
                    poiOverlay.zoomToSpan();
                } else if (suggestionCities != null && suggestionCities.size() > 0) {
                    showSuggestCity(suggestionCities);
                } else {
                    ToastUtil.show(PoiKeywordSearchActivity.this, R.string.no_result);
                }
            }
        } else {
            ToastUtil.show(PoiKeywordSearchActivity.this, R.string.no_result);
        }
    } else if (rCode == 27) {
        ToastUtil.show(PoiKeywordSearchActivity.this, R.string.error_network);
    } else if (rCode == 32) {
        ToastUtil.show(PoiKeywordSearchActivity.this, R.string.error_key);
    } else {
        ToastUtil.show(PoiKeywordSearchActivity.this, getString(R.string.error_other) + rCode);
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved