Android google map with current position - java

I'm writing an application that among other things should draw a map with the current device position and a remote point.
I started from the example created by Android Studio (Google->Google Map Activity).
I just add the code to get the current location:
package it.tux.mapper.activities;
import android.Manifest;
import android.annotation.SuppressLint;
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.util.Log;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
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;
import com.google.android.material.snackbar.Snackbar;
import java.util.Objects;
import it.tux.mapper.R;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, ActivityCompat.OnRequestPermissionsResultCallback, LocationListener {
private static final int PERMISSION_REQUEST_LOCATION = 11;
private static final int LOCATION_UPDATE_DELAY = 1000;
private final String gps_provider = LocationManager.GPS_PROVIDER;
private GoogleMap map;
private Location location;
private LocationManager location_manager;
private View layout;
#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);
if (mapFragment != null)
mapFragment.getMapAsync(this);
//USER CODE
layout = findViewById(R.id.map);
assert layout != null;
location = new Location(getString(R.string.location_provider));
location.isFromMockProvider();
initLocalization();
//
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_LOCATION) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Snackbar.make(layout, R.string.fine_location_access_granted, Snackbar.LENGTH_SHORT).show();
startLocalization();
} else {
Snackbar.make(layout, R.string.denied_fine_location_access_rationale, Snackbar.LENGTH_SHORT).show();
}
}
}
/**
* 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) {
map = googleMap;
}
#Override
public void onLocationChanged(Location location) {
this.location.set(location);
if (map != null) {
LatLng base = new LatLng(location.getLatitude(), location.getLongitude());
map.addMarker(new MarkerOptions().position(base).title(getString(R.string.destination_base_label)));
map.moveCamera(CameraUpdateFactory.newLatLng(base));
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
return;
}
#Override
public void onProviderEnabled(String s) {
return;
}
#Override
public void onProviderDisabled(String s) {
return;
}
private void requestLocationPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
Snackbar.make(layout, R.string.denied_fine_location_access_rationale,
Snackbar.LENGTH_INDEFINITE).setAction(R.string.ok, new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.CAMERA},
PERMISSION_REQUEST_LOCATION);
}
}).show();
} else {
Snackbar.make(layout, R.string.denied_fine_location_access_warning, Snackbar.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_LOCATION);
}
}
private void initLocalization() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
Snackbar.make(layout,
R.string.fine_location_access_granted,
Snackbar.LENGTH_SHORT).show();
startLocalization();
} else {
requestLocationPermission();
}
}
#SuppressLint("MissingPermission")
private void startLocalization() {
try {
location_manager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!location_manager.isProviderEnabled(gps_provider)) {
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
} else {
location_manager.requestLocationUpdates(gps_provider, LOCATION_UPDATE_DELAY, 2, this);
}
} catch (Throwable e) {
Log.e(getClass().getName(), "Exception: " + e.getMessage());
}
}
}
The code seems to work, i.e. no exceptions are triggered and onMapReady, onLocationChanged and onRequestPermissionsResult events are correctly fired.
The map is just empty. And the use count of the Api key is 0.
The manifest has the correct permission entries:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
And also the GoogleApi key is correctly set (I have a developer account):
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
Where's my error?

The problem seems to be related to the internet connection used to make the first connection to google api service. Under certain firewall the connection is probably blocked preventing a successful authorization. Changing the connection fixed this issue but I probably need to investigate deeply the API auth mechanism.

Related

Android: FusedLocationProvider, get location every few seconds

I'm making an app that tracks the user's location and ultimatly uploads it to a Firebase server.
I have created a simple app that displays the location when I press a button on screen. The problem is that it doesnt change the location when I press it again after I walked a few meters (I do get a new location when I re-enter the app though). What do I need to add in order for the app to update the location every X seconds? This is my activity:
package com.example.gpstest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestPermission();
client = LocationServices.getFusedLocationProviderClient(this);
Button button = findViewById(R.id.getLocation);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
return;
}
client.getLastLocation().addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null){
TextView lat = findViewById(R.id.location1);
TextView lon = findViewById(R.id.location2);
TextView alt = findViewById(R.id.location3);
lat.setText(Double.toString(location.getLatitude()));
lon.setText(Double.toString(location.getLongitude()));
alt.setText(Double.toString(location.getAltitude()));
}
}
});
}
});
}
private void requestPermission(){
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
}
}
Because you get the location from getLastLocation. For that you have to implement LocationCallback.
consider this link for more information
// implement these interface in your class
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener.
//than use this code
public void onConnected(Bundle bundle) {
Location mLastLocation = null;
if (mGoogleApiClient.isConnected()) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// 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 precise.
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
}
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
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
buildGoogleApiClient();
mGoogleApiClient.connect();
}
}

How to get a location on GPS open street map using android above 5.1

I'm using the location manager to find my location, but when I simulate with an api greater than 18, I can not find the location
package br.com.josileudorodrigues.myapplication;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Canvas;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.cocoahero.android.geojson.GeoJSON;
import org.osmdroid.bonuspack.kml.KmlDocument;
import org.osmdroid.bonuspack.location.NominatimPOIProvider;
import org.osmdroid.bonuspack.location.POI;
import org.osmdroid.config.Configuration;
import org.osmdroid.events.MapEventsReceiver;
import org.osmdroid.events.MapListener;
import org.osmdroid.events.ScrollEvent;
import org.osmdroid.events.ZoomEvent;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.Projection;
import org.osmdroid.views.overlay.FolderOverlay;
import org.osmdroid.views.overlay.MapEventsOverlay;
import org.osmdroid.views.overlay.Marker;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.OverlayItem;
import org.osmdroid.views.overlay.PathOverlay;
import org.osmdroid.views.overlay.ScaleBarOverlay;
import org.osmdroid.views.overlay.infowindow.InfoWindow;
import org.osmdroid.views.overlay.infowindow.MarkerInfoWindow;
import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider;
import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay;
import java.util.ArrayList;
import static android.os.Build.VERSION_CODES.M;
public class MainActivity extends AppCompatActivity implements MapEventsReceiver, LocationListener {
private static final int PERMISSAO_REQUERIDA =1 ;
private MapView osm;
private MapController mc;
private LocationManager locationManager;
private PathOverlay po;
private KmlDocument kmlDocument;
ArrayList<OverlayItem> overlayItemArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
osm = (MapView) findViewById(R.id.mapaId);
osm.setTileSource(TileSourceFactory.MAPNIK);
osm.setUseDataConnection(true);
osm.setMultiTouchControls(true);
osm.setClickable(true);
osm.setBuiltInZoomControls(true);
if (Build.VERSION.SDK_INT >= M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
String[] permissoes = {Manifest.permission.INTERNET, Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissoes, PERMISSAO_REQUERIDA);
}
}
osm.setMapListener(new MapListener() {
#Override
public boolean onScroll(ScrollEvent event) {
Log.i("Script()", "onScroll ()");
return true;
}
#Override
public boolean onZoom(ZoomEvent event) {
Log.i("Script()", "onZoom ()");
return false;
}
});
//onde mostra a imagem do mapa
Context ctx = getApplicationContext();
Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));
mc = (MapController) osm.getController();
mc.setZoom(15);
GeoPoint center = new GeoPoint(-5.1251, -38.3640);
mc.animateTo(center);
addMarker(center);
// here is where the permissions are
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
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
// .
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
MapEventsOverlay mapEventsOverlay = new MapEventsOverlay(this, this);
osm.getOverlays().add(0, mapEventsOverlay);
// Aqui adiciona a escala do mapa
ScaleBarOverlay scaleBarOverlay = new ScaleBarOverlay(osm);
osm.getOverlays().add(scaleBarOverlay);
kmlDocument = new KmlDocument();
// kmlDocument.parseGeoJSON(geoJsonString);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSAO_REQUERIDA: {
// Se a solicitação de permissão foi cancelada o array vem vazio.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permissão cedida, recria a activity para carregar o mapa, só será executado uma vez
this.recreate();
}
}
}
}
public void addMarker(final GeoPoint center) {
final Marker marker = new Marker(osm);
marker.setPosition(center);
marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
marker.setIcon(getResources().getDrawable(R.drawable.ic_mapa));
marker.setDraggable(true);
marker.setTitle("DADOS");
marker.setSnippet(center.getLatitude()+ "," + center.getLongitude());
marker.setSubDescription("subDescription Marker");
marker.setInfoWindow(new CustomMarkerInfoWindow(osm));
marker.setInfoWindowAnchor(marker.ANCHOR_CENTER, marker.ANCHOR_TOP);
marker.setOnMarkerClickListener(new Marker.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker m, MapView mapView) {
Log.i("Script","onMarkerClick");
m.showInfoWindow();
return true;
}
});
marker.setOnMarkerDragListener(new Marker.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
Log.i("Script", "onMarkerDragStart()");
}
#Override
public void onMarkerDragEnd(Marker marker) {
Log.i("Script", "onMarkerDragEnd()");
}
#Override
public void onMarkerDrag(Marker marker) {
Log.i("Script", "onMarkerDrag()");
}
});
//osm.getOverlays().clear();
osm.getOverlays().add(new MapOverlay(this));
osm.getOverlays().add(marker);
osm.invalidate();
}
#Override
public void onLocationChanged(Location location) {
GeoPoint center = new GeoPoint(location.getLatitude(), location.getLongitude());
mc.animateTo(center);
addMarker(center);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onDestroy() {
super.onDestroy();
if (locationManager != null) {
locationManager.removeUpdates((LocationListener) this);
}
}
class MapOverlay extends Overlay {
public MapOverlay(Context ctx) {
super(ctx);
}
#Override
public void draw(Canvas c, MapView osmv, boolean shadow) {
}
#Override
public boolean onSingleTapConfirmed(MotionEvent me, MapView mv) {
Projection p = osm.getProjection();
GeoPoint gp = (GeoPoint) p.fromPixels((int) me.getX(), (int) me.getY());
addMarker(gp);
return (true);
}
}
// Aqui quando eu pressionar em uma determinada parte do mapa ele
// irá mostrar as minhas cordenadas
#Override
public boolean singleTapConfirmedHelper(GeoPoint p) {
Toast.makeText(this, "Coordenadas:\nLatitude: ("+p.getLatitude() +"\nLongitude: " +
""+p.getLongitude()+")" , Toast.LENGTH_SHORT).show();
InfoWindow.closeAllInfoWindowsOn(osm); //Clicando em qualquer canto da tela, fecha o infowindow
return (true);
}
#Override
public boolean longPressHelper(GeoPoint p) {
return false;
}
// InfoWindow
public class CustomMarkerInfoWindow extends MarkerInfoWindow {
public CustomMarkerInfoWindow(MapView mapView) {
super(R.layout.bonuspack_bubble,mapView);
}
#Override
public void onOpen(Object item){
Marker m = (Marker) item;
ImageView iv = (ImageView) mView.findViewById(R.id.bubble_image);
iv.setImageResource(R.drawable.btn_moreinfo);
TextView snippet = (TextView) mView.findViewById(R.id.bubble_title);
snippet.setText(m.getTitle());
TextView coordenada = (TextView) mView.findViewById(R.id. coordenadas);
coordenada.setText(m.getSnippet());
Button bt = (Button) mView.findViewById(R.id.bubble_buttom);
bt.setVisibility(View.VISIBLE);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"Salvo",Toast.LENGTH_SHORT ).show();
}
});
}
}
}
Image
How would you fix this error?
You need to request GPS permissions from the user on APIs > 21 (i think)
On every gps update, roughly once a second, you are adding a new marker to the map. You'll eventually run out of memory. Consider just updating the marker's location.
See this https://github.com/osmdroid/osmdroid/wiki/How-to-use-the-osmdroid-library#how-to-add-the-my-location-overlay that overlay is a bit easier to use that rolling your own solution, but whatever. Here's a working example of using it https://github.com/osmdroid/osmdroid/blob/master/OpenStreetMapViewer/src/main/java/org/osmdroid/samplefragments/location/SampleMyLocationWithClick.java (code is below)
Not all emulators do GPS. Sometimes you have to poke around in the menus to stimulate it. Try to reproduce on hardware. Genymotion works pretty well
Code snippet
final MyLocationOverlayWithClick overlay = new MyLocationOverlayWithClick(mMapView);
overlay.enableFollowLocation();
overlay.enableMyLocation();
mMapView.getOverlayManager().add(overlay);
Finally you can run the sample app from here, https://play.google.com/store/apps/details?id=org.osmdroid or you can get the APK on github. If that doesn't work in your emulator, then the emulator is broken or doesn't support gps

app runs fine for the first time after installation but after that keeps on asking to turn on gps even if its on

Upon installing the app you will see the app works fine first time showing location as toast message but when you try to use it again, it asks to turn gps on even if its on. INFO: I am developing an app for android version 6. The code for location works fine for below version like android kitkat. Please help me fix this. :(
HomeActivity.java
package info.androidhive.fingerprint;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;
public class HomeActivity extends Activity {
Context mContext;
GPSTracker gps= new GPSTracker(mContext);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mContext = this;
if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(HomeActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
Toast.makeText(mContext, "You need to grant permission", Toast.LENGTH_SHORT).show();
// Check if GPS enabled
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
} else {
// Can't get location.
gps = new GPSTracker(mContext, HomeActivity.this); // GPS or network is not enabled.
// Ask user to enable GPS/network in settings.
gps.showSettingsAlert();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
gps = new GPSTracker(mContext, HomeActivity.this);
// Check if GPS enabled
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
} else {
// Can't get location.
// GPS or network is not enabled.
// Ask user to enable GPS/network in settings.
gps.showSettingsAlert();
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(mContext, "You need to grant permission", Toast.LENGTH_SHORT).show();
}
}
}
}
}
GPSTracker.java
package info.androidhive.fingerprint;
/*
Created by sal on 12/4/17.
*/
import android.Manifest;
import android.app.Activity;
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.support.v4.content.ContextCompat;
import android.util.Log;
public class GPSTracker extends Service{
private Context mContext;
// Flag for GPS status
boolean isGPSEnabled = false;
// Flag for network status
boolean isNetworkEnabled = false;
// Flag for GPS status
boolean canGetLocation = false;
Location location; // Location
double latitude; // Latitude
double longitude; // Longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1000; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
Activity activity;
public GPSTracker(Context context, Activity activity) {
this.mContext = context;
this.activity = activity;
getLocation();
}
public GPSTracker(Context abc) {
this.mContext=abc;
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// Getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// No network provider is enabled
this.canGetLocation=false;
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, mLocationListener);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
if (location == null) {
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 50);
} else {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, mLocationListener);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app.
* */
public void stopUsingGPS() {
}
private final LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/Wi-Fi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog.
* On pressing the Settings button it will launch Settings Options.
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing the Settings button.
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// On pressing the cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="info.androidhive.fingerprint">
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.location.gps" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".FingerprintActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".HomeActivity"
android:label="#string/title_activity_home"
android:theme="#style/AppTheme" />
</application>
</manifest>
Use LocationManager class of Google service to check for GPS status:-
compile 'com.google.android.gms:play-services:9.8.0'
// Demo class for GPS
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v13.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;
/**
* Created by admin on 18-Apr-17.
*/
public class DemoActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission(); //Step 1
}
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.e("GPS setting is ", locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) + "");
buildAlertMessageNoGps();
} else {
Log.e("GPS setting is ", locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) + "");
}
}
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getResources().getString(R.string.alertdialog_content))
.setCancelable(false)
.setPositiveButton("Setting", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
Toast.makeText(DemoActivity.this, getResources().getString(R.string.alertdialog_cancel_message), Toast.LENGTH_LONG).show();
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
return false;
} else {
return true;
}
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 100:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e(getClass().getSimpleName(), permissions[0] + " Granted...");
} else {
Toast.makeText(this, "Application may not function properly if you deny permission, Please allow Location permission from app settings", Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 100); // you can request again if user deny location request else your logic here
}
break;
}
}
}
Screenshots
1 - Requesting to turn GPS on
2 - GPS status
3 - Enable location from setting
4 - GSP status on
you are using
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 50);
which can only turn on Fine Location .
Put A line below this line
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 50);
It will do

