Get a Graphical Map in Android Studio - android

I have an activity called LocationTest and in my application that get the latitude and longitude and it is working properly.This activity includes a button that take us to another activity that called MapLocation that shows graphically the location on a map.But when I click the app will stop working.I will post the code of the 2 activities if somebody can help plz.I think the error is in the second activity
LocationTest Activity
public class LocationTest extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private FusedLocationProviderApi locationProvider = LocationServices.FusedLocationApi;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
public final static int MILLISECONDS_PER_SECOND=1000;
public final static int MINUTE = 60*MILLISECONDS_PER_SECOND;
private double longitude=0;
private double latitude=0;
private TextView lblLong;
private TextView lblLat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_test);
//this here is for the map
Button mapBtn =(Button)findViewById(R.id.mapBtn);
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mapBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(LocationTest.this,MapLocation.class);
startActivity(intent);
}
});
locationRequest= new LocationRequest();
/*locationRequest.setInterval(MINUTE);*/
locationRequest.setInterval((MINUTE));
locationRequest.setFastestInterval(15 * MILLISECONDS_PER_SECOND);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
lblLong = (TextView)findViewById(R.id.lblLong);
lblLat = (TextView)findViewById(R.id.lblLat);
}
#Override
protected void onStart() {
super.onStart();
googleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
googleApiClient.disconnect();
}
#Override
protected void onResume() {
super.onResume();
if(googleApiClient.isConnected()){
requestLocationUpdates();
}
}
#Override
public void onConnected(Bundle bundle) {
requestLocationUpdates();
}
private void requestLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(this, "Your Location Has Been Set: " + location.getLatitude() + " " + location.getLongitude(), Toast.LENGTH_LONG).show();
longitude = location.getLongitude();
latitude = location.getLatitude();
lblLong.setText(Double.toString(longitude));
lblLat.setText(Double.toString(latitude));
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
MapLocation Activity
public class MapLocation extends AppCompatActivity implements LocationListener{
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.activity_map_location);
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
googleMap = supportMapFragment.getMap();
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
}
#Override
public void onLocationChanged(Location location) {
TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
}

In order to show a map in your app, you will need the following steps:
1) Get you API key from https://developers.google.com/maps/documentation/android-api/ and set your permissions like this in your manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="Your package name" >
...
<!-- Creating Permission to receive Google Maps -->
<permission
android:name="com.arshad.map.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<!-- Permission to receive Google Maps -->
<uses-permission android:name="com.arshad.map.permission.MAPS_RECEIVE" />
<!-- Maps API needs OpenGL ES 2.0. -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
...
<!-- Maps API -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="Replace with your API key" />
...
</application>
</manifest>
2) Here is an example using fragments:
import android.Manifest;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import R;
public class MapFragment extends Fragment implements OnMapReadyCallback {
private static final String ARG_LONGITUDE = "longitude";
private static final String ARG_LATITUDE = "latitude";
private static final String LOG_TAG = MapFragment.class.getSimpleName();
private String mLongitude;
private String mLatitude;
//Google maps parameters initialization
static LatLng location = new LatLng(21, 57);
public static MapFragment newInstance(String longitude, String latitude) {
MapFragment fragment = new MapFragment();
Bundle args = new Bundle();
args.putString(ARG_LONGITUDE, longitude);
args.putString(ARG_LATITUDE, latitude);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
//Get lattitude and longitude
mLongitude = getArguments().getString(ARG_LONGITUDE);
mLatitude = getArguments().getString(ARG_LATITUDE);
Log.d(LOG_TAG, "Long = " + mLongitude + " lat = " + mLatitude);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_map, container, false);
MapFragment mapFragment = new MapFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.rl_map_container, mapFragment).commit();
mapFragment.getMapAsync(this);
return view;
}
#Override
public void onMapReady(GoogleMap map) {
//Setting the position of camera in the important location
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(Double.valueOf(mLatitude), Double.valueOf(mLongitude)), 17));
//Adding a marker with customized icon
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_<Your icon name>))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(Double.valueOf(mLatitude), Double.valueOf(mLongitude))));
// MAP_TYPE_TERRAIN, MAP_TYPE_HYBRID and MAP_TYPE_NONE
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
}
3) Make your layout like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".fragments.MapFragment"
>
<FrameLayout
android:id="#+id/rl_map_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Also, you can get more information in https://developers.google.com/maps/documentation/android-api/

Related

Cannot resolve symbol "locationListener" - Android

