上一篇- 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; } }