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

來源:互聯網
上載者:User

標籤:


上一篇- 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;        }    }    /**     * 此方法待驗證     * <p/>     * 給定座標點繪製出參考路線     *     * @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<DirectionsResponse>() {            @Override            public void onResponse(Response<DirectionsResponse> 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<Waypoint> into LatLng[]        List<Waypoint> 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;    }}


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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.