Routing between two points in Mapbox (Android) - android

I am using MapBox to create a route between two points. I have LatLng of two points already and have successfully add Markers at source and destination point but the problem is, I am unable to create a route between them. Here is the code. I don't know where i am lacking but i have followed a tutorial but in that Tutor is creating a route between current location and the location clicked on map and he is doing stuff in onMapClicked method since i am not using that approach due to have customized point. Instead, i am doing stuff in the onMapReady method other than all the procedure is identical.
package com.devaj.googlemaps;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.devaj.googlemaps.models.TDD;
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.MarkerOptions;
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.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
public class NavigationActivity extends AppCompatActivity implements OnMapReadyCallback{
public static final String TAG = "NavigationActivity";
private MapView mapView;
private TDD tdd;
private Point originPosition, dstPosition;
private Double originLat, originLng, dstLat, dstLng;
private LatLng originLatLng, dstLatLng;
private MapboxMap map;
private NavigationMapRoute navigationMapRoute;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_navigation);
MapBox(savedInstanceState);
}
#Override
public void onMapReady(#NonNull MapboxMap mapboxMap) {
map = mapboxMap;
originPosition = Point.fromLngLat(originLat, originLng);
dstPosition = Point.fromLngLat(dstLat, dstLng);
MarkerOptions options = new MarkerOptions();
options.title("Source");
options.position(originLatLng);
MarkerOptions options1 = new MarkerOptions();
options1.title("Destination");
options1.position(dstLatLng);
mapboxMap.addMarker(options);
mapboxMap.addMarker(options1);
mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
navigationMapRoute = new NavigationMapRoute(null, mapView, map, R.style.NavigationMapRoute);
getRoute(originPosition, dstPosition);
}
});
}
private void MapBox(Bundle savedInstanceState)
{
Intent i = getIntent();
tdd = (TDD) i.getSerializableExtra("tdd");
originLat = Double.parseDouble(tdd.getmSrcLat());
originLng = Double.parseDouble(tdd.getmSrcLng());
dstLat = Double.parseDouble(tdd.getmDstLat());
dstLng = Double.parseDouble(tdd.getmDstLng());
originLatLng = new LatLng(originLat, originLng);
dstLatLng = new LatLng(dstLat, dstLng);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
private void getRoute(Point origin, Point destination)
{
// CameraPosition position = new CameraPosition.Builder()
// .target(originLatLng) // 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
//
// map.animateCamera(CameraUpdateFactory
// .newCameraPosition(position), 7000);
NavigationRoute.builder(NavigationActivity.this)
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
if (response.body() == null)
{
Usable.logMessage(TAG, "No routes found, Check User and Access Token..");
return;
} else if (response.body().routes().size() == 0)
{
Usable.logMessage(TAG, "No routes found..");
return;
}
DirectionsRoute currentRoute = response.body().routes().get(0);
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
Log.e(TAG, "Error: "+ t.getMessage());
}
});
}
#Override
protected void onStart() {
super.onStart();
mapView.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();
}
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
}

You've got your lat/long order mixed up whenever you use Point.fromLngLat().
For example, dstPosition = Point.fromLngLat(dstLat, dstLng); is the wrong order.
Is there a log message in your logcat when you try the code you posted above? Search for Mbgl. Is response.body() null? Is the route size == 0? Basically, it'd be helpful if you could explain more when you say I am unable to create a route between them.
By the way, you don't have to use the Mapbox Navigation SDK for Android if you want to get a route between two points. The Mapbox Java SDK can do that.
https://docs.mapbox.com/android/java/overview/directions
https://docs.mapbox.com/android/java/examples/show-directions-on-a-map
https://docs.mapbox.com/android/java/examples/dashed-directions-line
Also, I'd move the onMapReady() stuff into the onStyleLoaded() callback.
#Override
public void onMapReady(#NonNull MapboxMap mapboxMap) {
mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
map = mapboxMap;
originPosition = Point.fromLngLat(originLng, originLat);
dstPosition = Point.fromLngLat(dstLng, dstLat);
MarkerOptions options = new MarkerOptions();
options.title("Source");
options.position(originLatLng);
MarkerOptions options1 = new MarkerOptions();
options1.title("Destination");
options1.position(dstLatLng);
mapboxMap.addMarker(options);
mapboxMap.addMarker(options1);
navigationMapRoute = new NavigationMapRoute(null, mapView, map, R.style.NavigationMapRoute);
getRoute(originPosition, dstPosition);
}
});
}

Related

I am trying to use Geofire to store and display the users that are logged in on a map

I am trying to use Geofire to store and display the users that are logged in on a map i am new in android studio
i am getting this error
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.parthtiwari.trace/com.example.parthtiwari.trace.tracking}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Circle com.google.android.gms.maps.GoogleMap.addCircle(com.google.android.gms.maps.model.CircleOptions)' on a null object reference
import android.app.AlertDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.app.FragmentActivity;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Interpolator;
import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.firebase.geofire.GeoQuery;
import com.firebase.geofire.GeoQueryEventListener;
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.*;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import java.util.HashMap;
import java.util.Map;
public class tracking extends FragmentActivity implements
GeoQueryEventListener,OnMapReadyCallback,
GoogleMap.OnCameraChangeListener{
private static final GeoLocation INITIAL_CENTER = new GeoLocation(22.7789,
-78.4017);
private static final int INITIAL_ZOOM_LEVEL = 14;
private static final String GEO_FIRE_DB = "https://trace-
5fa8c.firebaseio.com";
private static final String GEO_FIRE_REF = GEO_FIRE_DB + "/_geofire";
private GoogleMap mMap;
private GoogleMap map;
private Circle searchCircle;
private GeoFire geoFire;
private GeoQuery geoQuery;
private Map<String,Marker> markers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tracking);
// Obtain the SupportMapFragment and get notified when the map is ready
to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync((OnMapReadyCallback) this);
LatLng latLngCenter = new LatLng(INITIAL_CENTER.latitude,
INITIAL_CENTER.longitude);
this.searchCircle = this.map.addCircle(new
CircleOptions().center(latLngCenter).radius(1000));
this.searchCircle.setFillColor(Color.argb(66, 255, 0, 255));
this.searchCircle.setStrokeColor(Color.argb(66, 0, 0, 0));
this.map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngCenter,
INITIAL_ZOOM_LEVEL));
this.map.setOnCameraChangeListener(this);
FirebaseOptions options = new FirebaseOptions.Builder().setApplicationId("geofire").setDatabaseUrl(GEO_FIRE_DB).build();
FirebaseApp app = FirebaseApp.initializeApp(this, options);
// setup GeoFire
this.geoFire = new GeoFire(FirebaseDatabase.getInstance(app).getReferenceFromUrl(GEO_FIRE_REF));
// radius in km
this.geoQuery = this.geoFire.queryAtLocation(INITIAL_CENTER, 1);
// setup markers
this.markers = new HashMap<String, Marker>();
}
#Override
protected void onStop() {
super.onStop();
// remove all event listeners to stop updating in the background
this.geoQuery.removeAllListeners();
for (Marker marker: this.markers.values()) {
marker.remove();
}
this.markers.clear();
}
#Override
protected void onStart() {
super.onStart();
// add an event listener to start updating locations again
this.geoQuery.addGeoQueryEventListener(this);
}
#Override
public void onKeyEntered(String key, GeoLocation location) {
// Add a new marker to the map
Marker marker = this.map.addMarker(new MarkerOptions().position(new
LatLng(location.latitude, location.longitude)));
this.markers.put(key, marker);
}
#Override
public void onKeyExited(String key) {
// Remove any old marker
Marker marker = this.markers.get(key);
if (marker != null) {
marker.remove();
this.markers.remove(key);
}
}
#Override
public void onKeyMoved(String key, GeoLocation location) {
// Move the marker
Marker marker = this.markers.get(key);
if (marker != null) {
this.animateMarkerTo(marker, location.latitude, location.longitude);
}
}
#Override
public void onGeoQueryReady() {
}
#Override
public void onGeoQueryError(DatabaseError error) {
new AlertDialog.Builder(this)
.setTitle("Error")
.setMessage("There was an unexpected error querying GeoFire: " +
error.getMessage())
.setPositiveButton(android.R.string.ok, null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
// Animation handler for old APIs without animation support
private void animateMarkerTo(final Marker marker, final double lat, final
double lng) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final long DURATION_MS = 3000;
final Interpolator interpolator = new
AccelerateDecelerateInterpolator();
final LatLng startPosition = marker.getPosition();
handler.post(new Runnable() {
#Override
public void run() {
float elapsed = SystemClock.uptimeMillis() - start;
float t = elapsed/DURATION_MS;
float v = interpolator.getInterpolation(t);
double currentLat = (lat - startPosition.latitude) * v +
startPosition.latitude;
double currentLng = (lng - startPosition.longitude) * v +
startPosition.longitude;
marker.setPosition(new LatLng(currentLat, currentLng));
// if animation is not finished yet, repeat
if (t < 1) {
handler.postDelayed(this, 16);
}
}
});
}
private double zoomLevelToRadius(double zoomLevel) {
// Approximation to fit circle into view
return 16384000/Math.pow(2, zoomLevel);
}
#Override
public void onCameraChange(CameraPosition cameraPosition) {
LatLng center = cameraPosition.target;
double radius = zoomLevelToRadius(cameraPosition.zoom);
this.searchCircle.setCenter(center);
this.searchCircle.setRadius(radius);
this.geoQuery.setCenter(new GeoLocation(center.latitude,
center.longitude));
// radius in km
this.geoQuery.setRadius(radius/1000);
}
#Override
public void onMapReady(GoogleMap googleMap) {
}
}
You are requesting the GoogleMap instance asynchronously with this statement:
mapFragment.getMapAsync((OnMapReadyCallback) this);
When the map is available for use, it will be reported to you in this callback:
#Override
public void onMapReady(GoogleMap googleMap) {
}
You need to take all initialization code that uses the map out of your activity's onCreate() method and move it into onMapReady() or methods that are called from onMapReady(). For example:
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
//mMap = googleMap; // not used?
// all the map init stuff
LatLng latLngCenter = new LatLng(INITIAL_CENTER.latitude,
INITIAL_CENTER.longitude);
this.searchCircle = this.map.addCircle(new
CircleOptions().center(latLngCenter).radius(1000));
this.searchCircle.setFillColor(Color.argb(66, 255, 0, 255));
this.searchCircle.setStrokeColor(Color.argb(66, 0, 0, 0));
this.map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngCenter,
INITIAL_ZOOM_LEVEL));
this.map.setOnCameraChangeListener(this);
}
It's not clear why you are creating another app instance. I don't think Geofire needs it. Try using the default:
//FirebaseOptions options = new FirebaseOptions.Builder().setApplicationId("geofire").setDatabaseUrl(GEO_FIRE_DB).build();
//FirebaseApp app = FirebaseApp.initializeApp(this, options);
// setup GeoFire
this.geoFire = new GeoFire(FirebaseDatabase.getInstance().getReferenceFromUrl(GEO_FIRE_REF));

Re-Transition when I click on button (e.g./i.e. Like Intent from current Activity to self Activity)

Basically I am working on Google Map in which I have Google Map Activity and user click on any place of Google Map I was adding marker on this click and I have one button on this button click I take this marker position and put it to my Firebase Database.My complete code was working, but the problem is that when I click on the button which takes marker latlang to Firebase, my latlang value successfully update and my map Activity is re-transited (e.g./i.e. like Intent from current Activity to self Activity) that for my map was reloaded and I lose marker on screen.
Here is my Java code:
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.firebase.client.Firebase;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
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 PickUpActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, View.OnClickListener, GoogleMap.OnMapClickListener {
private static final int PERMISSION_REQUEST_CODE = 1;
public double marker_latitude;
public double marker_longitude;
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private Marker marker;
private double latitude;
private double longitude;
private Button btn;
private Bus bus;
private Firebase ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pick_up);
Firebase.setAndroidContext(this);
btn = (Button) findViewById(R.id.btn_pick);
ref = new Firebase(Config.FIREBASE_URL);
bus = new Bus();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mMap = mapFragment.getMap();
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
btn.setOnClickListener(this);
mMap.setOnMapClickListener(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
getCurrentLocation();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
private void getCurrentLocation() {
if (!checkPermission()) {
requestPermission();
}
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
longitude = location.getLongitude();
latitude = location.getLatitude();
moveMap();
}
}
private void moveMap() {
LatLng latLng = new LatLng(latitude, longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(PickUpActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(PickUpActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
Toast.makeText(PickUpActivity.this, "GPS permission allows us to access location data. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(PickUpActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getCurrentLocation();
} else {
}
break;
}
}
#Override
public void onClick(View v) {
if (v == btn) {
if (marker == null) {
Toast.makeText(PickUpActivity.this, "Please Select Any Place", Toast.LENGTH_SHORT).show();
} else {
bus.setlatitude(marker_latitude);
bus.setlongitude(marker_longitude);
ref.child("school1").child("bus1").child("parents").child("parent01").child("pickuppoint").setValue(bus);
Toast.makeText(PickUpActivity.this, "Pick Up Point Set", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onMapClick(LatLng latLng) {
mMap.clear();
marker = mMap.addMarker(new MarkerOptions()
.position(latLng) //setting position
.draggable(true) //Making the marker draggable
.title("" + latLng));
marker_latitude = latLng.latitude;
marker_longitude = latLng.longitude;
}
}
During analysis I found problem in below code:
bus.setlatitude(marker_latitude);
bus.setlongitude(marker_longitude);
ref.child("school1").child("bus1").child("parents").child("parent01").child("pickuppoint").setValue(bus);
If I put some static value on bus.setlatitude() and bus.setlongitude no re-transition occur. I don't know what I am doing wrong and what is solution for this problem.
if your user click on your Map the map will be cleared: mMap.clear();
#Override
public void onMapClick(LatLng latLng) {
mMap.addMarker(new MarkerOptions()
.position(latLng) //setting position
.draggable(true) //Making the marker draggable
.title(""+latLng));
marker_latitude = latLng.latitude;
marker_longitude= latLng.longitude;
}

Mapbox tracking mode SDK 4.0.0

I'm using android Mapbox SDK 4.0.0 and I cann't set center of map when location changed. I don't understand how to use MyLocationTrackingMode. Or how to recive current latitude and longitude and past them to CameraPosition. Can somebody help me, please? Thanks in advance!
package com.detores.wristmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.constants.Style;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
public class MainActivity extends AppCompatActivity {
private MapView mapView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create a mapView
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(MapboxMap mapboxMap) {
// Set map style
mapboxMap.setStyleUrl(Style.MAPBOX_STREETS);
// Set the camera's starting position
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(50.0051, 36.3562)) // set the camera's center position
.zoom(12) // set the camera's zoom level
.build();
// Move the camera to that position
mapboxMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mapboxMap.setMyLocationEnabled(true);
}
});
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
}
if I understand what you are trying to accomplish then this code snippet might help you get started:
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
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;
public class MainActivity extends AppCompatActivity implements MapboxMap.OnMyLocationChangeListener {
private MapboxMap map;
private MapView mapView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(MapboxMap mapboxMap) {
map = mapboxMap;
mapboxMap.setOnMyLocationChangeListener(MainActivity.this);
mapboxMap.setMyLocationEnabled(true);
}
});
}
#Override
public void onMyLocationChange(#Nullable Location location) {
if (location != null) {
map.easeCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude())));
}
}
// Add the mapView lifecycle to the activity's lifecycle methods
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#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);
}
}
Hope this helps you out!

How to toggle Action Bar while touching the map like Uber

I have implemented a map that behaves like Uber app i.e pin in center and map drags under the pin and the pin gets the location from map. But I am not able to implement the touch event for toggling the action bar just exactly Uber do. Please help me to implement that feature. First I have used support map fragment but to set touch events a view was required so later on I used MapView.Below is my code:
package com.example.myfastapp;
import java.util.List;
import java.util.Locale;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentSender.SendIntentException;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
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 mapFragment extends Fragment implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
MapView mapView;
//private View touch;
private GoogleMap map;
private LatLng center;
private LatLng currentpoint;
private Geocoder geocoder;
private List<Address> addresses;
double latitude;
double longitude;
protected Context context;
SupportMapFragment mf;
View v;
private static final CharSequence[] MAP_TYPE_ITEMS = { "Road Map",
"Satellite", "Terrain" };
// A request to connect to Location Services
private LocationRequest mLocationRequest;
private TextView markerText, Address;
private LinearLayout markerLayout;
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private GPSTracker gps;
// Milliseconds per second
public static final int MILLISECONDS_PER_SECOND = 1000;
// The update interval
public static final int UPDATE_INTERVAL_IN_SECONDS = 5;
// A fast interval ceiling
public static final int FAST_CEILING_IN_SECONDS = 1;
// Update interval in milliseconds
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = MILLISECONDS_PER_SECOND
* UPDATE_INTERVAL_IN_SECONDS;
// A fast ceiling of update intervals, used when the app is visible
public static final long FAST_INTERVAL_CEILING_IN_MILLISECONDS = MILLISECONDS_PER_SECOND
* FAST_CEILING_IN_SECONDS;
public mapFragment(Context context) {
super();
this.context = context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.mapfragment, container, false);
// v.setOnDragListener(new MyDragListener());
mapView = (MapView)v.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
ImageButton mapType = (ImageButton) v.findViewById(R.id.mapType);
mapType.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showMapTypeSelectorDialog();
}
});
ImageButton myLocationCustomButton = (ImageButton)v.findViewById(R.id.myLocationCustom);
myLocationCustomButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
gps = new GPSTracker(getActivity());
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
currentpoint = new LatLng(latitude, longitude);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(currentpoint, 18);
map.animateCamera(cameraUpdate);
map.setMyLocationEnabled(true);
}
});
markerText = (TextView) v.findViewById(R.id.locationMarkertext);
Address = (TextView) v.findViewById(R.id.adressText);
markerLayout = (LinearLayout) v.findViewById(R.id.locationMarker);
// Getting Google Play availability status
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(context);
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status,
getActivity(), requestCode);
dialog.show();
} else {
// Google Play Services are available
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
return v;
}
public void toggleActionBar()
{
ActionBar ab = getActivity().getActionBar();
if (ab != null)
{
if (ab.isShowing())
{
ab.hide();
}
else
{
if(!ab.isShowing())
{
ab.show();
}
}
}
}
private void setupMap() {
try {
/*map = ((SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.map)).getMap();*/
map = mapView.getMap();
// Enabling MyLocation in Google Map
map.setMyLocationEnabled(true);
map.getUiSettings().setZoomControlsEnabled(true);
map.getUiSettings().setMyLocationButtonEnabled(false);
map.getUiSettings().setCompassEnabled(false);
map.getUiSettings().setRotateGesturesEnabled(true);
map.getUiSettings().setZoomGesturesEnabled(true);
try {
MapsInitializer.initialize(this.getActivity());
} catch (Exception e) {
e.printStackTrace();
}
PendingResult<Status> result = LocationServices.FusedLocationApi
.requestLocationUpdates(mGoogleApiClient, mLocationRequest,
new LocationListener() {
#Override
public void onLocationChanged(Location location) {
markerText.setText("Location received: "
+ location.toString());
}
});
Log.e("Reached", "here");
result.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
Log.e("Result", "success");
} else if (status.hasResolution()) {
// Google provides a way to fix the issue
try {
status.startResolutionForResult(getActivity(), 100);
} catch (SendIntentException e) {
e.printStackTrace();
}
}
}
});
gps = new GPSTracker(getActivity());
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
currentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(currentpoint).zoom(16f).tilt(30).bearing(90).build();
map.setMyLocationEnabled(true);
map.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
map.clear();
map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
//toggleActionBar();
center = map.getCameraPosition().target;
markerText.setText(" Set your Location ");
map.clear();
markerLayout.setVisibility(View.VISIBLE);
try
{
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
markerLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
LatLng latLng1 = new LatLng(center.latitude,
center.longitude);
Marker m = map.addMarker(new MarkerOptions()
.position(latLng1)
.title(" Set your Location ")
.snippet("")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.my_location)));
m.setDraggable(true);
markerLayout.setVisibility(View.GONE);
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onConnected(Bundle connectionHint) {
setupMap();
}
#Override
public void onConnectionSuspended(int cause) {
}
#Override
public void onLocationChanged(Location location) {
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
double x, y;
StringBuilder str;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
#Override
protected void onPreExecute() {
Address.setText(" Getting location ");
}
#Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(context, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (Geocoder.isPresent()) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + " ");
str.append(city + " " + region_code + " ");
str.append(zipcode + " ");
}
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0) + ", "
+ addresses.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
/*
* public void addMarker(double lati, double longi) {
*
* LatLng latlng = new LatLng(lati, longi);
*
* MarkerOptions mo = new MarkerOptions(); mo.position(latlng);
* mo.icon(BitmapDescriptorFactory.fromResource(R.drawable.my_location));
* mo.title("My Location:"+ latlng); map.addMarker(mo);
*
* //map.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng,
* 15));//previous code CameraPosition cameraPosition = new
* CameraPosition.Builder() .target(latlng) .zoom(11.0f) .bearing(90) //
* Orientation of the camera to east .tilt(30) // Tilt of the camera to 30
* degrees .build();
* map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
* map.setMyLocationEnabled(true);
* map.getUiSettings().setCompassEnabled(true);
* map.getUiSettings().setZoomControlsEnabled(true);
* //map.setMapType(GoogleMap.MAP_TYPE_NORMAL); }
*/
public void showMapTypeSelectorDialog() {
// Prepare the dialog by setting up a Builder.
final String fDialogTitle = "Select Map Type";
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(fDialogTitle);
// Find the current map type to pre-check the item representing the
// current state.
int checkItem = map.getMapType() - 1;
System.out.print(checkItem);
// Add an OnClickListener to the dialog, so that the selection will be
// handled.
builder.setSingleChoiceItems(MAP_TYPE_ITEMS, checkItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item)
{
// Locally create a finalised object.
// Perform an action depending on which item was
// selected.
switch (item)
{
case 1:
map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case 2:
map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
default:
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
dialog.dismiss();
}
});
// Build the dialog and show it.
AlertDialog fMapTypeDialog = builder.create();
fMapTypeDialog.setCanceledOnTouchOutside(true);
fMapTypeDialog.show();
}
#Override
public void onResume()
{
super.onResume();
mapView.onResume();
mapView.getMap();
}
#Override
public void onPause()
{
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory()
{
super.onLowMemory();
mapView.onLowMemory();
}
}
The onCameraChangeListener is deprecated, but good news is that google has released 3 new listeners.
See: GoogleMap.OnCameraChangeListener
This interface was deprecated.
Replaced by GoogleMap.OnCameraMoveStartedListener, GoogleMap.OnCameraMoveListener and GoogleMap.OnCameraIdleListener. The order in which the deprecated onCameraChange method will be called in relation to the methods in the new camera change listeners is undefined.
I have used these listeners and now i am able get the hold and release event on map.
I believe you should add an onMarkerDragListener to your map object and do your code inside.
map.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
}
});
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"/>
<ImageButton
android:id="#+id/fabButton"
android:layout_width="56dp"
android:layout_height="56dp"
android:layout_gravity="bottom|right"
android:layout_marginBottom="16dp"
android:layout_marginRight="16dp"
android:background="#drawable/fab_bcg"
android:src="#drawable/ic_favorite_outline_white_24dp"
android:contentDescription="Desc"/>
This is methods for show and hide views
private void hideViews() {
mToolbar.animate().translationY(-mToolbar.getHeight()).setInterpolator(new AccelerateInterpolator(2));
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mFabButton.getLayoutParams();
int fabBottomMargin = lp.bottomMargin;
mFabButton.animate().translationY(mFabButton.getHeight()+fabBottomMargin).setInterpolator(new AccelerateInterpolator(2)).start();
}
private void showViews() {
mToolbar.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2));
mFabButton.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();
}

Display a path in my maps android app

I tried to develop a android app with maps. I'm a beginner in android app development, i doesn't know how to generate a path between my current position and to the destination. I can able to view by current location by the code shown below.
package com.example.myapp;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class Grandinmaps extends Activity implements OnMapReadyCallback{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grandinmaps);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
// TODO Auto-generated method stub
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(12.971907, 80.220462), 18));
}
}
And i doesn't know the code to generate the path to destination.
Any HELP...!!! Please:-)
For Drawing Route you can use this code:
Call for printing location route:
GmapV2Direction route;
Document document;
LatLng toPosition = new LatLng(routeData.get(i).latitude, routeData.get(i).longitude);
new GetRouteTask() {
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}.execute((LatLng) toPosition);
private class GetRouteTask extends AsyncTask<LatLng, Void, String> {
String response = "";
#Override
protected String doInBackground(LatLng... params) {
document = route.getDocument(fromPosition, params[0], GmapV2Direction.MODE_WALKING);//fromPosition is another LatLng object.can be your current location.
response = "Success";
return response;
}
#Override
protected void onPostExecute(String s) {
// directionMap.clear();
if (response.equalsIgnoreCase("Success")) {
Log.v("Map", "got here");
ArrayList<LatLng> directionPoint = route.getDirection(document);
PolylineOptions rectLine = new PolylineOptions().width(10).color(
Color.RED);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
// Adding route on the map
map.addPolyline(rectLine);
}
}
}

Categories

Resources