The below code is an extract from my Android application to get current location
I have been following http://blog.teamtreehouse.com/beginners-guide-location-android and http://droidmentor.com/get-the-current-location-in-android/
most of the documentation is outdated even the developer.google and developers.android stuff.
I want to know why both functions return null and what can I do about it
thank you.
#Override
public void onConnected(Bundle bundle) {
try
{
Log.d(TAG, "connection successful");
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation == null) {
Log.d(TAG, "get last location = null");
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); //then nothing happens
}
else {
Log.d(TAG, "last location successful");
handleNewLocation(mLastLocation);
}; }
#Override
public void onLocationChanged(Location location){
handleNewLocation(location);
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am here!");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
Address address = getAddress(location);
starttext.setText("Current Location: \n" + address.toString());
}
The FusedLocationProviderApi is depreciated https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi
So use FusedLocationProviderClient instead. Usage: https://developer.android.com/training/location/retrieve-current.html#play-services
Related
I am trying to implement an app that uses Google Map API, I'm using this deprecated method and it's causing my app to not perform properly. deprecated method is: FusedLocationAPI, any ideas how to replace it in this context?
code:
public void onConnected(#Nullable Bundle bundle) {
locationRequest = LocationRequest.create();
locationRequest.setInterval(100);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
lastlocation = location;
if (currentLocationMarker != null) {
currentLocationMarker.remove();
}
Log.d("lat = ", "" + latitude);
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Location");
markerOptions.snippet("My Present Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
currentLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(7));
if (client != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(client, this);
}
}
I developed an application for Android in Eclipse with Google maps. The problem is that the blue dot indicating my current location appears always parallel to the road where I am driving, on roads outside cities. But if you are within the city the point already on top of the road.
I'm using this to get my location on the start of the app:
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location myLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
then I add the blue dot to the map:
googleMap.setMyLocationEnabled(true);
and then I start listening for location changes:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, time, 1, this);
My location change function:
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Lat1 = location.getLatitude();
Long1 = location.getLongitude();
if (Lat1 != Lat || Long1 != Long) {
Lat = location.getLatitude();
Long = location.getLongitude();
if (startNav == true) {
googleMap.animateCamera(CameraUpdateFactory
.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 17));
b = new LatLng(Lat, Long);
if (a != null) {
String urlTopass = makeURL(b.latitude, b.longitude, a.latitude, a.longitude);
new connectAsyncTask(urlTopass).execute();
}
}
}
}
}
My question is why does the blue dot appear parallel to the street instead of on top of it?
Use the FusedLocationProviderAPI. It is recommended over using the older open source Location APIs, especially since you're already using a Google Map so you are already using Google Play Services.
Simply set up a Location Listener, and update your current location Marker in each onLocationChanged() callback. If you only want one location update, just un-register for callbacks after the first callback returns.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null || !mGoogleApiClient.isConnected()){
buildGoogleApiClient();
mGoogleApiClient.connect();
}
if (map == null) {
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap retMap) {
map = retMap;
setUpMap();
}
public void setUpMap(){
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
map.setMyLocationEnabled(true);
}
#Override
protected void onPause(){
super.onPause();
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
protected synchronized void buildGoogleApiClient() {
Toast.makeText(this, "buildGoogleApiClient", Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(Bundle bundle) {
Toast.makeText(this,"onConnected", Toast.LENGTH_SHORT).show();
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//mLocationRequest.setSmallestDisplacement(0.1F);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
//remove previous current location Marker
if (marker != null){
marker.remove();
}
double dLatitude = mLastLocation.getLatitude();
double dLongitude = mLastLocation.getLongitude();
marker = map.addMarker(new MarkerOptions().position(new LatLng(dLatitude, dLongitude))
.title("My Location").icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dLatitude, dLongitude), 8));
}
}
I do want to get current location with GoogleApiClient with this code below,
#Override
public void onConnected(#Nullable Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null)
{
currentLat = mLastLocation.getLatitude();
currentLon = mLastLocation.getLongitude();
}else
{
Toast.makeText(getApplicationContext(), "Cannot get lat and lon", Toast.LENGTH_SHORT).show();
}
}
then after that i do want to put marker on current location, my problem is mLastlocation still null
#Override
public void onMapReady(GoogleMap googleMap) {
dGoogleMap = googleMap;
if(mLastLocation != null)
{
MarkerOptions marker = new MarkerOptions()
.position(new LatLng(currentLat, currentLon))
.title("My Current Location");
dGoogleMap.addMarker(marker);
dGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(currentLat, currentLon), 16));
}
}
Or this is my fault missunderstand the flow of async, or just my poor logic needs to be improved.
Put below line in your onMapReady method
dGoogleMap.setMyLocationEnabled(true);
Current location pointer is jumping i dump to resolve the issue.I want to stop jumping the current pointer pointer.I want to show pointer without jumping situation.
I tried 4 days but not done this Task.
private boolean initMap() {
if (mMap == null && FirstTimeMapIniciate == 0) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFragment.getMap();
mMap.setMyLocationEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
return (mMap != null);
}
Here is OnLocationChange Code
#Override
public void onConnected(Bundle bundle) {
Toast.makeText(this, "Ready to map!", Toast.LENGTH_SHORT).show();
mListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng1 = new LatLng(latitude, longitude);
MarkerOptions mp = new MarkerOptions();
mp = new MarkerOptions();
mp.position(new LatLng(location.getLatitude(),
location.getLongitude()));
mMap.setMyLocationEnabled(true);
// mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
Toast.makeText(MainActivity.this, "Location : " + location.getLatitude() + ", " + location.getLongitude(), Toast.LENGTH_LONG).show();
if (FirstTimeMapIniciate == 0) {
gotoLocation(location.getLatitude(), location.getLongitude(), 15);
FirstTimeMapIniciate = 1;
}
AppUtill.UniqueId();
new JSONAsyncTask().execute("http://103.8.7/hajjapi/api/GPSLocator/GetLocations");
if (AppStatus.getInstance(getContext()).isOnline()) {
} else {
Toast.makeText(MainActivity.this, "Turn On your WIFI ", Toast.LENGTH_LONG).show();
}
/* if (marker != null) {
marker.remove();
}*/
}
};
LocationRequest request = LocationRequest.create();
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
request.setInterval(1000);
request.setFastestInterval(1000);
LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, request, mListener);
}
There are several problems in your logic as the first you don't need to call setMyLocationUpdate(true) at every location update.
The answer to your question as I'd say you need to implement your own service where you can apply your customized algorithm to filter out those jumps.
Is there any possible to throw notification if i was outside of radius when it has been settled ?
My schema is like this :
i am a student and my phone has been installed tracker.
if i walk into outside range of school. my application will give notification to my mother that i have been skip the class using SMS / email.
could you guide me ?
here is my code :
protected void onCreate(Bundle savedInstanceState) {
mLocationRequest = LocationRequest.create()
.setInterval(3)
.setFastestInterval(60)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_activity);
}
public void circle()
{
Circle circle = mMap.addCircle(new CircleOptions()
.center(new LatLng(-xxxxxx,xxxxx))
.radius(2)
.strokeColor(Color.RED)
.strokeWidth(1)
.fillColor(Color.BLUE));
}
public void setUpMapIfNeeded()
{
SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFrag.getMap();
mMap.setMyLocationEnabled(true);
circle();
}
public void onConnected(Bundle bundle)
{
Log.i(TAG,"Location Services Connected.");
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(location==null)
{
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this);
}
else
{
handleNewLocation(location);
}
}
private void handleNewLocation(Location location)
{
Log.d(TAG,location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude,currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am here !");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,21));
}
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
//put this code in handler new location
//put this code in handler new location
if(distanceBetween(current_latlon, circle_latlon)>radius_of_circle)//radius in meters
{
//here you can create a notification of whatever you want
}
//to calculate distance between two latlong
private float distanceBetween(LatLng latLng1, LatLng latLng2)
{
Location loc1 = new Location(LocationManager.GPS_PROVIDER);
Location loc2 = new Location(LocationManager.GPS_PROVIDER);
loc1.setLatitude(latLng1.latitude);
loc1.setLongitude(latLng1.longitude);
loc2.setLatitude(latLng2.latitude);
loc2.setLongitude(latLng2.longitude);
return loc1.distanceTo(loc2); //in meters
}