i am using google maps v2 and i'm new to it, what i'm doing is i open the map by pressing a button, the thing is that i need to pinpoint a certain location on the map and get its longitude and latitude to display the map again in another activity with the pinpointed location.
i'm a bit confused on how to manipulate google maps and how to display it in other activity, what do i need to add to the following code bellow??
here is my map code:
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
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.setMyLocationEnabled(true);
Location currentLocation = mMap.getMyLocation();
if (currentLocation != null) {
updateLocation(currentLocation);
} else {
Log.d(getClass().getName(), "Current location is NULL");
}
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
} else {
LocationListener locationListener = new MyLocationListener();
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#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 Activity#requestPermissions for more details.
return;
}
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1, locationListener);
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 1, locationListener);
Location locationGPS = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location locationNet = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location loc;
long GPSLocationTime = 0;
if (null != locationGPS) {
GPSLocationTime = locationGPS.getTime();
}
long NetLocationTime = 0;
if (null != locationNet) {
NetLocationTime = locationNet.getTime();
}
if (0 < GPSLocationTime - NetLocationTime) {
loc = locationGPS;
} else {
loc = locationNet;
}
if (loc != null) {
updateLocation(loc);
}
//LatLng sydney = new LatLng(-33.867, 151.206);
}
}
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
updateLocation(loc);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
public void updateLocation(Location loc) {
Toast.makeText(
getBaseContext(),
"Location changed: Lat: " + loc.getLatitude() + " Lng: "
+ loc.getLongitude(), Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " + loc.getLongitude();
Log.v(getClass().getName(), longitude);
String latitude = "Latitude: " + loc.getLatitude();
Log.v(getClass().getName(), latitude);
/*------- To get city name from coordinates -------- */
String cityName = null;
Geocoder gcd = new Geocoder(this, Locale.ENGLISH);
List<Address> addresses;
/*try {
addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
if (addresses.size() > 0) {
Log.d(getClass().getSimpleName(), (addresses.get(0).getLocality() == null ? "Null" : addresses.get(0).getLocality()));
cityName = addresses.get(0).getLocality();
}
} catch (IOException e) {
e.printStackTrace();
}*/
String s = longitude + "\n" + latitude + "\n\nMy Current City is: "
+ cityName;
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
LatLng myLocation = new LatLng(loc.getLatitude(), loc.getLongitude());
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.setMyLocationEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLocation, 13));
mMap.addMarker(new MarkerOptions()
.title(cityName)
.snippet("My Location")
.position(myLocation));
}
}
If by pinpoint you mean tap to add a point on the map then use the code :
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
// TODO Auto-generated method stub
mMap.clear();
mMap.addMarker(new MarkerOptions().position(point));
//To Send this point to second mapsActivity
Intent i=new Intent(MapsActivity.this,MapsActivity1.class);
Bundle args = new Bundle();
args.putParcelable("POINT", point);
i.putExtra("bundle",args);
startActivity(i);
}
});
To create another map activity just right click on "app" folder->New->Google->Google MapsActivity.
A new Activity will be added.
Inside the new MapsActivity's onCreate() get this point by :
Bundle bundle = getIntent().getParcelableExtra("bundle");
LatLng markerPoint = bundle.getParcelable("POINT");
Inside the second mapsActivity's setUpMapIfNeeded() :
mMap.addMarker(new MarkerOptions().position(markerPoint));
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(markerPoint, 10));
Here 10 is the zoomlevel adjust it accordingly.
You can get LatLongs of marker by marker.getPosition(). just send these values via intent extras to your next activity and display it again on the map in that activity.
Related
I have defined a service (i.e. LocationService ) which gives me users's current latitude and longitude as an intent extras to my_activity. Now , I want to use them to show current location on map (using Google maps) . I passed these latlng in mMap.animateCamera and mMap.moveCamera methods but they are not showing any Marker or zoom in to the current location . Please tell me if I am doing anything wrong .
Code for the LocationService and my MainActivity is pasted below :
LocationServices.java
public class LocationServicesForLocationUpdates extends Service implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{
private static final String TAG = LocationServicesForLocationUpdates.class.getSimpleName();
public static final String ACTION_LOCATION_BROADCAST
= LocationServicesForLocationUpdates.class.getName() + "LocationBroadcast";
public static final String EXTRA_LATITUDE = "extra_latitude";
public static final String EXTRA_LONGITUDE = "extra_longitude";
private GoogleApiClient mLocationClient;
private LocationRequest mLocationRequest = new LocationRequest();
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mLocationClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(3000);
mLocationClient.connect();
// return super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
/*
* LOCATION CALLBACKS
*/
#Override
public void onConnected(Bundle dataBundle) {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// 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.
Log.d(TAG, "== Error On onConnected() Permission not granted");
//Permission not granted by user so cancel the further execution.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest ,this);
Log.d(TAG, "Connected to Google API");
}
//to get the location change
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Location changed");
if (location != null) {
Log.d(TAG, "== location != null");
//Send result to activities
sendMessageToUI(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
}
}
private void sendMessageToUI(String lat, String lng) {
Log.d(TAG, "Sending info...");
Intent intent = new Intent(ACTION_LOCATION_BROADCAST);
intent.putExtra(EXTRA_LATITUDE, lat);
intent.putExtra(EXTRA_LONGITUDE, lng);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
New MainActivity.java
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback{
private TextView mLatlngTxtVu , mAddressTxtVu;
private boolean mAlreadyStartedService;
private static final String TAG = ParentHomeActivity.class.getSimpleName();
private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
private GoogleMap mGoogleMap;
Double mlattitude , mlongitude;
Marker mCurrentMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parent_home);
Log.d(TAG, "onCreate: Called");
mLatlngTxtVu = (TextView) findViewById(R.id.latlng_txtview);
mAddressTxtVu = (TextView) findViewById(R.id.address_txtvu);
LocalBroadcastManager.getInstance(this).registerReceiver(
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mlattitude = Double.parseDouble(intent.getStringExtra(LocationServicesForLocationUpdates.EXTRA_LATITUDE));
mlongitude = Double.parseDouble(intent.getStringExtra(LocationServicesForLocationUpdates.EXTRA_LONGITUDE));
Log.d("latlng", "onReceive: " + mlongitude + mlattitude);
if (mlattitude != null && mlongitude != null) {
mLatlngTxtVu.setText("Latitude : " + mlattitude + "Longitude: " + mlongitude);
}
}
}, new IntentFilter(LocationServicesForLocationUpdates.ACTION_LOCATION_BROADCAST)
);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.main_map);
mapFragment.getMapAsync(MainActivity.this);
}
#Override
protected void onResume() {
super.onResume();
checkGooglePlayServices();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap ;
Log.d(TAG, "onMapReady: called");
Log.d("coord", mlattitude + " " + mlongitude);
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;
}
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setMapToolbarEnabled(false);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(mlattitude, mlongitude)) // Sets the center of the map to location user
.zoom(14) // Sets the zoom
.bearing(0) // Sets the orientation of the camera to east
.tilt(90) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
LatLng latLng = new LatLng(mlattitude , mlongitude);
mGoogleMap.addMarker(new MarkerOptions().position(latLng).title("YOU"));
// mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
/* CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(mlattitude, mlongitude)) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));*/
}
private void checkGooglePlayServices() {
//Check whether this user has installed Google play service which is being used by Location updates.
if (isGooglePlayServicesAvailable()) {
//Passing null to indicate that it is executing for the first time.
checkAndPromptForInternetConnection(null);
} else {
Toast.makeText(getApplicationContext(), "Play services Not Available", Toast.LENGTH_LONG).show();
}
}
private boolean checkAndPromptForInternetConnection(DialogInterface dialog) {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo == null || !activeNetworkInfo.isConnected()) {
promptInternetConnect();
return false;
}
if (dialog != null) {
dialog.dismiss();
}
//Yes there is active internet connection. Next check Location is granted by user or not.
if (checkPermissions()) { //Yes permissions are granted by the user. Go to the next step.
startedLocationServices();
} else { //No user has not granted the permissions yet. Request now.
requestPermissions();
}
return true;
}
/**
* Step 3: Start the Location Monitor Service
*/
private void startedLocationServices() {
//And it will be keep running until you close the entire application from task manager.
//This method will executed only once.
if (!mAlreadyStartedService && mLatlngTxtVu != null) {
mLatlngTxtVu.setText("Running ");
//Start location sharing service to app server.........
Intent intent = new Intent(this, LocationServicesForLocationUpdates.class);
startService(intent);
mAlreadyStartedService = true;
//Ends................................................
}
}
/**
* Show A Dialog with button to refresh the internet state.
*/
private void promptInternetConnect() {
AlertDialog.Builder builder = new AlertDialog.Builder(ParentHomeActivity.this);
builder.setTitle("No internet connection");
builder.setMessage("Please Check your internet connection");
String positiveText = "Refresh";
builder.setPositiveButton(positiveText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Block the Application Execution until user grants the permissions
if (checkAndPromptForInternetConnection(dialog)) {
//Now make sure about location permission.
if (checkPermissions()) {
//Step 2: Start the Location Monitor Service
//Everything is there to start the service.
startedLocationServices();
} else if (!checkPermissions()) {
requestPermissions();
}
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
/**
* Return the availability of GooglePlayServices
*/
public boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(this);
if (status != ConnectionResult.SUCCESS) {
if (googleApiAvailability.isUserResolvableError(status)) {
googleApiAvailability.getErrorDialog(this, status, 2404).show();
}
return false;
}
return true;
}
/**
* Return the current state of the permissions needed.
*/
private boolean checkPermissions() {
int permissionState1 = ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION);
int permissionState2 = ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION);
return permissionState1 == PackageManager.PERMISSION_GRANTED && permissionState2 == PackageManager.PERMISSION_GRANTED;
}
/**
* Start permissions requests.
*/
private void requestPermissions() {
boolean shouldProvideRationale =
ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.ACCESS_FINE_LOCATION);
boolean shouldProvideRationale2 =
ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION);
// Provide an additional rationale to the img_user. This would happen if the img_user denied the
// request previously, but didn't check the "Don't ask again" checkbox.
if (shouldProvideRationale || shouldProvideRationale2) {
Log.i(TAG, "Displaying permission rationale to provide additional context.");
showSnackbar(R.string.grantPermission,
android.R.string.ok, new View.OnClickListener() {
#Override
public void onClick(View view) {
// Request permission
ActivityCompat.requestPermissions(ParentHomeActivity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
});
} else {
Log.i(TAG, "Requesting permission");
// Request permission. It's possible this can be auto answered if device policy
// sets the permission in a given state or the img_user denied the permission
// previously and checked "Never ask again".
ActivityCompat.requestPermissions(ParentHomeActivity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
}
/**
* Shows a {#link Snackbar}.
*
* #param mainTextStringId The id for the string resource for the Snackbar text.
* #param actionStringId The text of the action item.
* #param listener The listener associated with the Snackbar action.
*/
private void showSnackbar(final int mainTextStringId, final int actionStringId,
View.OnClickListener listener) {
Snackbar.make(
findViewById(android.R.id.content),
getString(mainTextStringId),
Snackbar.LENGTH_INDEFINITE)
.setAction(getString(actionStringId), listener).show();
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
Log.i(TAG, "onRequestPermissionResult");
if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
if (grantResults.length <= 0) {
// If img_user interaction was interrupted, the permission request is cancelled and you
// receive empty arrays.
Log.i(TAG, "User interaction was cancelled.");
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Permission granted, updates requested, starting location updates");
startedLocationServices();
} else {
// Permission denied.
// Notify the img_user via a SnackBar that they have rejected a core permission for the
// app, which makes the Activity useless. In a real app, core permissions would
// typically be best requested during a welcome-screen flow.
// Additionally, it is important to remember that a permission might have been
// rejected without asking the img_user for permission (device policy or "Never ask
// again" prompts). Therefore, a img_user interface affordance is typically implemented
// when permissions are denied. Otherwise, your app could appear unresponsive to
// touches or interactions which have required permissions.
showSnackbar(R.string.permissionDenied,
R.string.settings, new View.OnClickListener() {
#Override
public void onClick(View view) {
// Build intent that displays the App settings screen.
Intent intent = new Intent();
intent.setAction(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package",
BuildConfig.APPLICATION_ID, null);
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
}
#Override
public void onDestroy() {
//Stop location sharing service to app server.........
stopService(new Intent(this, LocationServicesForLocationUpdates.class));
mAlreadyStartedService = false;
//Ends................................................
super.onDestroy();
}
}
Feel free to ask any queries in case you don't understand my problem and tell me the correct approach to solve my problem . I am new to android app development.
in onMapReady() please create a new LatLng position and add it in as MarkerOption
#Override
public void onMapReady(GoogleMap googleMap) {
.......
.......
// make sure you are getting your latitude and longitude string value
mlattitude = Double.parseDouble(intent.getStringExtra(LocationServicesForLocationUpdates.EXTRA_LATITUDE));
mlongitude = Double.parseDouble(intent.getStringExtra(LocationServicesForLocationUpdates.EXTRA_LONGITUDE));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(mLattitude,mlongitude)) // My position
.zoom(14) // Zoom Level
.bearing(0) // camera position, (0 north , 180 south )
.tilt(90) // Inclinaison de la camera
.build();
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
LatLng position = new LatLng(mlattitude,mlongitude);
googleMap.addMarker(new MarkerOptions().position(position)
.title("my marker"));
}
edit
Do not forget to call getMapAsync in your onReceive() method
LocalBroadcastManager.getInstance(this).registerReceiver(
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mlattitude = Double.parseDouble(intent.getStringExtra(LocationServicesForLocationUpdates.EXTRA_LATITUDE));
mlongitude = Double.parseDouble(intent.getStringExtra(LocationServicesForLocationUpdates.EXTRA_LONGITUDE));
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.main_map);
mapFragment.getMapAsync(MainActivity.this);
Log.d("latlng", "onReceive: " + mlongitude + mlattitude);
if (mlattitude != null && mlongitude != null) {
mLatlngTxtVu.setText("Latitude : " + mlattitude + "Longitude: " + mlongitude);
}
}
}, new IntentFilter(LocationServicesForLocationUpdates.ACTION_LOCATION_BROADCAST)
);
);
You can do like that :
public class MapsMarkerActivity extends AppCompatActivity
implements OnMapReadyCallback {
// Include the OnCreate() method here too, as described above.
#Override
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney, Australia,
// and move the map's camera to the same location.
LatLng sydney = new LatLng(-33.852, 151.211);
googleMap.addMarker(new MarkerOptions().position(sydney)
.title("Marker in Sydney"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
The code is from the Google documentation page
Whenever I run my Android code and my map opens on my real device (not on the emulator), it is not pointing anywhere and it just shows a map of the world zoomed out instead of the user's location. I have tried various various combinations to get this right and nothing has helped me.
Below is the code I tried for getting the user's and still the behavior remains the same. I tried changing GPS_SERVICE to NETWORK_PROVIDER and still no help. What might be the solution here?
The device I am using for testing here is One Plus 3.
Manifest.xml:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
MapsActivity:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
#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.NETWORK_PROVIDER, 0, 0, locationListener);
}
}
}
}
#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);
}
/**
* 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_HYBRID);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// Add a marker on user's location and move the camera.
LatLng yourLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(yourLocation).title("Your Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(yourLocation));
// To get the address of the user location.
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
// 1 - represents only one location is required.
List<Address> listAddresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if(listAddresses != null && listAddresses.size() > 0) {
Log.i("PlaceInfo", listAddresses.get(0).toString());
String address = "";
if(listAddresses.get(0).getSubThoroughfare() != null) {
address += listAddresses.get(0).getSubThoroughfare() + " ";
}
if(listAddresses.get(0).getThoroughfare() != null) {
address += listAddresses.get(0).getThoroughfare() + ", ";
}
if(listAddresses.get(0).getLocality() != null) {
address += listAddresses.get(0).getLocality() + ", ";
}
if(listAddresses.get(0).getPostalCode() != null) {
address += listAddresses.get(0).getPostalCode() + ", ";
}
if(listAddresses.get(0).getCountryName() != null) {
address += listAddresses.get(0).getCountryName();
}
Toast.makeText(MapsActivity.this, address, Toast.LENGTH_LONG).show();
Log.i("address", address);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#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.NETWORK_PROVIDER, 0, 0, locationListener);
}
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.NETWORK_PROVIDER, 0, 0, locationListener);
// Get the users's current location.
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
LatLng yourLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(yourLocation).title("Your Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(yourLocation));
}
}
}
}
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);
}
I have created a Map Activity in which I want that when the user types the name of a place, he is suggested various places. When the user makes any selection, the map should position on the selected location. I have used PlaceSelectionListener for the same. Though I am able to get the Latitude and Longitude, the map does not seem to position itself. It takes the location that was previously set. I have attached my code below for reference.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
MapDialog mapDialog;
Button button;
TextView textView;
LocationManager mLocationManager;
GooglePlacesAutocompleteAdapter dataAdapter;
EditText et;
ListView listView;
#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.
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.text_view);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
button.setVisibility(View.INVISIBLE);
Location location = getLastKnownLocation();
if (location != null) {
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
textView.setVisibility(View.VISIBLE);
textView.setText(getAddress(getApplicationContext(), userLocation.latitude, userLocation.longitude));
}
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Turn on Location").setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent onGPS = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(onGPS);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).setMessage("Turn on Location services to access the application");
int off = 0;
try {
off = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
if (off == 0) {
builder.show();
} else {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment) this.getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(_placeSelectedListener);
}
#Override
protected void onResume() {
super.onResume();
Log.e("TAG", "onResume");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* 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.
*/
private PlaceSelectionListener _placeSelectedListener = new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
Log.e("TAG", "place is " + String.valueOf(place.getLatLng().latitude + " " + place.getLatLng().longitude));
final Place xyz=place;
getWindow().getDecorView().findViewById(R.id.map).invalidate();
final OnMapReadyCallback onMapReadyCallback = new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(xyz.getLatLng().latitude, xyz.getLatLng().longitude);
mMap.addMarker(new MarkerOptions().position(sydney).title("Current Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(xyz.getLatLng(), 15));
Log.e("GAT","Address "+getAddress(getApplicationContext(),xyz.getLatLng().latitude, xyz.getLatLng().longitude));
}
};
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(onMapReadyCallback);
//Place model has all data about Location selected from search box
}
#Override
public void onError(Status status) {
}
};
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
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;
}
mMap.setMyLocationEnabled(true);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = service.getBestProvider(criteria, false);
Location location = getLastKnownLocation();
// service.getLastKnownLocation(provider);
Log.e("TAG", "onResume" + location);
if (location != null) {
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
Log.e("TAG", "Location is " + userLocation + " " + userLocation.latitude + " " + userLocation.longitude);
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(userLocation.latitude, userLocation.longitude);
mMap.addMarker(new MarkerOptions().position(sydney).title("Current Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
Log.e("GAT","Address "+getAddress(getApplicationContext(),userLocation.latitude,userLocation.longitude));
}
}
private Location getLastKnownLocation() {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
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 null;
}
Location l = mLocationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
public String getAddress(Context context, double lat, double lng) {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<android.location.Address> addresses = geocoder.getFromLocation(lat, lng, 1);
android.location.Address obj = addresses.get(0);
/*String add = obj.getAddressLine(0);
add = add + "\n" + obj.getCountryName();
add = add + "\n" + obj.getCountryCode();
add = add + "\n" + obj.getAdminArea();
add = add + "\n" + obj.getPostalCode();
add = add + "\n" + obj.getSubAdminArea();
add = add + "\n" + obj.getLocality();
add = add + "\n" + obj.getSubThoroughfare();*/
String add = obj.getAddressLine(0)+","+obj.getPostalCode()+" "+obj.getAdminArea()+" "+obj.getCountryCode();
return add;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return null;
}
}
}
I haven't tried it, but try to create onMapReady() to onConnected(), add buildGoogleApiClient() call from onCreate() to onMapReady()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
//buildGoogleApiClient();
// 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.setMyLocationEnabled(true);
//add this here:
buildGoogleApiClient();
//LatLng loc = new LatLng(lat, lng);
//mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
}
#Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
lat = mLastLocation.getLatitude();
lng = mLastLocation.getLongitude();
mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
}
}
You can use requestLocationUpdates(), and call removeLocationUpdates() when the first location comes in.
Here's a demo app which can help you to understand how maps api works: https://github.com/googlemaps/android-samples/tree/master/ApiDemos
Make sure you activity extends and implement these classes
... extends FragmentActivity implements OnMapReadyCallback
example, see the code below
public class LocationPickerActivity extends FragmentActivity implements OnMapReadyCallback{
Hi i have question how to implement info window on click on marker?
the problem is i have many marker on map and each marker have another activity if info window is clicked.enter code here
heres the example
Marker One-----> if clicked infowindow marker one then ActivityOne will show up
Marker Two-----> if clicked infowindow marker two then ActivityTwo will show up
i have tried many code but not solved
Intent intent = new Intent(ThisActivity.this,OneActivity.class);
startActivity(intent);
}
});
This is perfectly working:
mapview.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
if(marker==marler1){
Intent intent = new Intent(MapActivity.this,Activity1.class);
startActivity(intent);
}else(marker==marler2){
Intent intent = new Intent(MapActivity.this,Activity2.class);
startActivity(intent);
}
}
});
First: Try to search more for a solution.
Hint: (pseudo code)
Marker m1 = map.addMarker(bla bla);
Marker m2 = map.addMarker(bla bla);
onMarkerClicked(Marker m) {
if(m == m1) {
//do what you want to do for marker one
}
else if(m == m2) {
//do what you want to do for marker two
}
}
Good idea is setting marker title, and then in listener based on title do actions
marker.getTitle()
Here is my code.
first add dependency in build.gradle.
compile 'com.google.android.gms:play-services:8.4.0'
compile 'com.google.android.gms:play-services-location:8.1.0'
compile 'com.google.android.gms:play-services-maps:8.4.0'
public class MapDetailsActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 1;
LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
LatLng latLng;
GoogleMap mGoogleMap;
SupportMapFragment mFragment;
Marker currLocationMarker;
private double longitude;
private double latitude;
private String strname;
private String strADD;
private String strLat;
private String strLng;
private BreakIterator mLatitudeText;
private BreakIterator mLongitudeText;
private MarkerOptions markerOptions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE_REQUEST_CODE
);
Bundle bundle = getIntent().getExtras();
strname = bundle.getString("Vname");
Log.e("444", "NAME--:" + strname);
strADD = bundle.getString("Address");
Log.e("444", "ADDRESS:--" + strADD);
strLat = bundle.getString("Lat");
Log.e("444", "LATTITUDE:--" + strLat);
strLng = bundle.getString("Lng");
Log.e("444", "LNGitudE:--" + strLng);
mFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mFragment.getMapAsync(this);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
if (grantResults.length == 0 || grantResults[0] == PackageManager.PERMISSION_DENIED) {
return; //permission not granted, could also optionally log an error
}
if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {
//Do whatever you needed the write permissions for
}
}
#Override
public void onMapReady(GoogleMap gMap) {
Log.e("RESDY", "^^^6");
mGoogleMap = gMap;
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;
}
gMap.setMyLocationEnabled(true);//used to enable location layer which will allow a user to interact with current user location.
gMap.getUiSettings().setZoomControlsEnabled(true);
gMap.getUiSettings().setRotateGesturesEnabled(true);
gMap.getUiSettings().setScrollGesturesEnabled(true);
gMap.getUiSettings().setTiltGesturesEnabled(true);
buildGoogleApiClient();
mGoogleApiClient.connect();
}
protected synchronized void buildGoogleApiClient() {
// GoogleApiClient.Builder is used to configure client
// Toast.makeText(this, "buildGoogleApiClient", Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)//called when client connected or disconnected.
.addOnConnectionFailedListener(this)//failed attempt of connect client to service.
.addApi(LocationServices.API)//adds the LocationServices API endpoint from Google Play Services.
.build();
}
#Override
public void onConnected(Bundle bundle) {
// Toast.makeText(this, "onConnected", Toast.LENGTH_SHORT).show();
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000); //5 seconds
mLocationRequest.setFastestInterval(3000); //3 seconds
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//mLocationRequest.setSmallestDisplacement(0.1F); //1/10 meter
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;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(this, "onConnectionSuspended", Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this, "onConnectionFailed", Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location) {
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;
}
// Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mGoogleMap.clear();
if (currLocationMarker != null) {
currLocationMarker.remove();
}
longitude = Double.parseDouble(strLng);
latitude = Double.parseDouble(strLat);
latLng = new LatLng(latitude, longitude);
mGoogleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("" + strname);
markerOptions.snippet("" + strADD);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
currLocationMarker = mGoogleMap.addMarker(markerOptions);
//zoom with animation:
// CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude)).zoom(13).bearing(90).build();
// mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
public class CustomInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {
private View view;
public CustomInfoWindowAdapter() {
view = getLayoutInflater().inflate(R.layout.custom_info_window, null);
}
#Override
public View getInfoContents(Marker marker) {
if (marker != null
&& marker.isInfoWindowShown()) {
marker.hideInfoWindow();
marker.showInfoWindow();
}
return null;
}
#Override
public View getInfoWindow(Marker marker) {
final String title = marker.getTitle();
final TextView titleUi = ((TextView) view.findViewById(R.id.title));
if (title != null) {
titleUi.setText(title);
} else {
titleUi.setText("");
}
final String snippet = marker.getSnippet();
final TextView snippetUi = ((TextView) view
.findViewById(R.id.snippet));
if (snippet != null) {
snippetUi.setText(snippet);
} else {
snippetUi.setText("");
}
return view;
}
}
}
Hope this will help you :-)