I am having trouble implementing a LocationListener.
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
TextView latitudeTV;
TextView longitudeTV;
TextView altitudeTV;
TextView locationNameTV;
double latitude;
double longitude;
double altitude;
String locationName;
LocationManager locationManager;
Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latitudeTV = (TextView) findViewById(R.id.latitude);
longitudeTV = (TextView) findViewById(R.id.longitude);
altitudeTV = (TextView) findViewById(R.id.altitude);
locationNameTV = (TextView) findViewById(R.id.locationName);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, locationListener);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
onLocationChanged(location);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
altitude = location.getAltitude();
locationName = "Placeholder";
longitudeTV.setText("Longitude: \n" + longitude + "°");
latitudeTV.setText("Latitude: \n" + latitude + "°");
altitudeTV.setText("Altitude: \n" + altitude + "m");
locationNameTV.setText("Location: \n" + locationName);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
}
}
I'm not sure if it's a syntax issue or a scoping issue, but I keep getting "unable to resolve symbol" errors. It's acting like I haven't implemented the LocationListener methods. I have tried adding implements LocationListener to MainActivity and that shows an error saying I have not implemented the LocationListener methods. I'm not sure where my mistake is.
EDIT:
I've changed my code per your answers. When I try to implement //locationManager.requestLocationUpdates(Context.LOCATION_SERVICE, 5000, 0, this); I get the following when trying to launch the app: LocationTestApp keeps stopping. I've commented out that line, and the app works again.
public class MainActivity extends AppCompatActivity implements LocationListener {
TextView latitudeTV;
TextView longitudeTV;
TextView altitudeTV;
double latitude;
double longitude;
double altitude;
LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latitudeTV = (TextView) findViewById(R.id.latitude);
longitudeTV = (TextView) findViewById(R.id.longitude);
altitudeTV = (TextView) findViewById(R.id.altitude);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
//locationManager.requestLocationUpdates(Context.LOCATION_SERVICE, 5000, 0, this);
Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
onLocationChanged(location);
}
#Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
altitude = location.getAltitude();
longitudeTV.setText("Longitude: \n" + longitude + "°");
latitudeTV.setText("Latitude: \n" + latitude + "°");
altitudeTV.setText("Altitude: \n" + altitude + "m");
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
A LocationListener class, in this case an Activity, should be defined as below:
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
public class MainActivity extends AppCompatActivity implements LocationListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, this); // Note: You pass this, so the overridden methods
}
#Override
public void onLocationChanged(Location location) {
// Do your stuff here
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
And this is the solution in jle's comments.
But if you want to use the locationListener that you've declared in your onCreate, you should declare it before using it, in this way:
...onCreate(...) {
...
LocationListener locationListener = new LocationListener() {...} // Define this...
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, locationListener); // ...and then call this
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
onLocationChanged(location);
}

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

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

How get location by COARSE location

I'm trying to develo an app that get location by COARSE location. This app must run on Android 6 too than i've implemented permission request on run time, start the map but i can't get my current location... any tips?
This is my main activity:
package com.luca.fontanelle;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.location.LocationListener;
import android.Manifest;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
final static int REQUEST_LOCATION = 199;
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private String providerNetwork = LocationManager.NETWORK_PROVIDER;
private Location mCurrentLocation;
private LocationRequest mLocationRequest;
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(AppIndex.API).build();
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_LOW_POWER)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
// 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);
}
protected void onStart() {
super.onStart();
}
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
protected void onStop() {
super.onStop();}
protected void onDestroy() {
super.onDestroy();
}
public void onLocationChanged(Location location) {
mCurrentLocation = location;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
mMap.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude())));
mMap.moveCamera(CameraUpdateFactory.zoomTo(15.0f));
}
public void onConnected(Bundle bundle) {
if (controllaPermessi()) {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient,
builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
//final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
//...
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
Intent gpsOptionsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
//...
break;
}
}
});
/* 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;
}*/
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mCurrentLocation == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}else{
richiestaPermessi();
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
//Log.d("MapsActivity", "Connessione fallita. Codice di errore: " + connectionResult.getErrorCode());
}
}
private boolean controllaPermessi(){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void richiestaPermessi(){
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)){
Toast.makeText(getApplicationContext(), "Attiva la localizzazione per usufruire dell'app.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(), "Permessi accettati. Puoi usare tutte le funzionalità.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Permessi non accettati. Non puoi accedere alle funzionalità del GPS.", Toast.LENGTH_LONG).show();
}
break;
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
}
}
Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.luca.fontanelle">
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="23" />
<permission
android:name="com.luca.fontanelle.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission-sdk-23 android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Try this code with google fused location api
1) MainActivity.class
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleMap mMap;
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
protected final static String LOCATION_KEY = "location-key";
protected final static String LAST_UPDATED_TIME_STRING_KEY = "last-updated-time-string-key";
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;
protected Location mCurrentLocation;
protected String mLastUpdateTime;
private boolean mycheck, chrckonce;
private LocationManager manager;
private Double lat, lng;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
chrckonce = true;
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLastUpdateTime = "";
updateValuesFromBundle(savedInstanceState);
}
#Override
protected void onStart() {
super.onStart();
if (!manager.isProviderEnabled((LocationManager.GPS_PROVIDER))) {
//GPS is not available show alert
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS SETTINGS");
alertDialog.setMessage("GPS is not enable! Want to go to settings menu?");
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(" Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
finish();
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
finish();
}
});
alertDialog.show();
} else {
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
mycheck = true;
buildGoogleApiClient();
mGoogleApiClient.connect();
mMap.setMyLocationEnabled(true);
}
}
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
lat = location.getLatitude();
lng = location.getLongitude();
if (chrckonce) {
mMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(lat, lng)), 2000, null);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 18));
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
chrckonce = false;
}
}
//Update location from google fused api
private void updateValuesFromBundle(Bundle savedInstanceState) {
if (savedInstanceState != null) {
if (savedInstanceState.keySet().contains(LOCATION_KEY)) {
mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
}
if (savedInstanceState.keySet().contains(LAST_UPDATED_TIME_STRING_KEY)) {
mLastUpdateTime = savedInstanceState.getString(LAST_UPDATED_TIME_STRING_KEY);
}
}
}
//synchronized google fused location api
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
//create location request
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
//on resume activity
#Override
public void onResume() {
super.onResume();
if (mycheck == true) {
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
}
}
}
//when activity goes on pause
#Override
protected void onPause() {
super.onPause();
if (mycheck == true) {
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
}
}
}
//when activity stops
#Override
protected void onStop() {
if (mycheck == true) {
mGoogleApiClient.disconnect();
}
super.onStop();
}
#Override
public void onConnected(Bundle bundle) {
if (mCurrentLocation == null) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
}
startLocationUpdates();
}
//check connection suspended
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
//Location update
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
//location update close when activity closed
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
2) activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
</fragment>
</LinearLayout>
In Manifest permissions
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

How to toggle Action Bar while touching the map like Uber

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

Android: can't get current location on maps

I have an app with google maps with one single activity where a map is displayed. I have a menu that allows me to change the map type from but I would like to have an option to get my current location.
Here's the code of my activity:
package com.example.chiapa_mapas;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MainActivity extends android.support.v4.app.FragmentActivity implements OnMapClickListener, LocationListener{
private GoogleMap mMap;
private Context ctx;
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
mMap.setOnMapClickListener(this);
// Enable LocationLayer of Google Map
mMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.opcoes, menu);
return true; }
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.normal:
mMap.setMapType(1);
break;
case R.id.satellite:
mMap.setMapType(2);
break;
case R.id.terrain:
mMap.setMapType(3);
break;
case R.id.hybrid:
mMap.setMapType(4);
break;
case R.id.none:
mMap.setMapType(0);
break;
case R.id.posicao_actual:
//mMap.setMapType(0);
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria,true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0,(android.location.LocationListener) ctx);
break;
default: return super.onOptionsItemSelected(item);
}
return true;
}
#Override
public void onMapClick(LatLng position) {
// TODO Auto-generated method stub
mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
//double ltt = position.latitude;
//double lgt = position.longitude;
//String msg = "Latitude: " + Double.toString(ltt) + " , Longitude: " + Double.toString(lgt) + "";
//Toast toast = Toast.makeText(ctx, msg, Toast.LENGTH_SHORT);
//toast.show();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
// 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);
// Showing the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// Setting latitude and longitude in the TextView
locationManager.removeUpdates((android.location.LocationListener) this);
}
}
Can someone help? When I press the option "posicao actual" (current location) it crashes.
Thanks in advance
Chiapa
This works for me:
public void methodName(){
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
android.location.LocationListener locationListener = new android.location.LocationListener() {
public void onLocationChanged(Location location) {
//Any method here
}
public void onStatusChanged (String provider, int status, Bundle extras){}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled (String provider){}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0, locationListener);
}
Thanks chiapa.
change
locationManager.requestLocationUpdates(provider, 20000, 0,(android.location.LocationListener) ctx);
to
locationManager.requestLocationUpdates(provider, 20000, 0,this);
and remove updates too

Categories

Resources