How can I show the places suggestions below text box? - java

I am using mapbox for my apllication where I want to to show the suggestions of places below the textbox...
Below is my code,
In my code what was happening is after clicking on the search button which is a floatingaction button, a search bar opens and it allow us to search for places...
and after that a marker is placed to that location
It looks like this
package com.example.mapboxwithmarker;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import com.google.gson.JsonObject;
import com.mapbox.api.geocoding.v5.models.CarmenFeature;
import com.mapbox.geojson.Feature;
import com.mapbox.geojson.FeatureCollection;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.camera.CameraPosition;
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.maps.Style;
import com.mapbox.mapboxsdk.plugins.places.autocomplete.PlaceAutocomplete;
import com.mapbox.mapboxsdk.plugins.places.autocomplete.model.PlaceOptions;
import com.mapbox.mapboxsdk.style.layers.SymbolLayer;
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconOffset;
public class Locationsearch extends AppCompatActivity implements OnMapReadyCallback {
private static final int REQUEST_CODE_AUTOCOMPLETE = 1;
private MapView mapView;
private MapboxMap mapboxMap;
private CarmenFeature home;
private CarmenFeature work;
private String geojsonSourceLayerId = "geojsonSourceLayerId";
private String symbolIconId = "symbolIconId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Mapbox access token is configured here. This needs to be called either in your application
// object or in the same activity which contains the mapview.
Mapbox.getInstance(this, getString(R.string.mapbox_access_token));
// This contains the MapView in XML and needs to be called after the access token is configured.
setContentView(R.layout.activity_locationsearch);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
#Override
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
initSearchFab();
addUserLocations();
// Add the symbol layer icon to map for future use
style.addImage(symbolIconId, BitmapFactory.decodeResource(
Locationsearch.this.getResources(), R.drawable.ic_location_on));
// Create an empty GeoJSON source using the empty feature collection
setUpSource(style);
// Set up a new symbol layer for displaying the searched location's feature coordinates
setupLayer(style);
}
});
}
private void initSearchFab() {
findViewById(R.id.fab_location_search).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new PlaceAutocomplete.IntentBuilder()
.accessToken(Mapbox.getAccessToken() != null ? Mapbox.getAccessToken() : getString(R.string.mapbox_access_token))
.placeOptions(PlaceOptions.builder()
.backgroundColor(Color.parseColor("#EEEEEE"))
.limit(10)
.addInjectedFeature(home)
.addInjectedFeature(work)
.build(PlaceOptions.MODE_CARDS))
.build(Locationsearch.this);
startActivityForResult(intent, REQUEST_CODE_AUTOCOMPLETE);
}
});
}
private void addUserLocations() {
home = CarmenFeature.builder().text("Mapbox SF Office")
.geometry(Point.fromLngLat(-122.3964485, 37.7912561))
.placeName("50 Beale St, San Francisco, CA")
.id("mapbox-sf")
.properties(new JsonObject())
.build();
work = CarmenFeature.builder().text("Mapbox DC Office")
.placeName("740 15th Street NW, Washington DC")
.geometry(Point.fromLngLat(-77.0338348, 38.899750))
.id("mapbox-dc")
.properties(new JsonObject())
.build();
}
private void setUpSource(#NonNull Style loadedMapStyle) {
loadedMapStyle.addSource(new GeoJsonSource(geojsonSourceLayerId));
}
private void setupLayer(#NonNull Style loadedMapStyle) {
loadedMapStyle.addLayer(new SymbolLayer("SYMBOL_LAYER_ID", geojsonSourceLayerId).withProperties(
iconImage(symbolIconId),
iconOffset(new Float[] {0f, -8f})
));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_AUTOCOMPLETE) {
// Retrieve selected location's CarmenFeature
CarmenFeature selectedCarmenFeature = PlaceAutocomplete.getPlace(data);
// Create a new FeatureCollection and add a new Feature to it using selectedCarmenFeature above.
// Then retrieve and update the source designated for showing a selected location's symbol layer icon
if (mapboxMap != null) {
Style style = mapboxMap.getStyle();
if (style != null) {
GeoJsonSource source = style.getSourceAs(geojsonSourceLayerId);
if (source != null) {
source.setGeoJson(FeatureCollection.fromFeatures(
new Feature[] {Feature.fromJson(selectedCarmenFeature.toJson())}));
}
// Move map camera to the selected location
mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.target(new LatLng(((Point) selectedCarmenFeature.geometry()).latitude(),
((Point) selectedCarmenFeature.geometry()).longitude()))
.zoom(14)
.build()), 4000);
}
}
}
}
// Add the mapView lifecycle to the activity's lifecycle methods
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
But what I want to achieve is I want to use one EditText as a search box and show the result(suggestions) below the edittext...
How can I achieve this?

Related

Android onCreate of Activity class is not triggered

I am trying to write a plugin for Capacitor. It should pass the accelerometer data to the JavaScript. The bridge works fine.
However, the heading class does not seem to be initialized. The onCreate function does not seem to be executed, so do all the other functions. Nothing is logged to the console.
In AndroidManifest.xml I have requested the following feature:
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" />
The file looks like this:
package de.example.capmap;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import com.getcapacitor.BridgeActivity;
import de.example.Compass;
public class MainActivity extends BridgeActivity {
private Heading heading;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerPlugin(Compass.class);
heading = new Heading();
}
}
class Heading extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor mAccelerometer;
private static final String TAG = "Heading";
#Override
public final void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "onCreate: Initializing");
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(Heading.this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onSensorChanged(SensorEvent event){
Log.i(TAG, "onSensorChanged: " + event.values[0]);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.i(TAG, "onAccuracyChanged:" + accuracy);
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
}
and the Compass Plugin, which gets executed:
import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginHandle;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
import com.getcapacitor.Bridge;
#CapacitorPlugin(name = "Compass")
public class Compass extends Plugin {
public static Bridge staticBridge = null;
#Override
public void load() {
staticBridge = this.bridge;
java.lang.System.out.println("Compass successfully started");
}
public static void onMagneticHeading(float magneticHeading){
Compass pushPlugin = Compass.getCompassInstance();
if (pushPlugin != null) {
pushPlugin.sendMagneticHeading(magneticHeading);
}
}
#PluginMethod()
public void getMagneticHeading(PluginCall call) {
String value = call.getString("value");
JSObject ret = new JSObject();
ret.put("magneticHeading", value);
call.resolve(ret);
}
public void sendMagneticHeading(float magneticHeading) {
JSObject data = new JSObject();
data.put("magneticHeading", magneticHeading);
notifyListeners("heading", data, true);
}
public static Compass getCompassInstance() {
if (staticBridge != null && staticBridge.getWebView() != null) {
PluginHandle handle = staticBridge.getPlugin("Compass");
if (handle == null) {
return null;
}
return (Compass) handle.getInstance();
}
return null;
}
}
How come you're extending an Activity instead of just using a plain class? If it's because you want access to a Context, just pass one in through the constructor (you have one when you create the Heading).
If it's because you want the onPause and onResume lifecycle callbacks, so you know when to register/unregister with the SensorManager, there's a couple of things you could do.
First you can just create some methods the activity can call during onPause/onResume:
class Heading(Context context) {
...
public void sleep() {
sensorManager.unregisterListener(this);
}
public void wake() {
sensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
}
class MainActivity extends BridgeActivity {
...
#Override
protected void onResume() {
super.onResume();
heading.wake();
}
#Override
protected void onPause() {
super.onPause();
heading.sleep();
}
}
The other approach is to make Heading implement DefaultLifecycleObserver, which basically lets you implement onResume and onPause etc like you're doing, and you make it observe the Activity's lifecycle, instead of the Activity having to manually call stuff to be like "hey onPause just happened". I'll just link the example page, but it basically covers what you're doing here (and the earlier, manual example too) as well as some more advanced stuff

How can I show navigation route to a fixed location from current location?

This is my code which shows route to some point from curent location of user to that point....
My code works fine...
My current code shows route when marker is added after onclick event occurs but what I want to achieve is if I have a predefined marker at fixed longitude and latitude which is defined as p1 variable in below code, then it should show the route from the current location...
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.google.android.material.navigation.NavigationView;
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.Feature;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.location.LocationComponent;
import com.mapbox.mapboxsdk.location.modes.CameraMode;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.mapboxsdk.style.layers.SymbolLayer;
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
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;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconAllowOverlap;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconIgnorePlacement;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage;
public class ViewMapActivity extends AppCompatActivity implements OnMapReadyCallback, MapboxMap.OnMapClickListener, PermissionsListener {
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
private NavigationView navigationView;
Toolbar toolbar;
MapView mapView;
MapboxMap mapboxMap;
LocationComponent locationComponent;
private PermissionsManager permissionmanager;
DirectionsRoute currentRoute;
NavigationMapRoute navigationMapRoute;
LatLng p1=new LatLng(72.843214,19.018335);//this is the fixed marker cordinates which I want to use
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this,getString(R.string.mapbox_access_token) );
setContentView(R.layout.activity_view_map);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Navigation");
Toolbar toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawerLayout=findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(ViewMapActivity.this,drawerLayout,R.string.drawer_open,R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
navigationView = findViewById(R.id.naivgation_view);
View navView = navigationView.inflateHeaderView(R.layout.navigation_header);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
// UserMenuSelected(menuItem);
return false;
}
});
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocationComponent(mapboxMap.getStyle());
} else {
Toast.makeText(this, "Permission not granted", Toast.LENGTH_SHORT).show();
finish();
}
}
#Override
public boolean onMapClick(#NonNull LatLng point) {
Point destinationPoint = Point.fromLngLat(point.getLongitude(), point.getLatitude());
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
Point originPoint = Point.fromLngLat(locationComponent.getLastKnownLocation().getLongitude(), locationComponent.getLastKnownLocation().getLatitude());
GeoJsonSource source = mapboxMap.getStyle().getSourceAs("destination-source-id");
if (source != null) {
source.setGeoJson(Feature.fromGeometry(destinationPoint));
}
getRoute(originPoint, destinationPoint);
return true;
}
private void getRoute(Point originPoint, Point destinationPoint) {
NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken())
.origin(originPoint)
.destination(destinationPoint)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
Log.d("response inside fun", String.valueOf(response.body().routes().size()));
if (response.body() != null && response.body().routes().size() >= 1) {
currentRoute = response.body().routes().get(0);
Log.d("current route", String.valueOf(currentRoute));
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, mapboxMap, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
}
});
}
#Override
public void onMapReady(#NonNull MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
this.mapboxMap.setMinZoomPreference(15);
mapboxMap.setStyle(getString(R.string.navigation_guidance_day), new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
enableLocationComponent(style);
addDestinationIconLayer(style);
mapboxMap.addOnMapClickListener(ViewMapActivity.this);
}
});
}
private void addDestinationIconLayer(Style style) {
style.addImage("destination-icon-id",
BitmapFactory.decodeResource(this.getResources(), R.drawable.mapbox_marker_icon_default));
GeoJsonSource geoJsonSource = new GeoJsonSource("destination-source-id");
style.addSource(geoJsonSource);
SymbolLayer destinationSymbolLayer = new SymbolLayer("destination-symbol-layer-id", "destination-source-id");
destinationSymbolLayer.withProperties(iconImage("destination-icon-id"), iconAllowOverlap(true), iconIgnorePlacement(true));
style.addLayer(destinationSymbolLayer);
}
public void startNavigationBtnClick(View v) {
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(currentRoute)
.shouldSimulateRoute(false)
.build();
NavigationLauncher.startNavigation(ViewMapActivity.this, options);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionmanager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void enableLocationComponent(#NonNull Style style) {
if (PermissionsManager.areLocationPermissionsGranted(this)) {
locationComponent = mapboxMap.getLocationComponent();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationComponent.activateLocationComponent(this, style);
locationComponent.setLocationComponentEnabled(true);
locationComponent.setCameraMode(CameraMode.TRACKING);
} else {
permissionmanager = new PermissionsManager(this);
permissionmanager.requestLocationPermissions(this);
}
}
// Add the mapView lifecycle to the activity's lifecycle methods
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
How can I achieve this?
In onStyleLoaded(), instead of calling mapboxMap.addOnMapClickListener, you should just put the code you have in the onClick() method, like this:
Point destinationPoint = Point.fromLngLat(p1.getLongitude(), p1.getLatitude());
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
Point originPoint = Point.fromLngLat(locationComponent.getLastKnownLocation().getLongitude(), locationComponent.getLastKnownLocation().getLatitude());
GeoJsonSource source = mapboxMap.getStyle().getSourceAs("destination-source-id");
if (source != null) {
source.setGeoJson(Feature.fromGeometry(destinationPoint));
}
getRoute(originPoint, destinationPoint);

Mapbox SDK Android Studio

I got to put the map in my app and running in my mobile, but I don't get to put the overlay file GeoJson from Assets Folder in the my locate folder in PC. I want to overlay the points from GeoJson and show popups of points' id. How could I do this?
Below the code that I made from tutorials in Mapbox site in Android Studio
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
import java.net.URI;
import java.net.URISyntaxException;
public class MainActivity extends AppCompatActivity {
private MapView mapView;
private final String SOURCE_ID = "SOURCE_ID";
private final String ICON_ID = "ICON_ID";
private final String LAYER_ID = "LAYER_ID";
private final String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(#NonNull MapboxMap mapboxMap) {
mapboxMap.setStyle(Style.DARK, new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
try {
GeoJsonSource layer = new GeoJsonSource("mapView", new URI("assets://covid_unidades.geojson"));
style.addSource(layer);
} catch (URISyntaxException excepcion) {
Log.d(TAG, String.valueOf(excepcion));
}
}
});
}
});
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
} ```

How to detect the direction of a suggested route in MapBox Directions API?

I am working on a project where I create an app that will direct users through a college campus using AR (Much like the one shown here: https://www.youtube.com/watch?v=vRmTn25xm7Q (7:20)).
I am starting off with the Navigation API for Android from MapBox. I want to know if there is any possible way to fetch a variable where the route guides you a direction(left, right, and forward) and put it through a parameter to prompt a UI element such as an arrow on AR screen in a Unity Android Project.
Here is my code from the Navigation API:
package com.creighton.adh81910.creighton_navigation;
import android.content.Context;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatDelegate;
import android.view.SearchEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.mapbox.api.directions.v5.DirectionsCriteria;
import com.mapbox.api.directions.v5.MapboxDirections;
import com.mapbox.services.;
import com.mapbox.android.core.;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncherOptions.*;
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.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.plugins.locationlayer.LocationLayerPlugin;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
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 com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.services.android.navigation.v5.utils.LocaleUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.util.Log;
import java.security.acl.Permission;
import java.util.List;
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, LocationEngineListener, PermissionsListener, MapboxMap.OnMapClickListener {
private MapView mapView;
private MapboxMap map;
private Button startButton;
private PermissionsManager permissionsManager;
private LocationEngine locationEngine;
private LocationLayerPlugin locationLayerPlugin;
private Location originLocation;
private Point originPosition;
private Point destinationPosition;
private Marker destinationMarker;
private NavigationMapRoute navigationMapRoute;
private static final String TAG = "MainActivity";
private DirectionsRoute currentRoute;
private MapboxDirections mapboxDirections;
private MapboxDirections.Builder directionsBuilder;
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
#override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, "pk.eyJ1IjoiYWRoYXJtYXZhcmFwdSIsImEiOiJjampzdXBkMW4wY25jM3BtcnUzNGpwdTA4In0.qN9Y1LoHxPaONtXLp7rBCw");
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.mapView);
startButton = findViewById(R.id.startButton);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
startButton.setOnClickListener(new View.OnClickListener() {
#override
public void onClick(View v) {
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(currentRoute)
.shouldSimulateRoute(simulateRoute)
.build();
NavigationLauncher.startNavigation(MainActivity.this, options);
}
});
// Example of a call to a native method
//TextView tv = (TextView) findViewById(R.id.sample_text);
//tv.setText(stringFromJNI());
}
#override
public void onMapReady(MapboxMap mapboxMap) {
map = mapboxMap;
map.addOnMapClickListener(this);
enableLocation();
}
private void enableLocation() {
if (PermissionsManager.areLocationPermissionsGranted(this)) {
initializeLocationEngine();
initializeLocationLayer();
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
private void initializeLocationEngine() {
locationEngine = new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null) {
originLocation = lastLocation;
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
private void initializeLocationLayer() {
locationLayerPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationLayerPlugin.setLocationLayerEnabled(true);
locationLayerPlugin.setCameraMode(CameraMode.TRACKING);
locationLayerPlugin.setRenderMode(RenderMode.NORMAL);
}
private void setCameraPosition(Location location) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 17));
}
#override
public void onMapClick(#nonnull LatLng point) {
destinationMarker = map.addMarker(new MarkerOptions().position(point));
destinationPosition = Point.fromLngLat(point.getLongitude(), point.getLatitude());
originPosition = Point.fromLngLat(originLocation.getLongitude(), originLocation.getLatitude());
getRoute(originPosition, destinationPosition);
startButton.setEnabled(true);
startButton.setBackgroundResource(R.color.mapbox_blue);
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder(getApplicationContext())
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback() {
#override
public void onResponse(Call call, Response response) {
if (response.body() == null) {
Log.e(TAG, "No routes found, check right user and access token");
return;
} else if (response.body().routes().size() == 0) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, map);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
Log.e(TAG, "Error" + t.getMessage());
}
});
}
#override
#SuppressWarnings("MissingPermission")
public void onConnected() {
locationEngine.requestLocationUpdates();
}
#override
public void onLocationChanged(Location location) {
if (location != null) {
originLocation = location;
setCameraPosition(location);
}
}
#override
public void onExplanationNeeded(List permissionsToExplain) {
//Present Dialog
}
#override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocation();
}
}
#override
public void onRequestPermissionsResult(int requestCode, #nonnull String[] permissions, #nonnull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#override
public void onStart() {
super.onStart();
if (locationEngine != null) {
locationEngine.requestLocationUpdates();
}
if (locationLayerPlugin != null) {
locationLayerPlugin.onStart();
}
mapView.onStart();
}
#override
public void onResume() {
super.onResume();
mapView.onResume();
}
#override
public void onPause() {
super.onPause();
mapView.onPause();
}
#override
public void onStop() {
super.onStop();
if (locationEngine != null) {
locationEngine.removeLocationUpdates();
}
if (locationLayerPlugin != null) {
locationLayerPlugin.onStop();
}
mapView.onStop();
}
#override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#override
protected void onDestroy() {
super.onDestroy();
if (locationEngine != null) {
locationEngine.deactivate();
}
mapView.onDestroy();
}
#override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
/**
A native method that is implemented by the 'native-lib' native library,
which is packaged with this application.
*/
public native String stringFromJNI();
public static final class Builder {
private final MapboxDirections.Builder directionsBuilder;
private Builder() {
directionsBuilder = MapboxDirections.builder();
}
public Builder Profile(#NonNull #DirectionsCriteria.ProfileCriteria String profile) {
directionsBuilder.profile(profile);
return this;
}
public static Builder builder(Context context) {
return builder(context, new LocaleUtils());
}
static Builder builder(Context contect, LocaleUtils localeUtils) {
return new Builder()
.Profile(DirectionsCriteria.PROFILE_WALKING);
}
}
}

Place Picker loads to long, variables don't change correctly

I'm making a simple place picker program in android. I want to save some text when user choose a point on map with place picker. And the problem is when I click on button the place picker opens too long and variable which is responsible for place can't keep up change and dialog that responses for enter text never opens. I think, maybe problem is with threads, isn't it?
MapsActivity.java
package com.example.kirill.myapplication;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, View.OnClickListener {
private static final int PLACE_PICKER_REQUEST = 1;
private GoogleMap mMap;
private Button addEventBtn;
private PlacePicker.IntentBuilder builder;
private Place place;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddEventButton:
place = null;
callPlacePicker();
if (place != null) {
openDialog();
}
break;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
addEventBtn = (Button) findViewById(R.id.AddEventButton);
}
#Override
public void onMapReady(GoogleMap googleMap){
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
Marker marker = mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
addEventBtn.setOnClickListener(this);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
place = PlacePicker.getPlace(this, data);
}
}
}
public void openDialog() {
DialogEventCreate dialogEventCreate = new DialogEventCreate();
dialogEventCreate.show(getSupportFragmentManager(), "dialog Event Create");
}
public void callPlacePicker() {
builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
DialogEventCreate.java
package com.example.kirill.myapplication;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
public class DialogEventCreate extends AppCompatDialogFragment {
private EditText editEventName;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, null);
builder.setView(view)
.setTitle("Create Event")
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
editEventName = view.findViewById(R.id.editEventName);
return builder.create();
}
}
Please help me, what could go wrong?
Your problem is that the Place Picker communicates with your main activity asynchronously, so you're opening your dialog before it returns. Try waiting until Place Picker has returned before opening the dialog like so:
.
.
.
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddEventButton:
place = null;
callPlacePicker();
break;
}
}
.
.
.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
place = PlacePicker.getPlace(this, data);
openDialog();
}
}
}

Categories