Я создал пошаговое навигационное приложение, используя mapbox, и я хотел добавить его в строку поиска в приложении.Я прочитал форумы онлайн и узнал о плагине мест.Я добавил необходимые зависимости, но не уверен, как на самом деле добавить плагин в приложение.Я новичок и буду очень признателен за помощь / руководство своего рода.
Это то, что я сделал до сих пор.
Это моя основная деятельность:
package com.example.mapbox_with_search_bar;
import android.annotation.SuppressLint;
import android.location.Location;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.mapbox.android.core.location.LocationEngine;
import com.mapbox.android.core.location.LocationEngineListener;
import com.mapbox.android.core.location.LocationEnginePriority;
import com.mapbox.android.core.location.LocationEngineProvider;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerPlugin;
import com.mapbox.mapboxsdk.plugins.locationlayer.modes.CameraMode;
import com.mapbox.mapboxsdk.plugins.locationlayer.modes.RenderMode;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncher;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncherOptions;
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, LocationEngineListener, PermissionsListener, MapboxMap.OnMapClickListener
{
private MapView mapView;
private MapboxMap map;
private PermissionsManager permissionsManager;
private LocationEngine locationEngine;
private LocationLayerPlugin locationLayerPlugin;
private Location originLocation;
private Point originPosition;
private Point destinationPosition;
private DirectionsRoute currentRoute;
private Marker destinationMarker;
private LatLng originCoord;
private LatLng destinationCoord;
private static final String TAG = "MainActivity";
private NavigationMapRoute navigationMapRoute;
private Button startButton;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Mapbox.getInstance(this,getString(R.string.access_token));
setContentView(R.layout.activity_main);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
// MADE CHANGES HERE
@Override
public void onMapReady(MapboxMap mapboxMap)
{
this.map = mapboxMap;
enableLocationPlugin();
originCoord = new LatLng(originLocation.getLatitude(), originLocation.getLongitude());
map.addOnMapClickListener(this);
startButton = findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(currentRoute)
.shouldSimulateRoute(true)
.build();
NavigationLauncher.startNavigation(MainActivity.this, options);
}
});
}
private void enableLocationPlugin()
{
if (PermissionsManager.areLocationPermissionsGranted(this))
{
initializeLocationEngine();
locationLayerPlugin = new LocationLayerPlugin(mapView, map);
locationLayerPlugin.setLocationLayerEnabled(true);
locationLayerPlugin.setCameraMode(CameraMode.TRACKING);
getLifecycle().addObserver(locationLayerPlugin);
locationLayerPlugin.setRenderMode(RenderMode.NORMAL);
}
else
{
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
private void setCameraPosition(Location location)
{
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),location.getLongitude()),15.0));
}
@Override
public void onMapClick(@NonNull LatLng point)
{
if (destinationMarker != null)
{
map.removeMarker(destinationMarker);
}
destinationCoord = point;
destinationMarker = map.addMarker(new MarkerOptions()
.position(destinationCoord));
destinationPosition = Point.fromLngLat(destinationCoord.getLongitude(), destinationCoord.getLatitude());
originPosition = Point.fromLngLat(originCoord.getLongitude(), originCoord.getLatitude());
getRoute(originPosition, destinationPosition);
startButton.setEnabled(true);
startButton.setBackgroundResource(R.color.mapboxBlue);
}
private void getRoute(Point origin, Point destination)
{
NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(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;
}
else if (response.body().routes().size() < 1)
{
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
// Draw the route on the map
if (navigationMapRoute != null)
{
navigationMapRoute.removeRoute();
}
else
{
navigationMapRoute = new NavigationMapRoute(null, mapView, map, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
@Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable)
{
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
private void initializeLocationEngine()
{
LocationEngineProvider locationEngineProvider = new LocationEngineProvider(this);
locationEngine = locationEngineProvider.obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
@SuppressLint("MissingPermission")
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null)
{
originLocation = lastLocation;
}
else
{
locationEngine.addLocationEngineListener(this);
}
}
@SuppressLint("MissingPermission")
@Override
public void onConnected()
{
}
@Override
public void onLocationChanged(Location location)
{
}
@Override
public void onExplanationNeeded(List<String> permissionsToExplain)
{
//present toast
}
@Override
public void onPermissionResult(boolean granted)
{
if (granted)
{
enableLocationPlugin();
}
else
{
//Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@SuppressLint("MissingPermission")
@Override
protected void onStart()
{
super.onStart();
mapView.onStart();
if (locationLayerPlugin != null)
{
locationLayerPlugin.onStart();
}
}
@Override
protected void onResume()
{
super.onResume();
mapView.onResume();
}
@Override
protected void onPause()
{
super.onPause();
mapView.onPause();
}
@Override
protected void onStop()
{
super.onStop();
mapView.onStop();
if (locationLayerPlugin != null)
{
locationLayerPlugin.onStart();
}
}
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState)
{
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory()
{
super.onLowMemory();
mapView.onLowMemory();
}
@Override
protected void onDestroy()
{
super.onDestroy();
mapView.onDestroy();
}
}
Это файл gradle уровня моего проекта:
buildscript
{
repositories
{
google()
jcenter()
mavenCentral()
maven { url "http://oss.sonatype.org/content/repositories/snapshots/" }
}
dependencies
{
classpath 'com.android.tools.build:gradle:3.2.0'
classpath 'com.google.gms:google-services:4.1.0'
}
}
allprojects
{
repositories
{
google()
jcenter()
maven
{
url 'https://mapbox.bintray.com/mapbox'
}
}
}
Это уровень приложения build.gradle:
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android
{
compileSdkVersion 27
defaultConfig
{
applicationId "com.example.kushagravashisht.mapbox_with_search_bar"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes
{
release
{
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions
{
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies
{
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.0.2'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
// MAPBOX DEPENDENCIES
implementation ('com.mapbox.mapboxsdk:mapbox-android-sdk:6.5.0@aar')
{
transitive=true
}
implementation 'com.mapbox.mapboxsdk:mapbox-android-navigation:0.20.0'
implementation ('com.mapbox.mapboxsdk:mapbox-android-navigation-ui:0.20.0')
{
transitive = true
}
implementation 'com.google.android.gms:play-services-maps:16.0.0'
implementation 'com.android.support:design:27.0.2'
// PLUGIN-PLACES DEPENDENCIES
implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-places:0.6.0'
implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-places:0.7.0-SNAPSHOT'
}
Пожалуйста, дайте мне знать, если что-то еще требуется из кода.Буду очень признателен, если кто-нибудь сможет помочь мне с интеграцией плагинов в этом существующем приложении.