Draw Polyline on google map while Running /Drawing
I'm Creating a where the users can track there a path from where to where he just ran. I have tried Following code it's working but while running it getting start to lagging can anyone tell me where I doing wrong.
To draw polyline I'm refreshing map after some interval
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 5445;
private GoogleMap googleMap;
private FusedLocationProviderClient fusedLocationProviderClient;
private Marker currentLocationMarker;
private Location currentLocation;
private boolean firstTimeFlag = true;
private ArrayList<LatLng> points =new ArrayList<>(); //added
Polyline line; //added
/* private final View.OnClickListener clickListener = view -> {
if (view.getId() == R.id.currentLocationImageButton && googleMap != null && currentLocation != null)
animateCamera(currentLocation);
};
*/
private final LocationCallback mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
if (locationResult.getLastLocation() == null)
return;
currentLocation = locationResult.getLastLocation();
if (firstTimeFlag && googleMap != null) {
animateCamera(currentLocation);
firstTimeFlag = false;
}
showMarker(currentLocation);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(this);
// findViewById(R.id.currentLocationImageButton).setOnClickListener(clickListener);
}
#Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
}
private void startCurrentLocationUpdates() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(3000);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
return;
}
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, mLocationCallback, Looper.myLooper());
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status)
return true;
else {
if (googleApiAvailability.isUserResolvableError(status))
Toast.makeText(this, "Please Install google play services to use this application", Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED)
Toast.makeText(this, "Permission denied by uses", Toast.LENGTH_SHORT).show();
else if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
startCurrentLocationUpdates();
}
}
private void animateCamera(#NonNull Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(getCameraPositionWithBearing(latLng)));
}
#NonNull
private CameraPosition getCameraPositionWithBearing(LatLng latLng) {
return new CameraPosition.Builder().target(latLng).zoom(16).build();
}
private void showMarker(#NonNull Location currentLocation) {
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
if (currentLocationMarker != null){
System.out.println("LastMArkerPostion" + currentLocationMarker.getPosition());
points.add(currentLocationMarker.getPosition());
currentLocationMarker.remove();
}
PolylineOptions options = new PolylineOptions();
for (int i = 0 ; i<points.size() ; i++ ){
options.add(points.get(i)).width(15).color(Color.BLUE).geodesic(true);
googleMap.addPolyline(options);
}
Drawable vectorDrawable = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_green_car_marker, null);
Bitmap bit = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bit);
vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
vectorDrawable.draw(canvas);
currentLocationMarker = googleMap.addMarker(new MarkerOptions().icon( BitmapDescriptorFactory.fromBitmap(bit)).position(latLng));
}
#Override
protected void onStop() {
super.onStop();
if (fusedLocationProviderClient != null)
fusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
}
#Override
protected void onResume() {
super.onResume();
if (isGooglePlayServicesAvailable()) {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
startCurrentLocationUpdates();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
fusedLocationProviderClient = null;
googleMap = null;
}
}
Thanks in advance
Solution
After so many research I found the solution on a GitHub repository
I have made some changes in original code
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String TAG = "MapsActivity";
public GoogleMap mMap;
private ArrayList<LatLng> points;
Polyline line;
Marker now;
double lat1;
double lon1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
points = new ArrayList<LatLng>();
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#SuppressLint("MissingPermission")
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (!mMap.isMyLocationEnabled())
mMap.setMyLocationEnabled(true);
LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (myLocation == null) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String provider = lm.getBestProvider(criteria, true);
myLocation = lm.getLastKnownLocation(provider);
}
if (myLocation != null) {
LatLng userLocation = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
lat1=myLocation.getLatitude();
lon1=myLocation.getLongitude();
mMap.addMarker(new MarkerOptions()
.position(userLocation)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
.title("Welcome ")
.snippet("Latitude:"+lat1+",Longitude:"+lon1)
);
Log.v(TAG, "Lat1=" + lat1);
Log.v(TAG, "Long1=" + lon1);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 20), 1500, null);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000,0, new LocationListener() {
#Override
public void onLocationChanged(Location myLocation) {
// Getting latitude of the current location
double latitude = myLocation.getLatitude();
// Getting longitude of the current location
double longitude = myLocation.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
//Adding new marker
/* now = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.position(latLng).title("New")
.snippet("Latitude:"+lat1+",Longitude:"+lon1)
);*/
// Showing the current location in Google Map
// mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
// mMap.animateCamera(CameraUpdateFactory.zoomTo(20));
//Draw polyline
drawPolygon(latitude, longitude);
// Toast.makeText(MapsActivity.this, String.valueOf(latitude)+String.valueOf(longitude), Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
});
}
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
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;
}
mMap.getUiSettings().setZoomControlsEnabled(true);
}
private void drawPolygon( double latitude, double longitude) {
List<LatLng> polygon = new ArrayList<>();
//old lat and long
polygon.add(new LatLng(lat1, lon1));
//new lat and long
polygon.add(new LatLng(latitude,longitude));
mMap.addPolygon(new PolygonOptions()
.addAll(polygon)
.strokeColor(Color.parseColor("#03A9F4"))
.strokeWidth(15)
.fillColor(Color.parseColor("#B3E5FC"))
);
lat1=latitude;
lon1=longitude;
}
}
Full code available on
Github
Related
'''
public class GpsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final int PRIORITY_HIGH_ACCURACY = 100;
private GoogleMap mMap;
private static final int PERMISSIONS_FINE_LOCATION = 99;
Location loc;
LatLng curPo;
boolean state = false;
private LocationRequest locationRequest;
private FusedLocationProviderClient fusedLocationProviderClient;
Button rstart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationRequest = LocationRequest.create()
.setInterval(5000)
.setPriority(PRIORITY_HIGH_ACCURACY)
.setSmallestDisplacement(5);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(locationRequest);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(GpsActivity.this);
setContentView(R.layout.activity_gps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
rstart = findViewById(R.id.rstart);
rstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
changeState();
}
});
askforPermission();
}
#SuppressLint("MissingPermission")
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(checkPermission()){
mMap.setMyLocationEnabled(true);
}
mMap.getUiSettings().setMyLocationButtonEnabled(true);
}
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart");
if (checkPermission()) {
Log.d(TAG, "onStart : call mFusedLocationClient.requestLocationUpdates");
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null);
if (mMap!=null)
mMap.setMyLocationEnabled(true);
}
}
#Override
protected void onStop() {
super.onStop();
if(fusedLocationProviderClient != null){
fusedLocationProviderClient.removeLocationUpdates(locationCallback);
}
}
// Methods
private void askforPermission(){
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED){
LocationCallback mCallback = new LocationCallback() {
#Override
public void onLocationResult(#NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
for(Location location : locationResult.getLocations()){
setCurrentLocation(location);
}
}
};
fusedLocationProviderClient.requestLocationUpdates(locationRequest,mCallback,null);
fusedLocationProviderClient.removeLocationUpdates(mCallback);
}else{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_FINE_LOCATION);
}
}
}
private boolean checkPermission() {
int hasFineLocationPermission = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
int hasCoarseLocationPermission = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION);
if (hasFineLocationPermission == PackageManager.PERMISSION_GRANTED &&
hasCoarseLocationPermission == PackageManager.PERMISSION_GRANTED ) {
return true;
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case PERMISSIONS_FINE_LOCATION:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
askforPermission();
}else{
Toast.makeText(this,"this App requires permission for gps", Toast.LENGTH_SHORT).show();
finish();
}
}
}
public void setCurrentLocation(Location location) {
LatLng startLatLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(startLatLng, 15);
mMap.moveCamera(cameraUpdate);
//mMap.addMarker(new MarkerOptions().position(currentLatLng)); //확인용
}
LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(#NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
List<Location> savedLocation = locationResult.getLocations();
if(savedLocation.size() > 0){
loc = savedLocation.get(savedLocation.size() - 1);
curPo = new LatLng(loc.getLatitude(), loc.getLongitude());
String curPoLog = "Lat: " + loc.getLatitude() + "Long: " + loc.getLongitude();
Log.d(TAG,"OnLocationResult: " + curPoLog);
setCurrentLocation(loc);
}
}
};
public void changeState() {
if(!state){
mMap.clear();
state = true;
Toast.makeText(this, "Recording Start", Toast.LENGTH_SHORT).show();
if(state && checkPermission()){
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
addMarkerSingle();
}
rstart.setText("Stop");
}else{
state = false;
Toast.makeText(this, "Recording Stop", Toast.LENGTH_SHORT).show();
if(!state) {
addMarkerSingle();
fusedLocationProviderClient.removeLocationUpdates(locationCallback);
}
rstart.setText("Start");
}
}
public void addMarkerSingle(){
if(checkPermission()){
fusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
double markerLat = location.getLatitude();
double markerLong = location.getLongitude();
LatLng startEnd = new LatLng(markerLat, markerLong);
mMap.addMarker(new MarkerOptions().position(startEnd));
}
});
}
}
}
'''
Hi I'm a noob to programming this is my first project after learning 3month and I have no
idea how to make it happen
I want to draw a real time foot print tracking polyline but no matter what I do, it never works I tried to get a LatLng and draw a polyline from inside LocationCallback and I also tried making a new Thread to handle it I tried in onCreate, onMapReady and everything but it never works. so I came here to ask how you guys handle these kindda stuff.
I know it's shitty code and I know I suck plz understand, among 3 month of lessons java class went for only 2weeks we never even got to using Thread part, plz help me out.
the code above is code with out any errors. I can check my location on real time and there is start marker and end marker. What I want to do is track the paths I walked and show it with polyline. not after i finish I want it to keep updating real time
Thank you for your time and help
You need to store/cache the list of LatLng you get from LocationCallback.
Create a property
private ArrayList<String> myPath = new ArrayList<>();
Now every time a new location is received in the LocationCallback you add it to the myPath and update your map
LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(#NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
List<Location> savedLocation = locationResult.getLocations();
if(savedLocation.size() > 0){
loc = savedLocation.get(savedLocation.size() - 1);
curPo = new LatLng(loc.getLatitude(), loc.getLongitude());
String curPoLog = "Lat: " + loc.getLatitude() + "Long: " + loc.getLongitude();
Log.d(TAG,"OnLocationResult: " + curPoLog);
setCurrentLocation(loc);
//add this
myPath.add(loc)
updateMap()
}
}
};
Your updateMap() method might look like this
PolylineOptions polylineOptions = new PolylineOptions();
polylineOptions.addAll(myPath);
polylineOptions.width(10f)
.color(Color.RED)
.geodesic(true);
if(mMap != null {
mMap.addPolyline(polylineOptions);
}
polyLineCollection.addPolyline(polylineOptions)
tempLine.tag = MarkerID(line.id, line.layerId , null)
try this code
//...
LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(#NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
List<Location> savedLocation = locationResult.getLocations();
Polyline polyline1 = googleMap.addPolyline(new PolylineOptions()
.clickable(false);
for(int i = 0; i<savedLocation.size; i++){
polyline1.add(new LatLng(savedLocation[i].latitude, savedLocation[i].longitude)));
}
// Store a data object with the polyline, used here to indicate an arbitrary type.
polyline1.setTag("A");
// Style the polyline.
stylePolyline(polyline1);
if(savedLocation.size() > 0){
loc = savedLocation.get(savedLocation.size() - 1);
curPo = new LatLng(loc.getLatitude(), loc.getLongitude());
String curPoLog = "Lat: " + loc.getLatitude() + "Long: " + loc.getLongitude();
Log.d(TAG,"OnLocationResult: " + curPoLog);
setCurrentLocation(loc);
}
}
};
...//
How do i assign a value to GoogleMap mMap;
it is showing null pointer exception when trying to run my activity and i think that means i have to assign a value to mMap how do i do that
this is the error i am getting
Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
this is my code
public class RideHailActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
{
private GoogleMap mMap;
private final int MY_PERMISSION_REQUEST_CODE = 7000;
private final int PLAY_SERVICES_RES_REQUEST = 7001;
private LocationRequest locationRequest;
private GoogleApiClient googleApiClient;
private Location lastLocation;
private static int UPDATE_INTERVAL = 5000;
private static int FASTEST_INTERVAL = 3000;
private static int DISPLACEMENT = 10;
DatabaseReference reference;
GeoFire geoFire;
Marker current;
MaterialAnimatedSwitch locationSwitch;
SupportMapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ride_hail);
MapsInitializer.initialize(getApplicationContext());
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
if (mapFragment != null) mapFragment.getMapAsync(this);
locationSwitch = (MaterialAnimatedSwitch)findViewById(R.id.location_switch);
locationSwitch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(boolean isOnline) {
if (isOnline) {
startLocationUpdates();
displayLocation();
}else {
stopLocationUpdates();
current.remove();
}
}
});
reference = FirebaseDatabase.getInstance().getReference("biker");
geoFire = new GeoFire(reference);
setUpLocation();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults [0] == PackageManager.PERMISSION_GRANTED) {
if (checkPlayServices()) {
buildGoogleApiClient();
createLocationRequest();
if (locationSwitch.isChecked()) displayLocation();
}
}
}
}
private void setUpLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
},MY_PERMISSION_REQUEST_CODE);
}else {
if (checkPlayServices()) {
buildGoogleApiClient();
createLocationRequest();
if (locationSwitch.isChecked()) displayLocation();
}
}
}
private void createLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setInterval(UPDATE_INTERVAL);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setSmallestDisplacement(DISPLACEMENT);
}
private void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RES_REQUEST).show();
else {
Toast.makeText(this, "This device is not supported", Toast.LENGTH_SHORT).show();
finish();
}
return false;
}
return true;
}
private void stopLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (lastLocation != null) {
if (locationSwitch.isChecked()) {
final double latitude = lastLocation.getLatitude();
final double longitude = lastLocation.getLongitude();
geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
if (current != null) current.remove();
current = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_bike))
.position(new LatLng(latitude, longitude))
.title("You"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude),15.0f));
rotateMarker(current, -360, mMap);
}
});
}
}
else {
Log.d("ERROR", "Cannot get your location");
}
}
private void rotateMarker(final Marker current, final float i, GoogleMap googleMap) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = current.getRotation();
final long duration = 1500;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float)elapsed/duration);
float rot = t*i+(1-t)*startRotation;
current.setRotation(-rot >180?rot/2:rot);
if (t<1.0) {
handler.postDelayed(this,16);
}
}
});
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
private void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
displayLocation();
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
googleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
lastLocation = location;
displayLocation();
}
}
thanks is advance
In your activity activity Xml,add a Mapview then initialize
MapView mMapView;
static final GoogleMap[] googleMap = new GoogleMap[1];
static LatLng mypos = new LatLng(0, 0);
void init_map(final Activity act, Bundle saved_inst)
{
//you need to have intialized mMapview from your layout
mMapView.onCreate(saved_inst);
mMapView.onResume(); // needed to get the map to display immediately
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap[0] = mMap;
if (ActivityCompat.checkSelfPermission(act, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(act, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
ActivityCompat.requestPermissions(act,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
99);
} else {
googleMap[0].setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
mypos = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder().target(mypos).zoom(10).build();
googleMap[0].animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
googleMap[0].setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
}
});
googleMap[0].setMyLocationEnabled(true);
googleMap[0].setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
}
});
}
you then call it like this from your oncreate
init_map(this,savedInstanceState);
this is assuming you have already set the api key from the manifest
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="your_api_key" />
to get started on geting an API key see https://developers.google.com/maps/documentation/android-sdk/get-api-key
I'm working on app which include google maps activity.
My problem is:
When I'm trying to move around in the map or zoom in & out it immediately return to my current location. Also when I search for location, new marker added at the searched location but immediately goes back to my current location.
I searched for solution but found nothing..
I hope somebody can figure it out
This is my google maps activity:
public class MapActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
public LocationManager locationManager;
public LocationListener locationListener;
public DatabaseReference mDatabase;
private FirebaseAuth mAuth;
private ArrayList<User> userArrayList = new ArrayList<>();
User useri;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
mapFragment.getMapAsync(this);
mDatabase = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(userLocation).title("המיקום שלי")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_action_marker1)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 11));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
if (Build.VERSION.SDK_INT < 23) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
mMap.setMyLocationEnabled(true);
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
//mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//MapStyleOptions style = MapStyleOptions.loadRawResourceStyle(this, R.raw.style);
//mMap.setMapStyle(style);
mMap.setMyLocationEnabled(true);
final Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
final LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
mDatabase.child("Users").child(mAuth.getCurrentUser().getUid()).child("lat").setValue(lastKnownLocation.getLatitude());
mDatabase.child("Users").child(mAuth.getCurrentUser().getUid()).child("lng").setValue(lastKnownLocation.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title("המיקום שלי")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_action_marker1)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 11));
showUsersOnMap();
}
}
}
// Search for location and show it on the map
public void onClick(View view) {
if(view.getId() == R.id.searchLocationBtn){
EditText searchBoxLocation = (EditText) findViewById(R.id.searchBoxLocation);
String location = searchBoxLocation.getText().toString();
List<Address> addressList = null;
MarkerOptions markerOptions = new MarkerOptions();
if( ! location.equals("")){
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0 ; i < addressList.size(); i++){
Address myAddress = addressList.get(i);
LatLng latLng = new LatLng(myAddress.getLatitude(), myAddress.getLongitude());
markerOptions.position(latLng);
mMap.clear();
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
}
}
}
}
// Function to show all the users on the map
public void showUsersOnMap(){
mDatabase.child("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
User user = ds.getValue(User.class);
userArrayList.add(user);
}
for (int i = 0; i < userArrayList.size(); i++) {
useri = userArrayList.get(i);
if (useri.getLat() != 0 && useri.getLng() != 0) {
MarkerOptions markerOptions = new MarkerOptions();
LatLng userlatLng = new LatLng(useri.getLat(), useri.getLng());
markerOptions.position(userlatLng);
mMap.addMarker(new MarkerOptions().position(userlatLng).title(useri.getName()).snippet(useri.getPhone())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_action_marker2)));
//mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng2,10));
}
else Toast.makeText(getApplicationContext(),"ישנה בעיה. אנא נסה להתחבר למפה שוב",Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
UPDATE:
I think I found what was the problem.
I just disabled the mMap.moveCamera() inside onLocationChanged() and it works just fine.
Now Im wondering if its ok to do so? its still keep the camera on my current location when I Drive for example?
In your search code you are adding marker every time in the loop
for (int i = 0 ; i < addressList.size(); i++){
Address myAddress = addressList.get(i);
LatLng latLng = new LatLng(myAddress.getLatitude(), myAddress.getLongitude());
markerOptions.position(latLng);
mMap.clear();
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
}
In the same code, you are moving the camera to a specific location mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11))
mMap.addMarker() will add a new marker to map.
mMap.moveCamera() will move the focus to the given location.
Check with your implementation.
Hope it helps:)
I am trying to get the current location of user and show a marker on the MAP. Here is my code
public class MapsActivity extends AppCompatActivity implements LocationListener, OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
String provider;
Location mLocation;
#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);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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;
}
mLocation=locationManager.getLastKnownLocation(provider);
if (mLocation != null) {
Log.i("Location Status: ", "Location Found");
} else if (mLocation == null) {
Log.i("Location Status: ", "Location Not Found");
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(mLocation!=null) {
try {
Double lat = mLocation.getLatitude();
Double lng = mLocation.getLongitude();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title("My Location"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 12));
} catch (Exception ex) {
Log.e("Location Error:","Exception was "+ex);
}
}
}
#Override
protected void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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.requestLocationUpdates(provider, 400, 1, this);
}
#Override
public void onLocationChanged(Location location) {
mMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("My Location"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 12));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(),"Please enable your location",Toast.LENGTH_LONG).show();
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
}
Now, the issue is that most of the times on I don't get any location, A map is shown without any marker and in the logs "Location Status:Location Not Found" which is set to be shown if location is null.
I tried to rebuild and run again. Now the location is detected on one device but it's showing the same awkward output on other devices. I want this to work every time but it's acting strange as the same code is showing two different behaviors on same device on different times with same settings.
P.S. Location is enabled on devices.
Any kind of help or tip will be appreciated. Thanks!
Try this code coded by me
Some time GPS can't able to locate your location that's why you getting null in object of mLocation
So my suggestion is to get location on bases of NETWORK_PROVIDER and also GPS_PROVIDER
here is my code
public class MapsActivity extends FragmentActivity implements LocationListener, OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
Location mLocation;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) this
.getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled) {
mLocation = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation == null) {
mLocation = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
if (locationManager != null) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (mLocation != null) {
Log.e("Location Status: ", "Location Found");
} else {
Log.e("Location Status: ", "Location Not Found");
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
/*// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));*/
if (mLocation != null) {
try {
Double lat = mLocation.getLatitude();
Double lng = mLocation.getLongitude();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title("My Location"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 12.5f));
} catch (Exception ex) {
Log.e("Location Error:", "Exception was " + ex);
}
}
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "enable your location", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Please enable your location", Toast.LENGTH_LONG).show();
}
#Override
protected void onPause() {
super.onPause();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.removeUpdates(this);
}
}
How to draw a route direction from current location to the destination using Google Maps API v2?
public class Trazo_Rutas extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient googleApiClient;
LocationRequest locationRequest;
Location lastLocation;
Marker userLocation;
private static final int Request_User_Location_Code = 99;
PlaceAutocompleteFragment placeAutoComplete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trazo__rutas);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkUserLocationPermission();
}
//Check if Google Play Services Available or not
if (!CheckGooglePlayServices()) {
Log.d("onCreate", "Finishing test case since Google Play Services are not available");
finish();
}
else {
Log.d("onCreate","Google Play Services available.");
}
//AutoComplete search bar
placeAutoComplete = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete);
placeAutoComplete.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
Log.d("Maps", "Place selected: " + place.getName());
}
#Override
public void onError(Status status) {
Log.d("Maps", "An error occurred: " + status);
}
});
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
private boolean CheckGooglePlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
0).show();
}
return false;
}
return true;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
//get latlong for corners for specified place
LatLng corner1 = new LatLng(25.64379, -103.60966);
LatLng corner2 = new LatLng(25.64317, -103.20935);
LatLng corner3 = new LatLng(25.43872, -103.61104);
LatLng corner4 = new LatLng(25.43748, -103.20866);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(corner1);
builder.include(corner2);
builder.include(corner3);
builder.include(corner4);
LatLngBounds bounds = builder.build();
//add them to builder
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
// 20% padding
int padding = (int) (width * 0.20);
//set latlng bounds
mMap.setLatLngBoundsForCameraTarget(bounds);
//move camera to fill the bound to screen
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding));
//set zoom to level to current so that you won't be able to zoom out viz. move outside bounds
mMap.setMinZoomPreference(mMap.getCameraPosition().zoom);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
public boolean checkUserLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)){
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, Request_User_Location_Code);
} else {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, Request_User_Location_Code);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case Request_User_Location_Code:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (googleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "Se requieren Permisos de Google", Toast.LENGTH_SHORT).show();
finish();
}
return;
}
}
protected synchronized void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
lastLocation = location;
if (userLocation != null) {
userLocation.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.draggable(true);
markerOptions.title("Tu ubicación");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
userLocation = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
if (googleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1100);
locationRequest.setFastestInterval(1100);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
}
This code is only for adding a marker.
How to draw the direction from current location to destination?
There are multiple ways of doing that..
Using browser, pass source and destination
public void showDirections(View view) {
final Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://maps.google.com/maps?" + "saddr="+ latitude + "," + longitude + "&daddr=" + latitude + "," + longitude));
intent.setClassName("com.google.android.apps.maps","com.google.android.maps.MapsActivity");
startActivity(intent);
}
Using Projection inside map See How to draw straight path between two points. Its not perfect solution for your issue, But you will get idea.