I want to make move of the marker in GOOGLE MAP
while gps
location changes just like in UBER
app. I have found some solutions but unab
Hope this Answer Will help you.instead of gps use Google Fused Api Read Documentation Here For Fused Api and Read this Answer how To Make Bus Marker Move
try this tutorial link for better understanding Fused Api Example
Use this:
implement LocationListener ,GoogleMap.OnMyLocationChangeListener
in your map activity and then use location change Listener
@Override
public void onMyLocationChange(Location location) {
//mMap.clear //if you want refresh map remove comment
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude =location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude); //your_text_view.settext(latitude+","+longtitudde)
// Showing the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.destination_marker)).position(latLng).title(maping_status));
// Zoom in the Google Map
mMap.animateCamera(CameraUpdateFactory.zoomTo(20));
}
You can use below code to update position of the Marker
public void onLocationChanged(Location location) {
double lattitude = location.getLatitude();
double longitude = location.getLongitude();
//Place current location marker
LatLng latLng = new LatLng(lattitude, longitude);
if(mCurrLocationMarker!=null){
mCurrLocationMarker.setPosition(latLng);
}else{
mCurrLocationMarker = mGoogleMap.addMarker(new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
.title("I am here");
}
tv_loc.append("Lattitude: " + lattitude + " Longitude: " + longitude);
gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
You don't need to clear map every time. You can do it by Marker object that is returned when adding Marker to Map. Hope it will help you.
If you're still looking for the solution, hope this https://www.youtube.com/watch?v=WKfZsCKSXVQ will help you. I've used this in one of my apps and it helps animating the marker from one location to other location. Source code can be grabbed here https://gist.github.com/broady/6314689.
You might need to add rotation to your marker to show the exact direction of the marker. Following is the block of code that I'm using to find bearing.
private float bearingBetweenLatLngs(LatLng begin, LatLng end) {
Location beginL = convertLatLngToLocation(begin);
Location endL = convertLatLngToLocation(end);
return beginL.bearingTo(endL);
}
First of All implement LocationListener in your Activity then
if you need to show only one Marker(update position of Marker), use this :
private Marker currentPositionMarker = null;
@Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(14).build();
// mMap.clear(); // Call if You need To Clear Map
if (currentPositionMarker == null)
currentPositionMarker = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
.position(latLng)
.zIndex(20));
else
currentPositionMarker.setPosition(latLng);
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
or if you want to add a new marker every time :
@Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(14).build();
mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
.position(latLng)
.zIndex(20));
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
if location was changed rapidly, it would take a couple of seconds for your app to update its location marker
In manifest add these lines
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
and then use this class
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
GoogleMap mgoogleMap;
GoogleApiClient mgoogleApi;
Context context;
Marker marker;
LocationRequest locationrequest;
public static final int map=1111;
public static final int coarse=1112;
@Override
protected void onCreate(Bundle savedInstanceState) {
if (googleServiceAvalable()) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
checkReadPermission();
checkCoarsePermission();
initMap();
} else {
}
}
public boolean googleServiceAvalable() {
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int isavailable = api.isGooglePlayServicesAvailable(this);
if (isavailable == ConnectionResult.SUCCESS) {
return true;
} else if (api.isUserResolvableError(isavailable)) {
Dialog dialog = api.getErrorDialog(this, isavailable, 0);
dialog.show();
} else {
Toast.makeText(this, "cant connect to play services", Toast.LENGTH_LONG).show();
}
return false;
}
private void initMap() {
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.fragment);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mgoogleMap = googleMap;
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) {
// 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;
}
}
mgoogleMap.setMyLocationEnabled(true);
if(checkCoarsePermission() && checkReadPermission()){
mgoogleApi = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mgoogleApi.connect();
}else {
checkReadPermission();
checkCoarsePermission();
}
}
private void goToLocation(double latitude, double longitude, int i) {
LatLng ll = new LatLng(latitude, longitude);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, i);
mgoogleMap.animateCamera(update);
if(marker !=null){
marker.remove();
}
MarkerOptions options =new MarkerOptions()
.title("Test")
.draggable(true)
.position(new LatLng(latitude,longitude ));
marker= mgoogleMap.addMarker(options);
}
@Override
public void onConnected(@Nullable Bundle bundle) {
locationrequest = new LocationRequest().create();
locationrequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationrequest.setInterval(1000);
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;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mgoogleApi, locationrequest, this);
Toast.makeText(context,"Location Connected and ready to publish",Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionSuspended(int i) {
Toast.makeText(context,"Location Connection Suspended",Toast.LENGTH_SHORT);
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Toast.makeText(context,"Location Connection Failed"+connectionResult.getErrorMessage(),Toast.LENGTH_SHORT);
}
@Override
public void onLocationChanged(Location location) {
if(location==null){
Toast.makeText(context,"Cant Find User Location",Toast.LENGTH_SHORT);
}else {
LatLng ll=new LatLng(location.getLatitude(),location.getLongitude());
goToLocation(ll.latitude,ll.longitude,18);
}
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public boolean checkReadPermission() {
int currentAPIVersion = Build.VERSION.SDK_INT;
if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MainActivity.this);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("Read Internal Storage permission required to display images!!!");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, map);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity) MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, map);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public boolean checkCoarsePermission() {
int currentAPIVersion = Build.VERSION.SDK_INT;
if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MainActivity.this);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("Read Internal Storage permission required to display images!!!");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) MainActivity.this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}, coarse);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity) MainActivity.this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}, coarse);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
switch (requestCode) {
case map:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
Toast.makeText(context,"You have to give permission",Toast.LENGTH_SHORT).show();
}
break;
case coarse:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
Toast.makeText(context,"You have to give permission",Toast.LENGTH_SHORT).show();
}
break;
}
}}