Anonymous class is not abstract and does not override (Android + Retrofit)

I am trying to make a Google map show nearby places using retrofit following this tutorial.
I get this error:
Error:(158, 46) error: is not abstract and does not
override abstract method onFailure(Call,Throwable) in
Callback
Error:(159, 13) error: method does not override or implement a method
from a supertype
I tried to implement methods using the alt + enter, but it gets different from the tutorial, and it messes up the code.
Here is my main (it's the same from the tutorial)
MapsActivity.java
package example.googlemapsapp;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
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.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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.HashMap;
import example.googlemapsapp.POJO.Example;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
double latitude;
double longitude;
private int PROXIMITY_RADIUS = 10000;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
//show error dialog if Google Play Services not available
if (!isGooglePlayServicesAvailable()) {
Log.d("onCreate", "Google Play Services not available. Ending Test case.");
finish();
}
else {
Log.d("onCreate", "Google Play Services available. Continuing.");
}
// 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);
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
0).show();
}
return false;
}
return true;
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
Button btnRestaurant = (Button) findViewById(R.id.btnRestaurant);
btnRestaurant.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build_retrofit_and_get_response("restaurant");
}
});
Button btnHospital = (Button) findViewById(R.id.btnHospital);
btnHospital.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build_retrofit_and_get_response("hospital");
}
});
Button btnSchool = (Button) findViewById(R.id.btnSchool);
btnSchool.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build_retrofit_and_get_response("school");
}
});
}
private void build_retrofit_and_get_response(String type) {
String url = "https://maps.googleapis.com/maps/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitMaps service = retrofit.create(RetrofitMaps.class);
Call<Example> call = service.getNearbyPlaces(type, latitude + "," + longitude, PROXIMITY_RADIUS);
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(Response<Example> response, Retrofit retrofit) {
try {
mMap.clear();
// This loop will go through all the results and add marker on each location.
for (int i = 0; i < response.body().getResults().size(); i++) {
Double lat = response.body().getResults().get(i).getGeometry().getLocation().getLat();
Double lng = response.body().getResults().get(i).getGeometry().getLocation().getLng();
String placeName = response.body().getResults().get(i).getName();
String vicinity = response.body().getResults().get(i).getVicinity();
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(lat, lng);
// Position of Marker on Map
markerOptions.position(latLng);
// Adding Title to the Marker
markerOptions.title(placeName + " : " + vicinity);
// Adding Marker to the Camera.
Marker m = mMap.addMarker(markerOptions);
// Adding colour to the marker
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
// move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
Log.d("onLocationChanged", "entered");
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
// Adding colour to the marker
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
// Adding Marker to the Map
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f", latitude, longitude));
Log.d("onLocationChanged", "Exit");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
}
The signature of onResponse differs from what you have.
You have:
public void onResponse( Response<Example> response, Retrofit retrofit)
It should be:
public void onResponse(Call<Example> call, Response<Example> response)
Your onFailure also needs to take a Call parameter:
public void onFailure(Call<Example> call, Throwable t)
It's possible the signatures of the methods have changed between versions of Retrofit, and that the tutorial is using an older version than you are. But I'm only speculating.
It's very easy to diagnose: Just read the error message and understand it:
It says that you are trying to sublcass the CallBack interface, so you have to override all the methods it declares. But you are not; because you have not overrided right the onFailure(Call<T> call, Throwable t) method.
See? You missed to add the call parameter in the onFailure method.
Do not trust so tightly on tutorials; use it as a basis, not as a Gospel. Maybe that tutorial is based on a prior version of Retrofit. (Or it maybe contains mistakes).

Retrofit response method parsing JSON from google map api doesn't work

The loop inside the retrofitResponse method does not loops which it was suppose to do. It was suppose to fetch json data from google map url.
package com.webstarts.byteglory.shomadhan;
import android.*;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.location.Location;
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.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationRequest;
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.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.webstarts.byteglory.shomadhan.POJO.Example;
import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;
public class StartActivity extends FragmentActivity implements ConnectionCallbacks, OnConnectionFailedListener, com.google.android.gms.location.LocationListener, OnMapReadyCallback {
protected GoogleApiClient mGoogleApiClient;
protected Location mLastLocation;
protected static final String TAG = "Location Services Test";
private Button search_location_button;
private Button search_area_button;
private Button toilet_status_button;
protected LatLng latlng;
protected LocationRequest mLocationRequest;
private GoogleMap mMap;
private int PROXIMITY_RADIUS = 10000;
Marker mCurrLocationMarker;
boolean mapReady = false;
private Marker mPerth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
search_location_button = (Button) findViewById(R.id.search_location_button);
search_area_button = (Button) findViewById(R.id.search_area_button);
toilet_status_button = (Button) findViewById(R.id.toilet_status_button);
locationApiClient();
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
// .findFragmentById(R.id.map);
// mapFragment.getMapAsync(this);
search_location_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Log.i(TAG, String.valueOf(latlng.latitude));
// Uri gmmIntentUri = Uri.parse("geo:"+String.valueOf(latlng.latitude)+","+String.valueOf(latlng.longitude)+"?z=15&q=public toilets");
// Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
// mapIntent.setPackage("com.google.android.apps.maps");
// startActivity(mapIntent);
retrofitResponse();
// Marker loc = mMap.addMarker(new MarkerOptions().position(latlng)
// .title("You are here now 23"));
// mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 15));
//
// // Zoom in, animating the camera.
// mMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
// Log.i(TAG, String.valueOf(latlng.latitude));
}
});
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
protected synchronized void locationApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/**
* Runs when a GoogleApiClient object successfully connects.
*/
#Override
public void onConnected(Bundle connectionHint) {
// Provides a simple way of getting a device's location and is well suited for
// applications that do not require a fine-grained location and that do not need location
// updates. Gets the best and most recent location currently available, which may be null
// in rare cases when a location is not available.
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.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(mGoogleApiClient, mLocationRequest, this);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null) {
latlng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
}
else {
Toast toast = Toast.makeText(this, "Turn on your location service", Toast.LENGTH_LONG);
toast.show();
finish();
}
}
public void onLocationChanged(Location location) {
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
/*
* Called by Google Play services if the connection to GoogleApiClient drops because of an
* error.
*/
public void onDisconnected() {
Log.i(TAG, "Disconnected");
}
#Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
private void retrofitResponse() {
String url = "https://maps.googleapis.com/maps/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitMaps service = retrofit.create(RetrofitMaps.class);
Call<Example> call = service.getNearbyPlaces("restaurents", latlng.latitude + "," + latlng.longitude, PROXIMITY_RADIUS);
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(Response<Example> response, Retrofit retrofit) {
try {
mMap.clear();
// This loop will go through all the results and add marker on each location.
Log.i("ishan", String.valueOf(response.body().getResults().size()));
for (int i = 0; i < response.body().getResults().size(); i++) {
Double lat = response.body().getResults().get(i).getGeometry().getLocation().getLat();
Double lng = response.body().getResults().get(i).getGeometry().getLocation().getLng();
String placeName = response.body().getResults().get(i).getName();
String vicinity = response.body().getResults().get(i).getVicinity();
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(lat, lng);
// Position of Marker on Map
markerOptions.position(latLng);
// Adding Title to the Marker
markerOptions.title(placeName + " : " + vicinity);
// Adding Marker to the Camera.
Marker m = mMap.addMarker(markerOptions);
// Adding colour to the marker
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
// move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Log.i("ishan", String.valueOf(i));
}
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
#Override
public void onMapReady(GoogleMap map) {
mapReady=true;
mMap = map;
// //Initialize Google Play Services
// if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// if (ContextCompat.checkSelfPermission(this,
// android.Manifest.permission.ACCESS_FINE_LOCATION)
// == PackageManager.PERMISSION_GRANTED) {
// }
// }
}
}
This is the interface of the retrofit. It has just the GET as it just reads data from map url.
package com.webstarts.byteglory.shomadhan;
import com.webstarts.byteglory.shomadhan.POJO.Example;
import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.Query;
public interface RetrofitMaps {
/*
* Retrofit get annotation with our URL
* And our method that will return us details of student.
*/
#GET("api/place/nearbysearch/json?sensor=true&key=AIzaSyABCGHHSFDGSDsdfGADFnM")
Call<Example> getNearbyPlaces(#Query("type") String type, #Query("location") String location, #Query("radius") int radius);
}
I have just looped inside the onResponse retrofit function like this:
public void onResponse(Call call, Response response) {
/* implement the toast */
/* =new ArrayList<User>(); */
ArrayList<User> test;
test=response.body().getUsers();
String jax= test.get(0).getFarm_name();
//Toast.makeText(MarkerDemoActivity.this, "farm name is "+jax, Toast.LENGTH_LONG).show();
//LatLng m_cord,String farm_name,String desc
int i = 0;
while ( test.size()>i) {
String farm_name = test.get(i).getFarm_name();
String desc1 = test.get(i).getOwner_tel();
String desc2 = test.get(i).getFarm_type();
String cords = test.get(i).getM_cord();
//split the co-ords
String[] latlong = cords.split(",");
double latitude = Double.parseDouble(latlong[0]);
double longitude = Double.parseDouble(latlong[1]);
LatLng location = new LatLng(latitude, longitude);
//do the loop here
// Add lots of markers to the map. LatLng m_cord,String farm_name,String desc
addMarkersToMapJax(location, farm_name, desc1 + desc2);
i++;
}
}
I created a marker function to load the co-ordinates:
private void addMarkersToMapJax(LatLng m_cord,String farm_name,String desc) {
// Uses a colored icon.
mArc = mMap.addMarker(new MarkerOptions()
.position(m_cord)
.title(farm_name)
.snippet(desc)

Categories