Android地图应用新视界--mapbox的应用开发之简单功能提取篇

2024-06-01 08:08

本文主要是介绍Android地图应用新视界--mapbox的应用开发之简单功能提取篇,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

上一篇-Android地图应用新视界--mapbox的应用开发之初始集成篇-中介绍了全球应用的多平台地图框架mapbox在Android端的集成步骤,此篇将延续上篇内容,主要提取一些简单的常用方法,开发者可以藉此做简单开发


如下:


目前开发者账户公共令牌:
pk.eyJ1IjoiamFja3l6IiwiYSI6ImNpb2pxbzJrbjAxeWp2MW0zNXNpcDhscDIifQ.TbKXdF03rKa1RUvxeqiCTw
申请令牌:


在MapboxGLAndroidSDKTestApp的AndroidManifest.xml中设置
<meta-data
            android:name="com.mapbox.AccessToken"
            android:value="" />(将这个码“XXX”写入value中)
在res/values/developer-config.xml中按上述步骤设置AccessToken的值

获取token令牌
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;
}
}



mapbox 内置风格
  • Mapbox Streets我们的标志性风格。阅读博客文章以获得更多关于这种风格的移动具体考虑。
  • Emerald大交通和户外地形。了解更多有关数据源
  • Light and Dark轻型和深色风格,是伟大的数据覆盖。用他们日夜模式,底图明亮数据之上,而更多
  • Satellite and Satellite Streets最好看,最准确,最先进最新的卫星图像提供的任何地方。看看我们的博客了解最新信息,我们最先进的技术和数据。
  • Hybrid混合型 不显眼的标签,上面的卫星式的,便于寻路的道路。
  • 置换方式
    mapView.setStyle(Style.MAPBOX_STREETS);
    mapboxMap.setStyleUrl(Style.SATELLITE_STREETS);
    ---------------------------------------------------------------------------------------------
    下载mapbox-光栅v8.json,打开它,取代mapbox.streets你userid.mapid,并将其添加到您的应用程序的资产目录或文件上传到服务器
    这种技术可以加载任何自定义样式的JSON符合Mapbox GL样式规格
    mapView.setStyleUrl("https://www.mapbox.com/android-sdk/files/mapbox-raster-v8.json");




悬浮的button:
compile 'com.android.support:design:23.2.0'

<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_map" />


绘制一个标记
           
@Override
public void onMapReady(MapboxMap mapboxMap) {
mapboxMap.addMarker(new MarkerOptions()
.position(new LatLng(48.13863, 11.57603))
.title("Hello World!")
.snippet("Welcome to my marker."));
}

绘制自定义图片标记
(可以mapboxMap.addMarkers然后实现一大堆方法 待研究)
             
@Override
public void onMapReady(MapboxMap mapboxMap) {
// Create an Icon object for the marker to use
IconFactory iconFactory = IconFactory.getInstance(MainActivity.this);
Drawable iconDrawable = ContextCompat.getDrawable(MainActivity.this, R.drawable.purple_marker);
Icon icon = iconFactory.fromDrawable(iconDrawable);
// Add the custom icon marker to the map
mapboxMap.addMarker(new MarkerOptions()
.position(new LatLng(-33.8500000, 18.4158234))
.title("Cape Town Harbour")
.snippet("One of the busiest ports in South Africa")
.icon(icon));
}
});
参考样式:
(//mapbox:access_token="<your access token here>" mapbox:style_url="mapbox://styles/mapbox/outdoors-v9")
mapboxmao--ZOOM 变焦范围为0.0-21.0


在配置文件配置
           
mapbox:style_url="@string/style_light"
mapbox:center_latitude="39.885"
mapbox:center_longitude="116.679"
mapbox:zoom="12"//变焦
mapbox:tilt="20"//倾斜度                                                                                                              


设置动画/自定义地图边界包含poi兴趣点
           
// When user clicks the map, animate to new camera location
mapboxMap.setOnMapClickListener(new MapboxMap.OnMapClickListener() {
@Override
public void onMapClick(@NonNull LatLng point) {
                        CameraPosition position = new CameraPosition.Builder()
.target(new LatLng(51.50550, -0.07520)) // Sets the new camera position
.zoom(17) // Sets the zoom
.bearing(180) // Rotate the camera
.tilt(30) // Set the camera tilt
.build(); // Creates a CameraPosition from the builder
                        mapboxMap.animateCamera(CameraUpdateFactory
.newCameraPosition(position), 7000);
}
});


边界包含poi兴趣点/标记点
@Override
public void onMapReady(final MapboxMap mapboxMap) {
final Marker marker1 = mapboxMap.addMarker(new MarkerOptions().position(new LatLng(-36.848380, 174.762275)).title("Sky Tower"));
final Marker marker2 = mapboxMap.addMarker(new MarkerOptions().position(new LatLng(-36.847179, 174.777072)).title("Vector Arena"));
final Marker marker3 = mapboxMap.addMarker(new MarkerOptions().position(new LatLng(-36.801887, 175.108709)).title("Waiheke Island"));
final Marker marker4 = mapboxMap.addMarker(new MarkerOptions().position(new LatLng(-36.835059, 174.691237)).title("Waitemata Harbour"));
// When user clicks the map, animate to new camera location
mapboxMap.setOnMapClickListener(new MapboxMap.OnMapClickListener() {
@Override
public void onMapClick(@NonNull LatLng point) {
LatLngBounds latLngBounds = new LatLngBounds.Builder()
.include(marker1.getPosition())
.include(marker2.getPosition())
.include(marker3.getPosition())
.include(marker4.getPosition())
.build();
mapboxMap.moveCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, 50));
}
});
}

来源: https://www.mapbox.com/android-sdk/examples/animate-camera/



点击监听--设定地点地图跳转 
public void dosomething(final MapboxMap mapboxMap) {
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(41.327752, 19.818666)) // Sets the center of the map to the specified location
.zoom(13)                            // Sets the zoom level
.build();
//set the user's viewpoint as specified in the cameraPosition object
mapboxMap. moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
//Add a marker to the map in the specified location
mapboxMap.addMarker(new MarkerOptions()
.position(new LatLng(41.327752, 19.818666))
.title("MapBox Marker!")
.snippet("Welcome to my marker."));
}
});
}



绘制geojson线/画图形
new DrawGeoJSON().execute();
private class DrawGeoJSON extends AsyncTask<Void, Void, List<LatLng>> {
@Override
protected List<LatLng> doInBackground(Void... voids) {
ArrayList<LatLng> points = new ArrayList<>();
try {
// Load GeoJSON file
InputStream inputStream = getAssets().open("example.geojson");
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
inputStream.close();
// Parse JSON
JSONObject json = new JSONObject(sb.toString());
JSONArray features = json.getJSONArray("features");
JSONObject feature = features.getJSONObject(0);
JSONObject geometry = feature.getJSONObject("geometry");
if (geometry != null) {
String type = geometry.getString("type");
// Our GeoJSON only has one feature: a line string
if (!TextUtils.isEmpty(type) && type.equalsIgnoreCase("LineString")) {
// Get the Coordinates
JSONArray coords = geometry.getJSONArray("coordinates");
for (int lc = 0; lc < coords.length(); lc++) {
JSONArray coord = coords.getJSONArray(lc);
LatLng latLng = new LatLng(coord.getDouble(1), coord.getDouble(0));
points.add(latLng);
}
}
}
} catch (Exception e) {
Log.e(TAG, "Exception Loading GeoJSON: " + e.toString());
}
return points;
}
@Override
protected void onPostExecute(List<LatLng> points) {
super.onPostExecute(points);
if (points.size() > 0) {
LatLng[] pointsArray = points.toArray(new LatLng[points.size()]);
// Draw Points on MapView
mapboxMap.addPolyline(new PolylineOptions()
.add(pointsArray)
.color(Color.parseColor("#3bb2d0"))
.width(2));
}
}
}

画一个图形图层
private void drawPolygon(MapboxMap mapboxMap) {
List<LatLng> polygon = new ArrayList<>();
polygon.add(new LatLng(45.522585, -122.685699));
polygon.add(new LatLng(45.534611, -122.708873));
polygon.add(new LatLng(45.530883, -122.678833));
polygon.add(new LatLng(45.547115, -122.667503));
polygon.add(new LatLng(45.530643, -122.660121));
polygon.add(new LatLng(45.533529, -122.636260));
polygon.add(new LatLng(45.521743, -122.659091));
polygon.add(new LatLng(45.510677, -122.648792));
polygon.add(new LatLng(45.515008, -122.664070));
polygon.add(new LatLng(45.502496, -122.669048));
polygon.add(new LatLng(45.515369, -122.678489));
polygon.add(new LatLng(45.506346, -122.702007));
polygon.add(new LatLng(45.522585, -122.685699));
        mapboxMap.addPolygon(new PolygonOptions()
.addAll(polygon)
.fillColor(Color.parseColor("#3bb2d0")));
}


实现定位功能:
新版4.0.1定位实现
mapboxMap. setAccessToken(MAPBOX_ACCESS_TOKEN);
getMyLocationTest();


private void getMyLocationTest() {
mapboxMap.setMyLocationEnabled(true);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(mapboxMap.getMyLocation().getLatitude(), mapboxMap.getMyLocation().getLongitude())) // Sets the               center of the map to the specified location
.zoom(13)                            // Sets the zoom level
.build();
//set the user's viewpoint as specified in the cameraPosition object
mapboxMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}



private LocationManager locationManager;
public void getMyLocation() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// 获取所有可用的位置提供器
List<String> providerList = locationManager.getProviders(true);
String provider;
if (providerList.contains(LocationManager.GPS_PROVIDER)) {
provider = LocationManager.GPS_PROVIDER;
} else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {
provider = LocationManager.NETWORK_PROVIDER;
} else {
// 当没有可用的位置提供器时,弹出Toast提示用户
Toast.makeText(this, "No location provider to use",
Toast.LENGTH_SHORT).show();
return;
}
Log.e("location", provider);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
//    ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
//   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//                                          int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
// 显示当前设备的位置信息
showLocation(location);
}
locationManager.requestLocationUpdates(provider, 5000, 1, locationListener);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
if (locationManager != null) {
// 关闭程序时将监听器移除
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
//    ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
//   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//                                          int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.removeUpdates(locationListener);
}
}
LocationListener locationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle
extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(Location location) {
// 更新当前设备的位置信息
showLocation(location);
}
};
private void showLocation(Location location) {
String currentPosition = "latitude is " + location.getLatitude() + "\n"
+ "longitude is " + location.getLongitude();
Log.e("location",currentPosition);
}
在2014demo中:
private void myLocation(MapboxMap mapboxMap) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mapboxMap.setMyLocationEnabled(true);
//        mapboxMap.setMyLocationTrackingMode(MyLocationTracking.TRACKING_FOLLOW);//持续跟踪
mapboxMap.getMyLocation();
}



在地图中显示方向-绘制路线
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap mapboxMap) {
map = mapboxMap;
// Add origin and destination to the map
mapboxMap.addMarker(new MarkerOptions()
.position(new LatLng(origin.getLatitude(), origin.getLongitude()))
.title("Origin")
.snippet("Alhambra"));
mapboxMap.addMarker(new MarkerOptions()
.position(new LatLng(destination.getLatitude(), destination.getLongitude()))
.title("Destination")
.snippet("Plaza del Triunfo"));
// Get route from API
try {
getRoute(origin, destination);
} catch (ServicesException e) {
e.printStackTrace();
}
}
});


private void  getRoute(Position origin, Position destination) throws ServicesException {
MapboxDirections client = new MapboxDirections.Builder()
.setOrigin(origin)
.setDestination(destination)
.setProfile(DirectionsCriteria.PROFILE_CYCLING)
.setAccessToken("<your access token here>")
.build();
client.enqueueCall(new Callback<DirectionsResponse>() {
@Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
}
// Print some info about the route
currentRoute = response.body().getRoutes().get(0);
Log.d(TAG, "Distance: " + currentRoute.getDistance());
Toast.makeText(MainActivity.this, "Route is " +  currentRoute.getDistance() + " meters long.", Toast.LENGTH_SHORT).show();
// Draw the route on the map
drawRoute(currentRoute);
}
@Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
Log.e(TAG, "Error: " + t.getMessage());
Toast.makeText(MainActivity.this, "Error: " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void  drawRoute(DirectionsRoute route) {
// Convert LineString coordinates into LatLng[]
LineString lineString = LineString.fromPolyline(route.getGeometry(), Constants.OSRM_PRECISION_V5);
List<Position> coordinates = lineString.getCoordinates();
LatLng[] points = new LatLng[coordinates.size()];
for (int i = 0; i < coordinates.size(); i++) {
points[i] = new LatLng(
coordinates.get(i).getLatitude(),
coordinates.get(i).getLongitude());
}
// Draw Points on MapView
map.addPolyline(new PolylineOptions()
.add(points)
.color(Color.parseColor("#009688"))
.width(5));
}




长按绘制路线
private void longclick(final MapboxMap mapboxMap) {
mapboxMap.setOnMapLongClickListener(new MapboxMap.OnMapLongClickListener() {
@Override
public void onMapLongClick(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 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(this, 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));
}



地理位置搜索功能
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mas_geocoding);
// Set up the MapView
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap mapboxMap) {
map = mapboxMap;
}
});
// Set up autocomplete widget
GeocoderAutoCompleteView autocomplete = (GeocoderAutoCompleteView) findViewById(R.id.query);
autocomplete. setAccessToken( MapboxAccountManager.getInstance().getAccessToken());
autocomplete. setType(GeocodingCriteria.TYPE_POI);
autocomplete. setOnFeatureListener(new GeocoderAutoCompleteView.OnFeatureListener() {
@Override
public void  OnFeatureClick(GeocodingFeature feature) {
Position position = feature.asPosition();
updateMap(position.getLatitude(), position.getLongitude());
}
});
}
private void  updateMap(double latitude, double longitude) {
// Build marker
map.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title("Geocoder result"));
//跳转目的地界面
// Animate camera to geocoder result location
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude))
.zoom(15)
.build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), 5000, null);
}


下载静态地图
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mas_static_image);
ImageView imageView = (ImageView) findViewById(R.id.mapImage);
MapboxStaticImage staticImage;
try {
staticImage = new MapboxStaticImage.Builder()
.setAccessToken(MapboxAccountManager.getInstance().getAccessToken())
.setUsername(Constants.MAPBOX_USER)
.setStyleId(Constants.MAPBOX_STYLE_SATELLITE)
.setLon(12.3378) // Image center longitude
.setLat(45.4338) // Image center Latitude
.setZoom(13)
.setWidth(640) // Image width
.setHeight(360) // Image height
.setRetina(true) // Retina 2x image will be returned
.build();
new DownloadImageTask(imageView).execute(staticImage.getUrl().toString());
} catch (ServicesException e) {
Log.e(TAG, "MapboxStaticImage error: " + e.getMessage());
e.printStackTrace();
}
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView imageView;
public DownloadImageTask(ImageView imageView) {
this.imageView = imageView;
}
protected Bitmap doInBackground(String... urls) {
// Create OkHttp object
final OkHttpClient client = new OkHttpClient();
// Build request
Request request = new Request.Builder()
.url(urls[0])
.build();
Response response = null;
Bitmap bitmap = null;
try {
// Make request
response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
// If the response is successful,
// create the static map image
if (response.isSuccessful()) {
try {
bitmap = BitmapFactory.decodeStream(response.body().byteStream());
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
return bitmap;
}
protected void onPostExecute(Bitmap result) {
// Add static map image to imageView
imageView.setImageBitmap(result);
}
}

 
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_offline_simple);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
// Set up the OfflineManager
offlineManager = OfflineManager.getInstance(this);
offlineManager.setAccessToken(MapboxAccountManager.getInstance().getAccessToken());
// Create a bounding box for the offline region
LatLngBounds latLngBounds = new LatLngBounds.Builder()
.include(new LatLng(37.7897, -119.5073)) // Northeast
.include(new LatLng(37.6744, -119.6815)) // Southwest
.build();
// Define the offline region
OfflineTilePyramidRegionDefinition definition = new OfflineTilePyramidRegionDefinition(
mapView.getStyleUrl(),
latLngBounds,
10,
20,
this.getResources().getDisplayMetrics().density);
// Set the metadata
byte[] metadata;
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put(JSON_FIELD_REGION_NAME, "Yosemite National Park");
String json = jsonObject.toString();
metadata = json.getBytes(JSON_CHARSET);
} catch (Exception e) {
Log.e(TAG, "Failed to encode metadata: " + e.getMessage());
metadata = null;
}
// Create the region asynchronously
offlineManager.createOfflineRegion(definition, metadata, new OfflineManager.CreateOfflineRegionCallback() {
@Override
public void onCreate(OfflineRegion offlineRegion) {
offlineRegion.setDownloadState(OfflineRegion.STATE_ACTIVE);
// Display the download progress bar
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
startProgress();
// Monitor the download progress using setObserver
offlineRegion.setObserver(new OfflineRegion.OfflineRegionObserver() {
@Override
public void onStatusChanged(OfflineRegionStatus status) {
// Calculate the download percentage and update the progress bar
double percentage = status.getRequiredResourceCount() >= 0 ?
(100.0 * status.getCompletedResourceCount() / status.getRequiredResourceCount()) :
0.0;
if (status.isComplete()) {
// Download complete
endProgress("Region downloaded successfully.");
} else if (status.isRequiredResourceCountPrecise()) {
// Switch to determinate state
setPercentage((int) Math.round(percentage));
}
}
@Override
public void onError(OfflineRegionError error) {
// If an error occurs, print to logcat
Log.e(TAG, "onError reason: " + error.getReason());
Log.e(TAG, "onError message: " + error.getMessage());
}
@Override
public void mapboxTileCountLimitExceeded(long limit) {
// Notify if offline region exceeds maximum tile count
Log.e(TAG, "Mapbox tile count limit exceeded: " + limit);
}
});
}
@Override
public void onError(String error) {
Log.e(TAG, "Error: " + error);
}
});
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
offlineManager.listOfflineRegions(new OfflineManager.ListOfflineRegionsCallback() {
@Override
public void onList(OfflineRegion[] offlineRegions) {
// delete the last item in the offlineRegions list which will be yosemite offline map
offlineRegions[(offlineRegions.length - 1)].delete(new OfflineRegion.OfflineRegionDeleteCallback() {
@Override
public void onDelete() {
Toast.makeText(SimpleOfflineMapActivity.this, "Yosemite offline map deleted", Toast.LENGTH_LONG).show();
}
@Override
public void onError(String error) {
Log.e(TAG, "On Delete error: " + error);
}
});
}
@Override
public void onError(String error) {
Log.e(TAG, "onListError: " + error);
}
});
}




// Progress bar methods
private void startProgress() {
// Start and show the progress bar
isEndNotified = false;
progressBar.setIndeterminate(true);
progressBar.setVisibility(View.VISIBLE);
}
private void setPercentage(final int percentage) {
progressBar.setIndeterminate(false);
progressBar.setProgress(percentage);
}
private void endProgress(final String message) {
// Don't notify more than once
if (isEndNotified) return;
// Stop and hide the progress bar
isEndNotified = true;
progressBar.setIndeterminate(false);
progressBar.setVisibility(View.GONE);
// Show a toast
Toast.makeText(SimpleOfflineMapActivity.this, message, Toast.LENGTH_LONG).show();
}




目前开发者账户公共令牌:
pk.eyJ1IjoiamFja3l6IiwiYSI6ImNpb2pxbzJrbjAxeWp2MW0zNXNpcDhscDIifQ.TbKXdF03rKa1RUvxeqiCTw
申请令牌:
pk.eyJ1IjoiamFja3l6IiwiYSI6ImNpb2w3OTlmdDAwNzd1Z20weG42MjF5dmMifQ.775C4o6elT5la-uuMjJe4w


在MapboxGLAndroidSDKTestApp的AndroidManifest.xml中设置
<meta-data
            android:name="com.mapbox.AccessToken"
            android:value="" />(将这个码“XXX”写入value中)
在res/values/developer-config.xml中按上述步骤设置AccessToken的值

获取token令牌
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;
}
}



mapbox 内置风格
  • Mapbox Streets我们的标志性风格。阅读博客文章以获得更多关于这种风格的移动具体考虑。
  • Emerald大交通和户外地形。了解更多有关数据源
  • Light and Dark轻型和深色风格,是伟大的数据覆盖。用他们日夜模式,底图明亮数据之上,而更多
  • Satellite and Satellite Streets最好看,最准确,最先进最新的卫星图像提供的任何地方。看看我们的博客了解最新信息,我们最先进的技术和数据。
  • Hybrid混合型 不显眼的标签,上面的卫星式的,便于寻路的道路。
  • 置换方式
    mapView.setStyle(Style.MAPBOX_STREETS);
    mapboxMap.setStyleUrl(Style.SATELLITE_STREETS);
    ---------------------------------------------------------------------------------------------
    下载mapbox-光栅v8.json,打开它,取代mapbox.streets你userid.mapid,并将其添加到您的应用程序的资产目录或文件上传到服务器
    这种技术可以加载任何自定义样式的JSON符合Mapbox GL样式规格
    mapView.setStyleUrl("https://www.mapbox.com/android-sdk/files/mapbox-raster-v8.json");




悬浮的button:
compile 'com.android.support:design:23.2.0'

<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_map" />


绘制一个标记
         
@Override
public void onMapReady(MapboxMap mapboxMap) {
mapboxMap.addMarker(new MarkerOptions()
.position(new LatLng(48.13863, 11.57603))
.title("Hello World!")
.snippet("Welcome to my marker."));
}

绘制自定义图片标记
(可以mapboxMap.addMarkers然后实现一大堆方法 待研究)
           
@Override
public void onMapReady(MapboxMap mapboxMap) {
// Create an Icon object for the marker to use
IconFactory iconFactory = IconFactory.getInstance(MainActivity.this);
Drawable iconDrawable = ContextCompat.getDrawable(MainActivity.this, R.drawable.purple_marker);
Icon icon = iconFactory.fromDrawable(iconDrawable);
// Add the custom icon marker to the map
mapboxMap.addMarker(new MarkerOptions()
.position(new LatLng(-33.8500000, 18.4158234))
.title("Cape Town Harbour")
.snippet("One of the busiest ports in South Africa")
.icon(icon));
}
});
参考样式:
(//mapbox:access_token="<your access token here>" mapbox:style_url="mapbox://styles/mapbox/outdoors-v9")
mapboxmao--ZOOM 变焦范围为0.0-21.0


在配置文件配置
         
mapbox:style_url="@string/style_light"
mapbox:center_latitude="39.885"
mapbox:center_longitude="116.679"
mapbox:zoom="12"//变焦
mapbox:tilt="20"//倾斜度                                                                                                              


设置动画/自定义地图边界包含poi兴趣点
         
// When user clicks the map, animate to new camera location
mapboxMap.setOnMapClickListener(new MapboxMap.OnMapClickListener() {
@Override
public void onMapClick(@NonNull LatLng point) {
                        CameraPosition position = new CameraPosition.Builder()
.target(new LatLng(51.50550, -0.07520)) // Sets the new camera position
.zoom(17) // Sets the zoom
.bearing(180) // Rotate the camera
.tilt(30) // Set the camera tilt
.build(); // Creates a CameraPosition from the builder
                        mapboxMap.animateCamera(CameraUpdateFactory
.newCameraPosition(position), 7000);
}
});


边界包含poi兴趣点/标记点
@Override
public void onMapReady(final MapboxMap mapboxMap) {
final Marker marker1 = mapboxMap.addMarker(new MarkerOptions().position(new LatLng(-36.848380, 174.762275)).title("Sky Tower"));
final Marker marker2 = mapboxMap.addMarker(new MarkerOptions().position(new LatLng(-36.847179, 174.777072)).title("Vector Arena"));
final Marker marker3 = mapboxMap.addMarker(new MarkerOptions().position(new LatLng(-36.801887, 175.108709)).title("Waiheke Island"));
final Marker marker4 = mapboxMap.addMarker(new MarkerOptions().position(new LatLng(-36.835059, 174.691237)).title("Waitemata Harbour"));
// When user clicks the map, animate to new camera location
mapboxMap.setOnMapClickListener(new MapboxMap.OnMapClickListener() {
@Override
public void onMapClick(@NonNull LatLng point) {
LatLngBounds latLngBounds = new LatLngBounds.Builder()
.include(marker1.getPosition())
.include(marker2.getPosition())
.include(marker3.getPosition())
.include(marker4.getPosition())
.build();
mapboxMap.moveCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, 50));
}
});
}

来源: https://www.mapbox.com/android-sdk/examples/animate-camera/



点击监听--设定地点地图跳转 
public void dosomething(final MapboxMap mapboxMap) {
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(41.327752, 19.818666)) // Sets the center of the map to the specified location
.zoom(13)                            // Sets the zoom level
.build();
//set the user's viewpoint as specified in the cameraPosition object
mapboxMap. moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
//Add a marker to the map in the specified location
mapboxMap.addMarker(new MarkerOptions()
.position(new LatLng(41.327752, 19.818666))
.title("MapBox Marker!")
.snippet("Welcome to my marker."));
}
});
}



绘制geojson线/画图形
new DrawGeoJSON().execute();
private class DrawGeoJSON extends AsyncTask<Void, Void, List<LatLng>> {
@Override
protected List<LatLng> doInBackground(Void... voids) {
ArrayList<LatLng> points = new ArrayList<>();
try {
// Load GeoJSON file
InputStream inputStream = getAssets().open("example.geojson");
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
inputStream.close();
// Parse JSON
JSONObject json = new JSONObject(sb.toString());
JSONArray features = json.getJSONArray("features");
JSONObject feature = features.getJSONObject(0);
JSONObject geometry = feature.getJSONObject("geometry");
if (geometry != null) {
String type = geometry.getString("type");
// Our GeoJSON only has one feature: a line string
if (!TextUtils.isEmpty(type) && type.equalsIgnoreCase("LineString")) {
// Get the Coordinates
JSONArray coords = geometry.getJSONArray("coordinates");
for (int lc = 0; lc < coords.length(); lc++) {
JSONArray coord = coords.getJSONArray(lc);
LatLng latLng = new LatLng(coord.getDouble(1), coord.getDouble(0));
points.add(latLng);
}
}
}
} catch (Exception e) {
Log.e(TAG, "Exception Loading GeoJSON: " + e.toString());
}
return points;
}
@Override
protected void onPostExecute(List<LatLng> points) {
super.onPostExecute(points);
if (points.size() > 0) {
LatLng[] pointsArray = points.toArray(new LatLng[points.size()]);
// Draw Points on MapView
mapboxMap.addPolyline(new PolylineOptions()
.add(pointsArray)
.color(Color.parseColor("#3bb2d0"))
.width(2));
}
}
}

画一个图形图层
private void drawPolygon(MapboxMap mapboxMap) {
List<LatLng> polygon = new ArrayList<>();
polygon.add(new LatLng(45.522585, -122.685699));
polygon.add(new LatLng(45.534611, -122.708873));
polygon.add(new LatLng(45.530883, -122.678833));
polygon.add(new LatLng(45.547115, -122.667503));
polygon.add(new LatLng(45.530643, -122.660121));
polygon.add(new LatLng(45.533529, -122.636260));
polygon.add(new LatLng(45.521743, -122.659091));
polygon.add(new LatLng(45.510677, -122.648792));
polygon.add(new LatLng(45.515008, -122.664070));
polygon.add(new LatLng(45.502496, -122.669048));
polygon.add(new LatLng(45.515369, -122.678489));
polygon.add(new LatLng(45.506346, -122.702007));
polygon.add(new LatLng(45.522585, -122.685699));
        mapboxMap.addPolygon(new PolygonOptions()
.addAll(polygon)
.fillColor(Color.parseColor("#3bb2d0")));
}




 
 



 
 



 
 



 
 



 
 



 
 



 
 



 
 



 
 



 
 



 
 



 
 



 
 



 
 



 
 



 
 



 
 



 
 



 
 




实现定位功能:
新版4.0.1定位实现
mapboxMap. setAccessToken(MAPBOX_ACCESS_TOKEN);
getMyLocationTest();


private void getMyLocationTest() {
mapboxMap.setMyLocationEnabled(true);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(mapboxMap.getMyLocation().getLatitude(), mapboxMap.getMyLocation().getLongitude())) // Sets the               center of the map to the specified location
.zoom(13)                            // Sets the zoom level
.build();
//set the user's viewpoint as specified in the cameraPosition object
mapboxMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}



private LocationManager locationManager;
public void getMyLocation() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// 获取所有可用的位置提供器
List<String> providerList = locationManager.getProviders(true);
String provider;
if (providerList.contains(LocationManager.GPS_PROVIDER)) {
provider = LocationManager.GPS_PROVIDER;
} else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {
provider = LocationManager.NETWORK_PROVIDER;
} else {
// 当没有可用的位置提供器时,弹出Toast提示用户
Toast.makeText(this, "No location provider to use",
Toast.LENGTH_SHORT).show();
return;
}
Log.e("location", provider);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
//    ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
//   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//                                          int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
// 显示当前设备的位置信息
showLocation(location);
}
locationManager.requestLocationUpdates(provider, 5000, 1, locationListener);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
if (locationManager != null) {
// 关闭程序时将监听器移除
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
//    ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
//   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//                                          int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.removeUpdates(locationListener);
}
}
LocationListener locationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle
extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(Location location) {
// 更新当前设备的位置信息
showLocation(location);
}
};
private void showLocation(Location location) {
String currentPosition = "latitude is " + location.getLatitude() + "\n"
+ "longitude is " + location.getLongitude();
Log.e("location",currentPosition);
}
在2014demo中:
private void myLocation(MapboxMap mapboxMap) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mapboxMap.setMyLocationEnabled(true);
//        mapboxMap.setMyLocationTrackingMode(MyLocationTracking.TRACKING_FOLLOW);//持续跟踪
mapboxMap.getMyLocation();
}



在地图中显示方向-绘制路线
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap mapboxMap) {
map = mapboxMap;
// Add origin and destination to the map
mapboxMap.addMarker(new MarkerOptions()
.position(new LatLng(origin.getLatitude(), origin.getLongitude()))
.title("Origin")
.snippet("Alhambra"));
mapboxMap.addMarker(new MarkerOptions()
.position(new LatLng(destination.getLatitude(), destination.getLongitude()))
.title("Destination")
.snippet("Plaza del Triunfo"));
// Get route from API
try {
getRoute(origin, destination);
} catch (ServicesException e) {
e.printStackTrace();
}
}
});


private void  getRoute(Position origin, Position destination) throws ServicesException {
MapboxDirections client = new MapboxDirections.Builder()
.setOrigin(origin)
.setDestination(destination)
.setProfile(DirectionsCriteria.PROFILE_CYCLING)
.setAccessToken("<your access token here>")
.build();
client.enqueueCall(new Callback<DirectionsResponse>() {
@Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
}
// Print some info about the route
currentRoute = response.body().getRoutes().get(0);
Log.d(TAG, "Distance: " + currentRoute.getDistance());
Toast.makeText(MainActivity.this, "Route is " +  currentRoute.getDistance() + " meters long.", Toast.LENGTH_SHORT).show();
// Draw the route on the map
drawRoute(currentRoute);
}
@Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
Log.e(TAG, "Error: " + t.getMessage());
Toast.makeText(MainActivity.this, "Error: " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void  drawRoute(DirectionsRoute route) {
// Convert LineString coordinates into LatLng[]
LineString lineString = LineString.fromPolyline(route.getGeometry(), Constants.OSRM_PRECISION_V5);
List<Position> coordinates = lineString.getCoordinates();
LatLng[] points = new LatLng[coordinates.size()];
for (int i = 0; i < coordinates.size(); i++) {
points[i] = new LatLng(
coordinates.get(i).getLatitude(),
coordinates.get(i).getLongitude());
}
// Draw Points on MapView
map.addPolyline(new PolylineOptions()
.add(points)
.color(Color.parseColor("#009688"))
.width(5));
}




长按绘制路线
private void longclick(final MapboxMap mapboxMap) {
mapboxMap.setOnMapLongClickListener(new MapboxMap.OnMapLongClickListener() {
@Override
public void onMapLongClick(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 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(this, 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));
}



地理位置搜索功能
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mas_geocoding);
// Set up the MapView
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap mapboxMap) {
map = mapboxMap;
}
});
// Set up autocomplete widget
GeocoderAutoCompleteView autocomplete = (GeocoderAutoCompleteView) findViewById(R.id.query);
autocomplete. setAccessToken( MapboxAccountManager.getInstance().getAccessToken());
autocomplete. setType(GeocodingCriteria.TYPE_POI);
autocomplete. setOnFeatureListener(new GeocoderAutoCompleteView.OnFeatureListener() {
@Override
public void  OnFeatureClick(GeocodingFeature feature) {
Position position = feature.asPosition();
updateMap(position.getLatitude(), position.getLongitude());
}
});
}
private void  updateMap(double latitude, double longitude) {
// Build marker
map.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title("Geocoder result"));
//跳转目的地界面
// Animate camera to geocoder result location
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude))
.zoom(15)
.build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), 5000, null);
}


下载静态地图
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mas_static_image);
ImageView imageView = (ImageView) findViewById(R.id.mapImage);
MapboxStaticImage staticImage;
try {
staticImage = new MapboxStaticImage.Builder()
.setAccessToken(MapboxAccountManager.getInstance().getAccessToken())
.setUsername(Constants.MAPBOX_USER)
.setStyleId(Constants.MAPBOX_STYLE_SATELLITE)
.setLon(12.3378) // Image center longitude
.setLat(45.4338) // Image center Latitude
.setZoom(13)
.setWidth(640) // Image width
.setHeight(360) // Image height
.setRetina(true) // Retina 2x image will be returned
.build();
new DownloadImageTask(imageView).execute(staticImage.getUrl().toString());
} catch (ServicesException e) {
Log.e(TAG, "MapboxStaticImage error: " + e.getMessage());
e.printStackTrace();
}
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView imageView;
public DownloadImageTask(ImageView imageView) {
this.imageView = imageView;
}
protected Bitmap doInBackground(String... urls) {
// Create OkHttp object
final OkHttpClient client = new OkHttpClient();
// Build request
Request request = new Request.Builder()
.url(urls[0])
.build();
Response response = null;
Bitmap bitmap = null;
try {
// Make request
response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
// If the response is successful,
// create the static map image
if (response.isSuccessful()) {
try {
bitmap = BitmapFactory.decodeStream(response.body().byteStream());
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
return bitmap;
}
protected void onPostExecute(Bitmap result) {
// Add static map image to imageView
imageView.setImageBitmap(result);
}
}

 
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_offline_simple);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
// Set up the OfflineManager
offlineManager = OfflineManager.getInstance(this);
offlineManager.setAccessToken(MapboxAccountManager.getInstance().getAccessToken());
// Create a bounding box for the offline region
LatLngBounds latLngBounds = new LatLngBounds.Builder()
.include(new LatLng(37.7897, -119.5073)) // Northeast
.include(new LatLng(37.6744, -119.6815)) // Southwest
.build();
// Define the offline region
OfflineTilePyramidRegionDefinition definition = new OfflineTilePyramidRegionDefinition(
mapView.getStyleUrl(),
latLngBounds,
10,
20,
this.getResources().getDisplayMetrics().density);
// Set the metadata
byte[] metadata;
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put(JSON_FIELD_REGION_NAME, "Yosemite National Park");
String json = jsonObject.toString();
metadata = json.getBytes(JSON_CHARSET);
} catch (Exception e) {
Log.e(TAG, "Failed to encode metadata: " + e.getMessage());
metadata = null;
}
// Create the region asynchronously
offlineManager.createOfflineRegion(definition, metadata, new OfflineManager.CreateOfflineRegionCallback() {
@Override
public void onCreate(OfflineRegion offlineRegion) {
offlineRegion.setDownloadState(OfflineRegion.STATE_ACTIVE);
// Display the download progress bar
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
startProgress();
// Monitor the download progress using setObserver
offlineRegion.setObserver(new OfflineRegion.OfflineRegionObserver() {
@Override
public void onStatusChanged(OfflineRegionStatus status) {
// Calculate the download percentage and update the progress bar
double percentage = status.getRequiredResourceCount() >= 0 ?
(100.0 * status.getCompletedResourceCount() / status.getRequiredResourceCount()) :
0.0;
if (status.isComplete()) {
// Download complete
endProgress("Region downloaded successfully.");
} else if (status.isRequiredResourceCountPrecise()) {
// Switch to determinate state
setPercentage((int) Math.round(percentage));
}
}
@Override
public void onError(OfflineRegionError error) {
// If an error occurs, print to logcat
Log.e(TAG, "onError reason: " + error.getReason());
Log.e(TAG, "onError message: " + error.getMessage());
}
@Override
public void mapboxTileCountLimitExceeded(long limit) {
// Notify if offline region exceeds maximum tile count
Log.e(TAG, "Mapbox tile count limit exceeded: " + limit);
}
});
}
@Override
public void onError(String error) {
Log.e(TAG, "Error: " + error);
}
});
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
offlineManager.listOfflineRegions(new OfflineManager.ListOfflineRegionsCallback() {
@Override
public void onList(OfflineRegion[] offlineRegions) {
// delete the last item in the offlineRegions list which will be yosemite offline map
offlineRegions[(offlineRegions.length - 1)].delete(new OfflineRegion.OfflineRegionDeleteCallback() {
@Override
public void onDelete() {
Toast.makeText(SimpleOfflineMapActivity.this, "Yosemite offline map deleted", Toast.LENGTH_LONG).show();
}
@Override
public void onError(String error) {
Log.e(TAG, "On Delete error: " + error);
}
});
}
@Override
public void onError(String error) {
Log.e(TAG, "onListError: " + error);
}
});
}




// Progress bar methods
private void startProgress() {
// Start and show the progress bar
isEndNotified = false;
progressBar.setIndeterminate(true);
progressBar.setVisibility(View.VISIBLE);
}
private void setPercentage(final int percentage) {
progressBar.setIndeterminate(false);
progressBar.setProgress(percentage);
}
private void endProgress(final String message) {
// Don't notify more than once
if (isEndNotified) return;
// Stop and hide the progress bar
isEndNotified = true;
progressBar.setIndeterminate(false);
progressBar.setVisibility(View.GONE);
// Show a toast
Toast.makeText(SimpleOfflineMapActivity.this, message, Toast.LENGTH_LONG).show();
}

这篇关于Android地图应用新视界--mapbox的应用开发之简单功能提取篇的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1020447

相关文章

Java中Springboot集成Kafka实现消息发送和接收功能

《Java中Springboot集成Kafka实现消息发送和接收功能》Kafka是一个高吞吐量的分布式发布-订阅消息系统,主要用于处理大规模数据流,它由生产者、消费者、主题、分区和代理等组件构成,Ka... 目录一、Kafka 简介二、Kafka 功能三、POM依赖四、配置文件五、生产者六、消费者一、Kaf

利用Python编写一个简单的聊天机器人

《利用Python编写一个简单的聊天机器人》这篇文章主要为大家详细介绍了如何利用Python编写一个简单的聊天机器人,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 使用 python 编写一个简单的聊天机器人可以从最基础的逻辑开始,然后逐步加入更复杂的功能。这里我们将先实现一个简单的

基于Python开发电脑定时关机工具

《基于Python开发电脑定时关机工具》这篇文章主要为大家详细介绍了如何基于Python开发一个电脑定时关机工具,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 简介2. 运行效果3. 相关源码1. 简介这个程序就像一个“忠实的管家”,帮你按时关掉电脑,而且全程不需要你多做

Go语言实现将中文转化为拼音功能

《Go语言实现将中文转化为拼音功能》这篇文章主要为大家详细介绍了Go语言中如何实现将中文转化为拼音功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 有这么一个需求:新用户入职 创建一系列账号比较麻烦,打算通过接口传入姓名进行初始化。想把姓名转化成拼音。因为有些账号即需要中文也需要英

基于WinForm+Halcon实现图像缩放与交互功能

《基于WinForm+Halcon实现图像缩放与交互功能》本文主要讲述在WinForm中结合Halcon实现图像缩放、平移及实时显示灰度值等交互功能,包括初始化窗口的不同方式,以及通过特定事件添加相应... 目录前言初始化窗口添加图像缩放功能添加图像平移功能添加实时显示灰度值功能示例代码总结最后前言本文将

Java后端接口中提取请求头中的Cookie和Token的方法

《Java后端接口中提取请求头中的Cookie和Token的方法》在现代Web开发中,HTTP请求头(Header)是客户端与服务器之间传递信息的重要方式之一,本文将详细介绍如何在Java后端(以Sp... 目录引言1. 背景1.1 什么是 HTTP 请求头?1.2 为什么需要提取请求头?2. 使用 Spr

Java中的Opencv简介与开发环境部署方法

《Java中的Opencv简介与开发环境部署方法》OpenCV是一个开源的计算机视觉和图像处理库,提供了丰富的图像处理算法和工具,它支持多种图像处理和计算机视觉算法,可以用于物体识别与跟踪、图像分割与... 目录1.Opencv简介Opencv的应用2.Java使用OpenCV进行图像操作opencv安装j

将Python应用部署到生产环境的小技巧分享

《将Python应用部署到生产环境的小技巧分享》文章主要讲述了在将Python应用程序部署到生产环境之前,需要进行的准备工作和最佳实践,包括心态调整、代码审查、测试覆盖率提升、配置文件优化、日志记录完... 目录部署前夜:从开发到生产的心理准备与检查清单环境搭建:打造稳固的应用运行平台自动化流水线:让部署像

使用IntelliJ IDEA创建简单的Java Web项目完整步骤

《使用IntelliJIDEA创建简单的JavaWeb项目完整步骤》:本文主要介绍如何使用IntelliJIDEA创建一个简单的JavaWeb项目,实现登录、注册和查看用户列表功能,使用Se... 目录前置准备项目功能实现步骤1. 创建项目2. 配置 Tomcat3. 项目文件结构4. 创建数据库和表5.

使用PyQt5编写一个简单的取色器

《使用PyQt5编写一个简单的取色器》:本文主要介绍PyQt5搭建的一个取色器,一共写了两款应用,一款使用快捷键捕获鼠标附近图像的RGB和16进制颜色编码,一款跟随鼠标刷新图像的RGB和16... 目录取色器1取色器2PyQt5搭建的一个取色器,一共写了两款应用,一款使用快捷键捕获鼠标附近图像的RGB和16