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

Android 地圖應用新視界:mapbox 常用功能封裝工具類

編輯:關於 Android 程式設計

在前面的「初始集成篇」中,我們介紹了跨平台的全球地圖框架 mapbox 在 Android 端的集成步驟;在「簡單功能提取篇」中,則示範了基礎功能的使用。本篇將延續前兩篇,把常用功能進一步封裝成工具類,讓你可以直接拿去使用。

直接上乾貨,如下:

 public class MapBoxUtils { private MapboxMap mapboxMap; private Context context; // 呼叫 mapbox API 的 token 令牌 public static String MAPBOX_ACCESS_TOKEN = "pk.eyJ1IjoiamFja3l6IiwiYSI6ImNpb2w3OTlmdDAwNzd1Z20weG42MjF5dmMifQ.775C4o6elT5la-uuMjJe4w"; public MapBoxUtils() { } public MapBoxUtils(MapboxMap mapboxMap, Context context) { this.mapboxMap = mapboxMap; this.context = context; mapboxMap.setAccessToken(MAPBOX_ACCESS_TOKEN); } /** 在指定位置繪製指定圖片 */ public void DrawMarker(final double latitude, final double longitude, int drawableId) { IconFactory iconFactory = IconFactory.getInstance(context); Drawable iconDrawable = ContextCompat.getDrawable(context, drawableId); Icon icon = iconFactory.fromDrawable(iconDrawable); mapboxMap.addMarker(new MarkerOptions() .position(new LatLng(latitude, longitude)) .icon(icon)).getPosition(); } /** 繪製簡單的預設標記 */ public void DrawSimpleMarker(final double latitude, final double longitude, String title, String sinippet) { mapboxMap.addMarker(new MarkerOptions() .position(new LatLng(latitude, longitude)) .title(title) .snippet(sinippet)); } /** 動畫跳轉到指定位置——指定方式 */ public void jumpToLocation(final double latitude, final double longitude, final double zoom, final double bearing, final double tilt) { CameraPosition cameraPosition = new CameraPosition.Builder() .target(new LatLng(latitude, longitude)) .zoom(zoom) .bearing(bearing) .tilt(tilt) .build(); mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), 3000); } /** 動畫跳轉到指定位置——預設方式 */ public void jumpToLocationDefault(final double latitude, final double longitude) { CameraPosition cameraPosition = new CameraPosition.Builder() .target(new LatLng(latitude, longitude)) .zoom(11) .bearing(0) .tilt(0) .build(); mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), 3000); } /** 獲取 token 令牌 */ public static String getMapboxAccessToken(@NonNull Context context) { try { PackageManager packageManager = context.getPackageManager(); ApplicationInfo appInfo = packageManager .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA); String token = appInfo.metaData.getString(MapboxConstants.KEY_META_DATA_MANIFEST); if (token == null || token.isEmpty()) { throw new IllegalArgumentException(); } return token; } catch (Exception e) { int tokenResId = context.getResources() .getIdentifier("mapbox_access_token", "string", context.getPackageName()); return tokenResId != 0 ? context.getString(tokenResId) : null; } } /** 給定座標點繪製參考路線 */ public void drawMyRoute(LatLng point) { mapboxMap.removeAnnotations(); Waypoint origin = new Waypoint(mapboxMap.getMyLocation().getLongitude(), mapboxMap.getMyLocation().getLatitude()); Waypoint destination = new Waypoint(point.getLongitude(), point.getLatitude()); mapboxMap.addMarker(new MarkerOptions() .position(new LatLng(point)) .title("目的地") .snippet("My destination")); getRoute(origin, destination); } private DirectionsRoute currentRoute = null; private void getRoute(Waypoint origin, Waypoint destination) { MapboxDirections directions = new MapboxDirections.Builder() .setAccessToken(MAPBOX_ACCESS_TOKEN) .setOrigin(origin) .setDestination(destination) .setProfile(DirectionsCriteria.PROFILE_WALKING) .build(); directions.enqueue(new Callback() { @Override public void onResponse(Response response, Retrofit retrofit) { currentRoute = response.body().getRoutes().get(0); showToastMessage(String.format("You are %d meters \nfrom your destination", currentRoute.getDistance())); drawRoute(currentRoute); } @Override public void onFailure(Throwable t) { showToastMessage("Error: " + t.getMessage()); } }); } private void showToastMessage(String message) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } private void drawRoute(DirectionsRoute route) { List waypoints = route.getGeometry().getWaypoints(); LatLng[] point = new LatLng[waypoints.size()]; for (int i = 0; i < waypoints.size(); i++) { point[i] = new LatLng( waypoints.get(i).getLatitude(), waypoints.get(i).getLongitude()); } mapboxMap.addPolyline(new PolylineOptions() .add(point) .color(Color.parseColor("#38afea")) .width(5)); } /** 獲取地圖 POI 資料,dataStyle=1 取當前中心點,=2 取矩形區域 */ public String getPOIDataJson(int dataStyle) { String data = null; String poiUrl = Constants.POI_URL; String currentPoint = getMyLocationLatLon(); String areaCoordinates = getAreaCoordinates(); String layerStyle = "try|cate|shop|hotel|msg"; String smartRecommend = "1"; String currentTime = getMyTime(); String zoneOffset = "28800000"; int currenRowNumber = 100; int pageSize = 100; String user_id = getMyUseId(); if (dataStyle == 1) { data = "{currentPoint:" + currentPoint + ",layerStyle:" + layerStyle + ",smartRecommend:" + smartRecommend + ",currentTime:" + currentTime + ",zoneOffset:" + zoneOffset + ",currenRowNumber:" + currenRowNumber + ",pageSize:" + pageSize + ",user_id:" + user_id + "}"; } else if (dataStyle == 2) { data = "{areaCoordinates:" + areaCoordinates + ",layerStyle:" + layerStyle + ",smartRecommend:" + smartRecommend + ",currentTime:" + currentTime + ",zoneOffset:" + zoneOffset + ",currenRowNumber:" + currenRowNumber + ",pageSize:" + pageSize + ",user_id:" + user_id + "}"; } LogUtils.e("Tag", "請求地圖 poi 資料的 post_Json 是:\n" + data); return data; } private String getMyUseId() { String user_id = SpUtils.getInitialize(context).getValue("user_id", ""); return user_id; } /** 獲取當前位置座標——經度,維度 */ public String getMyLocationLatLon() { String currentPoint = mapboxMap.getMyLocation().getLongitude() + "," + mapboxMap.getMyLocation().getLatitude(); return currentPoint; } /** 獲取可見區域四角座標所圍成的區域 */ public String getAreaCoordinates() { VisibleRegion bounds = mapboxMap.getProjection().getVisibleRegion(); String topleft = bounds.farLeft.getLongitude() + "," + bounds.farLeft.getLatitude(); String topright = bounds.farRight.getLongitude() + "," + bounds.farRight.getLatitude(); String bottomleft = bounds.nearLeft.getLongitude() + "," + bounds.nearLeft.getLatitude(); String bottomright = bounds.nearRight.getLongitude() + "," + bounds.nearRight.getLatitude(); String areaCoordinates = topleft + "," + bottomleft + "," + bottomright + "," + topright + "," + topleft; return areaCoordinates; } public String device_id() { return Variables.device_id; } public String token() { return Variables.device_id; } /** 得到當前時間,格式:15:30:30 */ private String getMyTime() { SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); Date curDate = new Date(System.currentTimeMillis()); String strTime = formatter.format(curDate); return strTime; } }

這個工具類把地圖開發中最常用的操作都做了封裝,包括:

DrawMarker/DrawSimpleMarker:在指定座標繪製自訂或預設標記。

jumpToLocation/jumpToLocationDefault:以動畫方式將視角平滑移動到目標位置,可自訂縮放、旋轉角度與傾斜度。

getMapboxAccessToken:從 AndroidManifest 或字串資源中讀取 token,方便集中管理。

drawMyRoute/getRoute/drawRoute:以裝置當前位置為起點、點擊位置為終點,呼叫 Mapbox Directions API 取得步行路線並繪製於地圖上。

getPOIDataJson/getAreaCoordinates:組裝查詢地圖 POI 資料所需的 JSON,可選擇以當前中心點或可見矩形區域作為查詢範圍。

有了這層封裝,在實際專案中只要 new 一個 MapBoxUtils 物件,就能以最精簡的程式碼完成標記、定位、路線與資料請求等常見需求,大幅提升開發效率。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved