Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android地圖應用新視界--mapbox的常用功能封裝工具類

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

編輯:關於Android編程

上一篇-Android地圖應用新視界--mapbox的應用開發之初始集成篇-中介紹了全球應用的多平台地圖框架mapbox在Android端的集成步驟,

以及Android的地圖應用新視界--mapbox的應用開發之簡單功能提取篇,如果要了解建議先看前兩篇哦

此篇將延續上篇內容,主要提取常用功能封裝工具類,可以直接當工具類使用

直接上干貨

如下:


 

 

public class MapBoxUtils {
    private MapboxMap mapboxMap;
    private Context context;
    //調用mapboxAPI的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);
    }


    /**
     * 在指定位置繪制指定圖片
     *
     * @param latitude
     * @param longitude
     * @param drawableId 指定id的圖片
     */
    public void DrawMarker(final double latitude, final double longitude, int drawableId) {
        // Create an Icon object for the marker to use
        IconFactory iconFactory = IconFactory.getInstance(context);
        Drawable iconDrawable = ContextCompat.getDrawable(context, drawableId);
        Icon icon = iconFactory.fromDrawable(iconDrawable);

        // Add the custom icon marker to the map
        mapboxMap.addMarker(new MarkerOptions()
                .position(new LatLng(latitude, longitude))
                .icon(icon)).getPosition();

    }

    /**
     * 繪制簡單的默認標記
     *
     * @param latitude
     * @param longitude
     * @param title     標題
     * @param sinippet  說明
     */
    public void DrawSimpleMarker(final double latitude, final double longitude, String title, String sinippet) {

        // Add the custom icon marker to the map
        mapboxMap.addMarker(new MarkerOptions()
                .position(new LatLng(latitude, longitude))
                .title(title)
                .snippet(sinippet));

    }

    /**
     * 動畫跳轉到指定位置--指定方式
     *
     * @param latitude
     * @param longitude
     * @param zoom      指定變焦
     * @param bearing   指定相對原始旋轉角度
     * @param tilt      指定視角傾斜度
     */
    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)) // Sets the center of the map to the specified location
                .zoom(zoom)
                .bearing(bearing)
                .tilt(tilt)
                .build();

        //set the user's viewpoint as specified in the cameraPosition object
        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)) // Sets the center of the map to the specified location
                .zoom(11)
                .bearing(0)
                .tilt(0)
                .build();

        //set the user's viewpoint as specified in the cameraPosition object
        mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), 3000);
    }


    /**
     * 獲取token令牌
     *
     * @param context
     * @return
     */
    public static String getMapboxAccessToken(@NonNull Context context) {
        try {
            // Read out AndroidManifest
            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) {
            // Use fallback on string resource, used for development
            int tokenResId = context.getResources()
                    .getIdentifier("mapbox_access_token", "string", context.getPackageName());
            return tokenResId != 0 ? context.getString(tokenResId) : null;
        }
    }

    /**
     * 此方法待驗證
     * 

* 給定坐標點繪制出參考路線 * * @param point */ public void drawMyRoute(LatLng point) { //刪除所有之前的標記 mapboxMap.removeAnnotations(); // Set the origin waypoint to the devices location設置初始位置 Waypoint origin = new Waypoint(mapboxMap.getMyLocation().getLongitude(), mapboxMap.getMyLocation().getLatitude()); // 設置目的地路徑--點擊的位置點 Waypoint destination = new Waypoint(point.getLongitude(), point.getLatitude()); // Add marker to the destination waypoint mapboxMap.addMarker(new MarkerOptions() .position(new LatLng(point)) .title("目的地") .snippet("My destination")); // Get route from API 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) { // Print some info about the route currentRoute = response.body().getRoutes().get(0); showToastMessage(String.format("You are %d meters \nfrom your destination", currentRoute.getDistance())); // Draw the route on the map 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) { // Convert List into LatLng[] 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()); } // Draw Points on MapView mapboxMap.addPolyline(new PolylineOptions() .add(point) .color(Color.parseColor("#38afea")) .width(5)); } /** * 獲取地圖數據,參數1代表獲取當前中心點數據; 數據2 標示獲取矩形區域點數據 * * @param dataStyle * @return */ 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; } /** * 得到user_id * * @return */ private String getMyUseId() { String user_id = SpUtils.getInitialize(context).getValue("user_id", ""); return user_id; } /** * 獲取當前位置的坐標--經度,維度 * * @return */ public String getMyLocationLatLon() { String currentPoint = mapboxMap.getMyLocation().getLongitude() + "," + mapboxMap.getMyLocation().getLatitude(); return currentPoint; } /** * 獲取可見區域四角坐標所圍成的區域坐標--緯度,經度模式 * * @return */ 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; } /** * 得到設備號 * * @return */ public String device_id() { return Variables.device_id; } /** * 得到token令牌 * * @return */ public String token() { return Variables.device_id; } /** * //得到當前的時間,格式:15:30:30 * * @return */ private String getMyTime() { SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); Date curDate = new Date(System.currentTimeMillis());//獲取當前時間 String strTime = formatter.format(curDate); return strTime; } }



 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved