本文主要是介绍Android地图应用新视界--mapbox的应用开发之简单功能提取篇,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
上一篇-Android地图应用新视界--mapbox的应用开发之初始集成篇-中介绍了全球应用的多平台地图框架mapbox在Android端的集成步骤,此篇将延续上篇内容,主要提取一些简单的常用方法,开发者可以藉此做简单开发
如下:
目前开发者账户公共令牌: pk.eyJ1IjoiamFja3l6IiwiYSI6ImNpb2pxbzJrbjAxeWp2MW0zNXNpcDhscDIifQ.TbKXdF03rKa1RUvxeqiCTw 申请令牌: |
mapbox 内置风格 |
|
悬浮的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" /> |
绘制一个标记 |
|
在配置文件配置 |
|
设置动画/自定义地图边界包含poi兴趣点 |
来源: 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>> {
|
实现定位功能:
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)); }
|
地理位置搜索功能 |
@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 申请令牌: |
mapbox 内置风格 |
|
悬浮的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" /> |
绘制一个标记 |
|
在配置文件配置 |
|
设置动画/自定义地图边界包含poi兴趣点 |
来源: 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>> {
|
实现定位功能:
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)); }
|
地理位置搜索功能 |
@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的应用开发之简单功能提取篇的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!