Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Send location (lat, long) via API to the chat and store it to FireBase - WORKING SOLUTION!! #29

Open
fritexvz opened this issue May 9, 2019 · 0 comments

Comments

@fritexvz
Copy link

fritexvz commented May 9, 2019

I figure it out.
Go to https://developers.google.com/maps/documentation/maps-static/intro.
Grab a Key with Enabled API's: https://console.cloud.google.com/home/dashboard.
Add no restrictions or use only for Android SDK.

Changes to the MainActivity.java:

...public class MainActivity extends AppCompatActivity ... {
LocationTrack locationTrack; // NEW HERE
...
// Location Permissions // NEW HERE
  private static final int REQUEST_LOCATION = 3;
  private static String[] PERMISSIONS_LOCATION = {
    android.Manifest.permission.ACCESS_FINE_LOCATION,
    android.Manifest.permission.ACCESS_COARSE_LOCATION
  };
...
protected void onCreate(Bundle savedInstanceState) {
...
  locationTrack = new LocationTrack(MainActivity.this); // NEW HERE
...
}

// DELETE OR COMMENT OUT ALL INSIDE
else if (requestCode == PLACE_PICKER_REQUEST) {
      if (resultCode == RESULT_OK) {
           .... // REMOVE ALL INSIDE HERE
     }
}


...
public boolean onOptionsItemSelected(MenuItem item) { ...
...
// NEW HERE UNDER STORAGE
             case R.id.sendLocation:
                verifyLocationPermissions();
                //locationPlacesIntent();
                break;

...
}
...

private void locationPlacesIntent(){
        /* COMMENT THIS OUT - DEPRECATED
            try {
            PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
            startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
        } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
            e.printStackTrace();
        }
       */ END COMMENT

      // NEW HERE - BELOW
      locationTrack = new LocationTrack(MainActivity.this);

      if (locationTrack.canGetLocation()) {

        double longitude = locationTrack.getLongitude();
        double latitude = locationTrack.getLatitude();

        Toast.makeText(getApplicationContext(), "Longitude:" + Double.toString(longitude) + "\nLatitude:" + Double.toString(latitude), Toast.LENGTH_SHORT).show();
        MapModel mapModel = new MapModel(latitude +"", longitude +"");
        ChatModel chatModel = new ChatModel(userModel,Calendar.getInstance().getTime().getTime()+"",mapModel);
        mFirebaseDatabaseReference.child(CHAT_REFERENCE).push().setValue(chatModel);
      } else {
        //locationTrack.showSettingsAlert();
        Toast.makeText(getApplicationContext(),"Greška!", Toast.LENGTH_SHORT).show();
      }
    }
.....
}

...

// NEW HERE - BELOW
public void verifyLocationPermissions() {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION);

    if (permission != PackageManager.PERMISSION_GRANTED) {
      // We don't have permission so prompt the user
      ActivityCompat.requestPermissions(
        MainActivity.this,
        PERMISSIONS_LOCATION,
        REQUEST_LOCATION
      );
    }else{
      // we already have permission, lets go ahead and call camera intent
      locationPlacesIntent();
    }
  }


} // END OF public class MainActivity

Create new file LocationTrack.java:

package alessandro.firebaseandroid;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;

public class LocationTrack extends Service implements LocationListener {

  private final Context mContext;


  boolean checkGPS = false;


  boolean checkNetwork = false;

  boolean canGetLocation = false;

  Location loc;
  double latitude;
  double longitude;


  private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;


  private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
  protected LocationManager locationManager;

  public LocationTrack(Context mContext) {
    this.mContext = mContext;
    getLocation();
  }

  private Location getLocation() {

    try {
      locationManager = (LocationManager) mContext
        .getSystemService(LOCATION_SERVICE);

      // get GPS status
      checkGPS = locationManager
        .isProviderEnabled(LocationManager.GPS_PROVIDER);

      // get network provider status
      checkNetwork = locationManager
        .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

      if (!checkGPS && !checkNetwork) {
        Toast.makeText(mContext, "No Service Provider is available", Toast.LENGTH_SHORT).show();
      } else {
        this.canGetLocation = true;

        // if GPS Enabled get lat/long using GPS Services
        if (checkGPS) {

          if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, 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.
          }
          locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            MIN_TIME_BW_UPDATES,
            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
          if (locationManager != null) {
            loc = locationManager
              .getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (loc != null) {
              latitude = loc.getLatitude();
              longitude = loc.getLongitude();
            }
          }


        }


                /*if (checkNetwork) {


                    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, 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.
                    }
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                    if (locationManager != null) {
                        loc = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                    }

                    if (loc != null) {
                        latitude = loc.getLatitude();
                        longitude = loc.getLongitude();
                    }
                }*/

      }


    } catch (Exception e) {
      e.printStackTrace();
    }

    return loc;
  }

  public double getLongitude() {
    if (loc != null) {
      longitude = loc.getLongitude();
    }
    return longitude;
  }

  public double getLatitude() {
    if (loc != null) {
      latitude = loc.getLatitude();
    }
    return latitude;
  }

  public boolean canGetLocation() {
    return this.canGetLocation;
  }

  public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);


    alertDialog.setTitle("GPS is not Enabled!");

    alertDialog.setMessage("Do you want to turn on GPS?");


    alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        mContext.startActivity(intent);
      }
    });


    alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
      }
    });


    alertDialog.show();
  }


  public void stopListener() {
    if (locationManager != null) {

      if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
      }
      locationManager.removeUpdates(LocationTrack.this);
    }
  }

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

  @Override
  public void onLocationChanged(Location location) {

  }

  @Override
  public void onStatusChanged(String s, int i, Bundle bundle) {

  }

  @Override
  public void onProviderEnabled(String s) {

  }

  @Override
  public void onProviderDisabled(String s) {

  }
} // END OF NEW FILE

Full code here: https://www.journaldev.com/13325/android-location-api-tracking-gps

strings.xml

  • do not forget to add your key here
    <string name="api_key_google_places">YOUR_API_KEY</string>

app/build.gradle:

  • add this
        //Places SERVICES
        implementation 'com.google.android.gms:play-services-places:16.1.0'
        implementation 'com.google.android.libraries.places:places:1.1.0'
        implementation 'com.google.android.gms:play-services-maps:16.1.0'
        implementation 'com.google.android.gms:play-services-location:16.0.0'

Util.java

  • change this:
    return "https://maps.googleapis.com/maps/api/staticmap?center="+latitudeFinal+","+longitudeFinal+"&zoom=18&size=280x280&markers=color:red|"+latitudeFinal+","+longitudeFinal;

  • to this:
    return "https://maps.googleapis.com/maps/api/staticmap?center="+latitudeFinal+","+longitudeFinal+"&zoom=18&size=640x640&maptype=roadmap&key=YOUR_KEY_HERE&markers=color:red|"+latitudeFinal+","+longitudeFinal;

And it works as a charm.
You have a toast and you get image with link - which opens Google Maps application.

In case if needed, take a look here: https://www.journaldev.com/13325/android-location-api-tracking-gps

Working by me here:
https://ibb.co/N7crJNX
https://ibb.co/XJGM4Lh
https://ibb.co/61x1pNC

I can help you to get it working

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant