Move marker with gps in google map android - android

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 unable to solve my issue. The solutions are 1 and 2
Below is my onLocationChange() method
public void onLocationChanged(Location location) {
double lattitude = location.getLatitude();
double longitude = location.getLongitude();
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(lattitude, longitude);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("I am here");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
tv_loc.append("Lattitude: " + lattitude + " Longitude: " + longitude);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
Update 1 (Re-edited)
For more understanding i am adding some more code, but first i want to tell that i am using tabs in my app. The very first tab is of my map. So i am using fragments for it.
public class MyLocation extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
LocationListener{
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker=null;
TextView tv_loc;
private static View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(view != null)
{
ViewGroup viewGroupParent = (ViewGroup)view.getParent();
if(viewGroupParent !=null)
{
viewGroupParent.removeView(viewGroupParent);
}
}
try{
view = inflater.inflate(R.layout.my_location,container, false);
}catch (Exception e)
{
/* map is already there, just return view as it is */
return view;
}
// inflat and return the layout
//View rootView = inflater.inflate(R.layout.my_location, container, false);
tv_loc = (TextView)view.findViewById(R.id.textView);
mapFrag = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
return view;
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if(mGoogleApiClient !=null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
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);
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
/*double lattitude = location.getLatitude();
double longitude = location.getLongitude();
mLastLocation = location;
if (mCurrLocationMarker != null) {
//mGoogleMap.clear();
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(lattitude, longitude);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("I am here");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)).draggable(true);
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
mCurrLocationMarker.setPosition(new LatLng(lattitude,longitude));
tv_loc.append("Lattitude: " + lattitude + " Longitude: " + longitude);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}*/
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(getActivity())
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
/*super.onRequestPermissionsResult(requestCode, permissions, grantResults);*/
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED)
{
if(mGoogleApiClient == null)
{
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
//finish();
Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}}
Any help would be highly appreciated

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.

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

This can be done using CameraPosition, googleMap.animateCamera and marker movement animation using linear interpolator.
You can take a look at this tutorial here and the respective github page.
This tutorial uses google maps v2. Hope this helps.

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));
}

Inorder to animate just call this method (animateMarker) with previous location and new location along with Marker object
private Marker mCurrentMarker;
private float ZOOMLEVEL=18.0f;
private LatLng previousLatLon;
private Handler mLocalHandler;
private GoogleMap mGoogleMap;
public void animateMarker(final Marker marker, final LatLng toPosition,final LatLng fromPosition) {
final long duration = 500;
final Interpolator interpolator = new LinearInterpolator();
mLocalHandler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - mStartTime;
float t = interpolator.getInterpolation((float) elapsed
/ duration);
marker.setPosition(toPosition);
marker.setAnchor(Constants.MAPANCHOR, Constants.MAPANCHOR);
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(toPosition, ZOOMLEVEL));
if (t < 1.0) {
// Post again 16ms later.
mLocalHandler.postDelayed(this, 16);
} else {
marker.setVisible(true);
}
}
}
});
previousLatLon=toPosition;// reassign the previous location to current location
}

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

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;
}
}}

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);
}

Related

How to set an error message when search an invalid location in maps activity

public class MapsActivity extends AppCompatActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
MarkerOptions markerOptions;
EditText ed_place;
Button btn_getLocation;
Geocoder geocoder;
List<Address> addresses;
double lat, lng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
ed_place = findViewById(R.id.ed_place);
btn_getLocation = findViewById(R.id.btn_getLocation);
getSupportActionBar().setTitle("Map Location Activity");
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
geocoder = new Geocoder(this, Locale.getDefault());
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google Play Services
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
} else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
btn_getLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
addresses = geocoder.getFromLocationName(ed_place.getText().toString(), 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses == null) {
Toast.makeText(getApplicationContext(), "Invalid address", Toast.LENGTH_SHORT).show();
} else {
mGoogleMap.clear();
lat = addresses.get(0).getLatitude();
lng = addresses.get(0).getLongitude();
LatLng position = new LatLng(lat, lng);
markerOptions = new MarkerOptions();
markerOptions.position(position);
markerOptions.snippet("Latitude" + lat + "Longitude" + lng);
mGoogleMap.addMarker(markerOptions);
CameraUpdate updatePosition = CameraUpdateFactory.newLatLng(position);
mGoogleMap.moveCamera(updatePosition);
Toast.makeText(getApplicationContext(), lat + " :" + lng, Toast.LENGTH_SHORT).show();
}
}
});
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
}
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
}
This is my map activity.I use geocoding to get latitude and longitude of the location and mark it.When i search a wrong location app crashes.How to set an error message when i search a invalid location.
Use this code
try {
Geocoder geoCoder = new Geocoder(this);
List<Address> matches = geoCoder.getFromLocation(lat, lng, 1);
Address bestMatch = (matches.isEmpty() ? null : matches.get(0));
if (bestMatch != null) {
LatLng ltlng= new LatLng(bestMatch.getLatitude(),bestMatch.getLongitude());
Searchmarker = mMap.addMarker(new MarkerOptions().position(ltlng));
mMap.animateCamera(CameraUpdateFactory.newLatLng(ltlng));
} else {
Toast.makeText(this, "No result found", Toast.LENGTH_LONG).show();
}
}catch (Exception e){
Toast.makeText(this, "Error search :- Wrong input", Toast.LENGTH_LONG).show();
}
Yes it happens whenever we try to search a wrong location on map , for that you can put the searching code for places using geocoder into try catch block and handle the exception and show a message to the user for invalid search.

Unable to add markers - only Location or Markers visible at once

I've a pretty large working app, I've implemented myLocation in MapLocation.class which extends Fragment.
Everything was working fine, my whole list of markers were displaying perfectly but after implementation of myLocation, a strange condition occurred.
Condition is on first run/install (after uninstalling the previous one or clearing the data), markers are displayed perfectly but neither myLocation works nor the myLocation icon appears, even it asks for permission.
On second run through studio or launching app again after clearing from recents, location works perfectly with the icon on its place but Markers become invisible. Invisible because camera focuses on Marker's place instead of myLocation as in the code.
Code is as follows:
public class MetroLocation extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
MapView mMapView;
private GoogleMap googleMap;
ArrayList<Double> arLat = new ArrayList<>();
ArrayList<Double> arLong = new ArrayList<>();
ArrayList<String> arName=new ArrayList<>();
ArrayList<String> arLine = new ArrayList<>();
double lng;
double lat;
LatLng latLng;
Marker mCurrLocation;
Location mLastLocation;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
private Cursor Lat;
private Cursor Long;
private Cursor Stations;
private MyDatabase db;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_metro_location, container, false);
mMapView = v.findViewById(R.id.mapLocation);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();
db = new MyDatabase(getActivity());
Lat = db.getLat();
Long = db.getLong();
Stations = db.getStation();
Cursor line = db.getMetroLine();
for(Lat.moveToFirst(); !Lat.isAfterLast(); Lat.moveToNext()) {
arLat.add(Lat.getDouble(0));
}
for(Long.moveToFirst(); !Long.isAfterLast(); Long.moveToNext()) {
arLong.add(Long.getDouble(0));
}
for(Stations.moveToFirst(); !Stations.isAfterLast(); Stations.moveToNext()) {
arName.add(Stations.getString(0));
}
for(line.moveToFirst(); !line.isAfterLast(); line.moveToNext()) {
arLine.add(line.getString(0));
}
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(this);
return v;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
#Override
public void onDestroy() {
super.onDestroy();
Lat.close();
Long.close();
Stations.close();
db.close();
mMapView.onDestroy();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocation != null) {
mCurrLocation.remove();
}
latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(3000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mLocationRequest.setSmallestDisplacement(2F);
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
googleMap.clear();
latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocation = googleMap.addMarker(markerOptions);
}
if (ContextCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(getActivity(),"Connection Suspended",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(getActivity(),"Connection Failed",Toast.LENGTH_SHORT).show();
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(getActivity())
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
googleMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
}
}
}
}
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setAllGesturesEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
for(int j= 0;j<arLat.size();j++) {
double lat1 = arLat.get(j);
double long1 = arLong.get(j);
String name = arName.get(j);
String snippet = "Metro Station"+ " Line : " + arLine.get(j);
LatLng latLng = new LatLng(lat1, long1);
googleMap.addMarker(new MarkerOptions().position(latLng).title(name).snippet(snippet).flat(true).icon(
BitmapDescriptorFactory.fromResource(R.drawable.green)));
}
int i = arLat.size() / 2;
lat = arLat.get(i);
lng = arLong.get(i);
LatLng latLng1 = new LatLng(lat, lng);
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng1).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
googleMap.setMyLocationEnabled(true);
} else {
checkLocationPermission();
}
} else {
buildGoogleApiClient();
googleMap.setMyLocationEnabled(true);
}
if (mMapView != null &&
mMapView.findViewById(Integer.parseInt("1")) != null) {
View locationButton = mMapView.findViewWithTag("GoogleMapMyLocationButton");
View locationButton1 = mMapView.findViewWithTag("GoogleMapCompass");
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
layoutParams.setMargins(0, 0, 40, 253);
RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) locationButton1.getLayoutParams();
layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0);
layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_TOP,0);
layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
layoutParams1.bottomMargin = 100;
}
}
}
If there's something my code has wrong, please help.
EDIT - I've experienced that marker appears for a flash and then disappears. Everything else remains same. Also, a restart is required for location and it's button to appear.

When placing markers on map activity the camera move to the marker

I am using nearbyPlaces web service and I have a problem, I am putting a marker on the map for each pharmacie that it finds, but the camera always move to the marker and it does not stay in the current user position dot.
this is the code
public class GetNearbyPlacesData extends AsyncTask<Object, String, String> {
String googlePlacesData;
GoogleMap mMap;
String url;
#Override
protected String doInBackground(Object... params) {
try {
Log.d("GetNearbyPlacesData", "doInBackground entered");
mMap = (GoogleMap) params[0];
url = (String) params[1];
DownloadUrl downloadUrl = new DownloadUrl();
googlePlacesData = downloadUrl.readUrl(url);
Log.d("GooglePlacesReadTask", "doInBackground Exit");
} catch (Exception e) {
Log.d("GooglePlacesReadTask", e.toString());
}
return googlePlacesData;
}
#Override
protected void onPostExecute(String result) {
Log.d("GooglePlacesReadTask", "onPostExecute Entered");
List<HashMap<String, String>> nearbyPlacesList = null;
DataParser dataParser = new DataParser();
nearbyPlacesList = dataParser.parse(result);
ShowNearbyPlaces(nearbyPlacesList);
Log.d("GooglePlacesReadTask", "onPostExecute Exit");
}
private void ShowNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList) {
for (int i = 0; i < nearbyPlacesList.size(); i++) {
Log.d("onPostExecute","Entered into showing locations");
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
HashMap<String, String> googlePlace = nearbyPlacesList.get(i);
double lat = Double.parseDouble(googlePlace.get("lat"));
double lng = Double.parseDouble(googlePlace.get("lng"));
String placeName = googlePlace.get("place_name");
String vicinity = googlePlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(placeName + " : " + vicinity);
mMap.addMarker(markerOptions);
//markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(14.0f));
}
}
}
public class NearbyPharmaciesFragment extends Fragment implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
double latitude;
double longitude;
private int PROXIMITY_RADIUS = 1000;
LocationManager locationManager;
GoogleApiClient mGoogleApiClient;
AlertDialog alert = null;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_nearby_pharmacies, container, false);
locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);
if ( !locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
AlertNoGps();
}
// Inflate the layout for this fragment
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
//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.");
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
//SupportMapFragment mapFragment = (SupportMapFragment) getActivity().getSupportFragmentManager()
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return rootView;
}
private boolean CheckGooglePlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(getActivity());
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(getActivity(), result,
0).show();
}
return false;
}
return true;
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
private String getUrl(double latitude, double longitude, String nearbyPlace) {
StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=" + latitude + "," + longitude);
googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
googlePlacesUrl.append("&type=" + nearbyPlace);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + "API_KEY");
Log.d("getUrl", googlePlacesUrl.toString());
return (googlePlacesUrl.toString());
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
Log.d("onLocationChanged", "entered");
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
float zoom=11.0f;
mMap.animateCamera(CameraUpdateFactory.zoomTo(zoom));
//Toast.makeText(getActivity(),"Your Current Location", Toast.LENGTH_LONG).show();
mMap.clear();
String pharmacy = "pharmacy";
String url = getUrl(latitude, longitude, pharmacy);
Object[] DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
if (new InternetWatcher().isConnectedToNetwork(getActivity())){
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
getNearbyPlacesData.execute(DataTransfer);
}else{
Toast.makeText(getActivity(), R.string.internet_para_ver_farmacias, Toast.LENGTH_LONG).show();
getActivity().onBackPressed();
}
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d("onLocationChanged", "Removing Location Updates");
}
Log.d("onLocationChanged", "Exit");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
private void AlertNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.gps_no_activado_dialogo)
.setCancelable(false)
.setPositiveButton(R.string.si_gps, new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
getActivity().onBackPressed();
Toast.makeText(getActivity(), R.string.gps_Required, Toast.LENGTH_LONG).show();
dialog.cancel();
}
});
alert = builder.create();
alert.show();
}
Any help please? thanks in advance
Your posted code includes these lines:
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(14.0f));
Sounds like you don't want to move the camera, so you should probably delete them.

markerOption didnt move with current marker in google Map

I try to make app that works with google map .in my map i have currentmarker and markeroption,when i move current marker(Blue Point)makes move but markeroption(redflag,with CurrenrtLocation tag)didnt get move with current marker(Blue Point).how can i make markeroption that move with current marker in googlemap.Thanks
This picture shows when i move current marker move but markeroption didnt move
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapbutton);
// 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);}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google Play Services
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);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location)
{
if (location != null) {
// ---Get current location latitude, longitude---
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
LatLng currentLatLng = new LatLng(location.getLatitude(), location.getLongitude());
Marker currentLocationMarker = mMap.addMarker(new MarkerOptions().position(currentLocation).title("Current Location"));
// Move the camera instantly to hamburg with a zoom of 15.
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 15));
// Zoom in, animating the camera.
if (!zoomed) {
mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
zoomed = true;
}
if (!firstPass){
currentLocationMarker.remove();
}
firstPass = false;
Toast.makeText(this,"Latitude = "+
location.getLatitude() + "" +"Longitude = "+ location.getLongitude(),
Toast.LENGTH_LONG).show();
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission was granted.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
//You can add here other case statements according to your requirement.
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}}
Make currentLocationMarker a class attribute, actually you are removing it just after adding it.
class YourActivity extends Activity implements onMapReady {
private Marker currentLocationMarker;
#Override
public void onLocationChanged(Location location){
if ( location != null ){
if ( currentLocationMarker == null ){
currentLocationMarker = mMap.addMarker(new MarkerOptions().position(currentLocation).title("Current Location"));
}else{
currentLocationMarker.setPosition(new LatLng(location.getLatitude(), location.getLongitude()));
}
}
}
}
Explanations
In your code you add a marker the first time the location change, and then each time location change you add a new one and delete it immediatly with :
Marker currentLocationMarker = mMap.addMarker(new MarkerOptions().position(currentLocation).title("Current Location"));
//...
if (!firstPass){
currentLocationMarker.remove();
}
The best thing to do is to keep reference to the marker you create, and instead of removing it a creating a new one, just update its position, that what I'm doing in my code, if marker doesn't exist (currentLocationMarker == null) then create it and keep reference in class. If marker exist (the else) then just update its position.

How to show current position marker on Map in android?

I am developing an application in which I want to display current location using marker in my map. I am using Google Map v2. Here I can display Map and marker when GPS is off ,but not visible any marker on map when GPS on. My requirement is display marker on map with current position
I tried like this,
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
//locationManger.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
this);
ArrayList<HashMap<String, String>> arl = (ArrayList<HashMap<String, String>>)
getIntent().getSerializableExtra("arrayList");
if(location!=null){
double latitude = location.getLatitude();
double langitude = location.getLongitude();
myPosition = new LatLng(latitude, langitude);
CameraPosition position= new CameraPosition.Builder().
target(myPosition).zoom(17).bearing(19).tilt(30).build();
//_googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(position));
_googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(position));
_googleMap.addMarker(new
MarkerOptions().position(myPosition).title("start"));
}
Use below code it worked for me:
#Override
public void onLocationChanged(Location location) {
map.clear();
MarkerOptions mp = new MarkerOptions();
mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
mp.title("my position");
map.addMarker(mp);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 16));
}
Try this,it is showing current location:
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// to set current location
googleMap.setMyLocationEnabled(true);
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
Try this:-
private void initMap() {
if (googleMap != null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// to set current location
googleMap.setMyLocationEnabled(true);
Marker pos_Marker = googleMap.addMarker(new MarkerOptions().position(starting).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_laumcher)).title("Starting Location").draggable(false));
pos_Marker.showInfoWindow();
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(START_locationpoint, 10));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15),2000, null);
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
Use this. It works for me.
#Override
public void onLocationChanged(Location location) {
map.clear();
mp1 = new MarkerOptions();
mp1.position(new LatLng(location.getLatitude(),
location.getLongitude()));
mp1.draggable(true);
mp1.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
map.addMarker(mp1);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location
.getLongitude()), 20));
}
You may try this:
public class MapsActivity extends AppCompatActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
private Circle mCircle;
double radiusInMeters = 100.0;
int strokeColor = 0xffff0000; //Color Code you want
int shadeColor = 0x44ff0000; //opaque red fill
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
getSupportActionBar().setTitle("Map Location Activity");
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
//mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
#Override
public void onLocationChanged(Location location)
{
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
CircleOptions addCircle = new CircleOptions().center(latLng).radius(radiusInMeters).fillColor(shadeColor).strokeColor(strokeColor).strokeWidth(8);
mCircle = mGoogleMap.addCircle(addCircle);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
Location mlocation;
#Override
public void onLocationChanged(Location location) {
// Add a marker in Sydney and move the camera
mLocation = location;
LatLng myLocation = new LatLng(mLocation.getLatitude(), mLocation.getLongitude());
mMap.addMarker(new MarkerOptions()
.position(myLocation)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
.title("My Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation));
Log.d("location", "Latitude:" + mLocation.getLatitude() + "\n" + "Longitude:" + mLocation.getLongitude());
}
for getting current position you can use getLastKnownLocation() method on LocationManager:
locationManager = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
Location currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LatLng current = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
googleMap.addMarker(new MarkerOptions().position(current).title("Marker Label").snippet("Marker Description"));
CameraPosition cameraPosition = new CameraPosition.Builder().target(current).zoom(14).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
float lat = (float) latLng.latitude;
float lon = (float) latLng.longitude;
mMap.clear();
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker in " + lat +" "+ lon));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
});

Categories

Resources