From f2668181a2a32bf4f6f79b33a4e2c1729681960c Mon Sep 17 00:00:00 2001 From: chan24 <aakaschan24@gmail.com> Date: Thu, 20 Apr 2017 19:41:37 +0530 Subject: [PATCH] nearByLocationadded --- app/build.gradle | 4 +- app/src/main/AndroidManifest.xml | 7 +- .../chan24/smartplanner/AppConfig.java | 38 +++ .../chan24/smartplanner/AppController.java | 51 ++++ .../chan24/smartplanner/MapsActivity.java | 224 +++++++++++++++--- app/src/main/res/layout/activity_maps.xml | 24 +- 6 files changed, 309 insertions(+), 39 deletions(-) create mode 100644 app/src/main/java/com/example/chan24/smartplanner/AppConfig.java create mode 100644 app/src/main/java/com/example/chan24/smartplanner/AppController.java diff --git a/app/build.gradle b/app/build.gradle index aceb0e0..8fa90c5 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -26,7 +26,7 @@ dependencies { }) compile 'com.android.support:appcompat-v7:25.1.0' compile 'com.android.support:design:25.1.1' - compile 'com.android.volley:volley:1.0.0' + compile 'com.mcxiaoke.volley:library:1.0.19' compile 'com.google.android.gms:play-services:10.0.1' compile 'com.android.support:support-annotations:25.3.1' compile 'com.google.android.gms:play-services-maps:10.0.1' @@ -37,4 +37,6 @@ dependencies { + + apply plugin: 'com.google.gms.google-services' \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 6cd5d8d..e065aee 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,6 +2,8 @@ <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.chan24.smartplanner"> + + <!-- The ACCESS_COARSE/FINE_LOCATION permissions are not required to use Google Maps Android API v2, but you must specify either coarse or fine @@ -19,6 +21,7 @@ android:required="true" /> <application + android:name=".AppController" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" @@ -48,10 +51,10 @@ android:name="com.google.android.gsm.version" android:value="@integer/google_play_services_version" /> + <activity android:name=".ProfileActivity" /> <activity android:name=".MapsActivity" - android:label="@string/title_activity_maps" /> - <activity android:name=".ProfileActivity"></activity> + android:label="@string/title_activity_maps"></activity> </application> </manifest> \ No newline at end of file diff --git a/app/src/main/java/com/example/chan24/smartplanner/AppConfig.java b/app/src/main/java/com/example/chan24/smartplanner/AppConfig.java new file mode 100644 index 0000000..840d3f2 --- /dev/null +++ b/app/src/main/java/com/example/chan24/smartplanner/AppConfig.java @@ -0,0 +1,38 @@ +package com.example.chan24.smartplanner; + + +public class AppConfig { + public static final String TAG = "gplaces"; + + public static final String RESULTS = "results"; + public static final String STATUS = "status"; + + public static final String OK = "OK"; + public static final String ZERO_RESULTS = "ZERO_RESULTS"; + public static final String REQUEST_DENIED = "REQUEST_DENIED"; + public static final String OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"; + public static final String UNKNOWN_ERROR = "UNKNOWN_ERROR"; + public static final String INVALID_REQUEST = "INVALID_REQUEST"; + + // Key for nearby places json from google + public static final String GEOMETRY = "geometry"; + public static final String LOCATION = "location"; + public static final String LATITUDE = "lat"; + public static final String LONGITUDE = "lng"; + public static final String ICON = "icon"; + public static final String SUPERMARKET_ID = "id"; + public static final String NAME = "name"; + public static final String PLACE_ID = "place_id"; + public static final String REFERENCE = "reference"; + public static final String VICINITY = "vicinity"; + public static final String PLACE_NAME = "place_name"; + + // remember to change the browser api key + public static final String GOOGLE_BROWSER_API_KEY = "AIzaSyB-c05UTNgIpizYVd1bCsGCNXCBO_TGP4o"; + public static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; + public static final int PROXIMITY_RADIUS = 5000; + // The minimum distance to change Updates in meters + public static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters + // The minimum time between updates in milliseconds + public static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute +} diff --git a/app/src/main/java/com/example/chan24/smartplanner/AppController.java b/app/src/main/java/com/example/chan24/smartplanner/AppController.java new file mode 100644 index 0000000..cac6d14 --- /dev/null +++ b/app/src/main/java/com/example/chan24/smartplanner/AppController.java @@ -0,0 +1,51 @@ +package com.example.chan24.smartplanner; + +import android.app.Application; +import android.text.TextUtils; + +import com.android.volley.Request; +import com.android.volley.RequestQueue; +import com.android.volley.toolbox.Volley; + +import static com.example.chan24.smartplanner.AppConfig.TAG; + + +public class AppController extends Application { + private RequestQueue mRequestQueue; + private static AppController mInstance; + + @Override + public void onCreate() { + super.onCreate(); + mInstance = this; + + } + + public static synchronized AppController getInstance() { + return mInstance; + } + + public RequestQueue getRequestQueue() { + if (mRequestQueue == null) { + mRequestQueue = Volley.newRequestQueue(getApplicationContext()); + } + return mRequestQueue; + } + + public <T> void addToRequestQueue(Request<T> req, String tag) { + req.setTag(TextUtils.isEmpty(tag) ? TAG : tag); + getRequestQueue().add(req); + } + + public <T> void addToRequestQueue(Request<T> req) { + req.setTag(TAG); + getRequestQueue().add(req); + } + + public void cancelPendingRequests(Object tag) { + if (mRequestQueue != null) { + mRequestQueue.cancelAll(tag); + } + } + +} diff --git a/app/src/main/java/com/example/chan24/smartplanner/MapsActivity.java b/app/src/main/java/com/example/chan24/smartplanner/MapsActivity.java index 433b379..75d7ef6 100644 --- a/app/src/main/java/com/example/chan24/smartplanner/MapsActivity.java +++ b/app/src/main/java/com/example/chan24/smartplanner/MapsActivity.java @@ -1,79 +1,243 @@ package com.example.chan24.smartplanner; -import android.content.Context; +import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; +import android.graphics.Color; +import android.location.Criteria; import android.location.Location; import android.location.LocationManager; import android.location.LocationListener; import android.provider.Settings; +import android.support.design.widget.CoordinatorLayout; +import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; +import android.util.Log; +import android.view.View; +import android.widget.TextView; import android.widget.Toast; +import com.android.volley.Response; +import com.android.volley.VolleyError; +import com.android.volley.toolbox.JsonObjectRequest; +import com.google.android.gms.common.ConnectionResult; +import com.google.android.gms.common.GoogleApiAvailability; +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 { +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import static com.example.chan24.smartplanner.AppConfig.*; + +public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,LocationListener { private GoogleMap mMap; - private LocationManager locationManager; - private LocationListener locationListener; + LocationManager locationManager; + CoordinatorLayout mainCoordinateLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + + if (!isGooglePlayServicesAvailable()){ + return; + } setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); + + mainCoordinateLayout = (CoordinatorLayout) findViewById(R.id.mainCoordinatorLayout); + locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); + if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { + showLocationSettings(); + } + } + + private void showLocationSettings() { + Snackbar snackbar = Snackbar.make(mainCoordinateLayout,"Location Error.GPS Disabled!",Snackbar.LENGTH_LONG).setAction("Enable", new View.OnClickListener() { + @Override + public void onClick(View v) { + startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); + } + }); + + snackbar.setActionTextColor(Color.RED); + snackbar.setDuration(Snackbar.LENGTH_INDEFINITE); + + View sbView = snackbar.getView(); + TextView textview =(TextView)sbView.findViewById(R.id.snackbar_text); + textview.setTextColor(Color.YELLOW); + + snackbar.show(); } + private boolean isGooglePlayServicesAvailable() { + GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); + int resultCode = apiAvailability.isGooglePlayServicesAvailable(this); + if (resultCode != ConnectionResult.SUCCESS) { + if (apiAvailability.isUserResolvableError(resultCode)) { + apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST).show(); + } else { + Log.i(TAG, "This device is not supported."); + finish(); + } + return false; + } + return true; + } + + @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")); - mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));*/ + 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) { + return; + } + mMap.setMyLocationEnabled(true); + mMap.getUiSettings().setCompassEnabled(true); + mMap.getUiSettings().setZoomControlsEnabled(true); + showCurrentLocation(); + } - 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) { + private void showCurrentLocation() { + Criteria criteria = new Criteria(); + String bestProvider = locationManager.getBestProvider(criteria, true); + if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && + ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) + != PackageManager.PERMISSION_GRANTED) { return; } - mMap.setMyLocationEnabled(true); - mMap.setTrafficEnabled(true); - locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); - locationListener = new LocationListener() { - @Override - public void onLocationChanged(Location location) { - Toast.makeText(getApplicationContext(),"long"+location.getLongitude()+"lat"+location.getLatitude(),Toast.LENGTH_LONG).show(); - } + Location location = locationManager.getLastKnownLocation(bestProvider); - @Override - public void onStatusChanged(String provider, int status, Bundle extras) { + if (location != null){ + onLocationChanged(location); + } + locationManager.requestLocationUpdates(bestProvider, MIN_TIME_BW_UPDATES, + MIN_DISTANCE_CHANGE_FOR_UPDATES, this); + } - } + @Override + public void onLocationChanged(Location location) { + double latitude = location.getLatitude(); + double longitude = location.getLongitude(); - @Override - public void onProviderEnabled(String provider) { + LatLng latLng = new LatLng(latitude, longitude); + mMap.addMarker(new MarkerOptions().position(latLng).title("My Location")); + mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); + mMap.animateCamera(CameraUpdateFactory.zoomTo(15)); - } + loadNearByPlaces(latitude, longitude); + + } - @Override - public void onProviderDisabled(String provider) { - Intent i= new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); - startActivity(i); - } - }; - locationManager.requestLocationUpdates("gps",5000,0,locationListener); + @Override + public void onStatusChanged(String provider, int status, Bundle extras) { + } + @Override + public void onProviderEnabled(String provider) { + } + + @Override + public void onProviderDisabled(String provider) { + + } + + private void loadNearByPlaces(double latitude, double longitude) { + String type = "restaurant"; + StringBuilder googlePlacesUrl = + new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?"); + googlePlacesUrl.append("location=").append(latitude).append(",").append(longitude); + googlePlacesUrl.append("&radius=").append(PROXIMITY_RADIUS); + googlePlacesUrl.append("&types=").append(type); + googlePlacesUrl.append("&sensor=true"); + googlePlacesUrl.append("&key=" + GOOGLE_BROWSER_API_KEY); + + JsonObjectRequest request = new JsonObjectRequest(googlePlacesUrl.toString(), + new Response.Listener<JSONObject>() { + @Override + public void onResponse(JSONObject result) { + + Log.i(TAG, "onResponse: Result= " + result.toString()); + parseLocationResult(result); + } + }, + new Response.ErrorListener() { + @Override public void onErrorResponse(VolleyError error) { + Log.e(TAG, "onErrorResponse: Error= " + error); + Log.e(TAG, "onErrorResponse: Error= " + error.getMessage()); + } + }); + + AppController.getInstance().addToRequestQueue(request); + } + + private void parseLocationResult(JSONObject result) { + String id, place_id, placeName = null, reference, icon, vicinity = null; + double latitude, longitude; + + try { + JSONArray jsonArray = result.getJSONArray("results"); + + if (result.getString(STATUS).equalsIgnoreCase(OK)) { + + mMap.clear(); + + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject place = jsonArray.getJSONObject(i); + + id = place.getString(SUPERMARKET_ID); + place_id = place.getString(PLACE_ID); + if (!place.isNull(NAME)) { + placeName = place.getString(NAME); + } + if (!place.isNull(VICINITY)) { + vicinity = place.getString(VICINITY); + } + latitude = place.getJSONObject(GEOMETRY).getJSONObject(LOCATION) + .getDouble(LATITUDE); + longitude = place.getJSONObject(GEOMETRY).getJSONObject(LOCATION) + .getDouble(LONGITUDE); + reference = place.getString(REFERENCE); + icon = place.getString(ICON); + + MarkerOptions markerOptions = new MarkerOptions(); + LatLng latLng = new LatLng(latitude, longitude); + markerOptions.position(latLng); + markerOptions.title(placeName + " : " + vicinity); + + mMap.addMarker(markerOptions); + } + + Toast.makeText(getBaseContext(), jsonArray.length() + " Supermarkets found!", + Toast.LENGTH_LONG).show(); + } else if (result.getString(STATUS).equalsIgnoreCase(ZERO_RESULTS)) { + Toast.makeText(getBaseContext(), "No Supermarket found in 5KM radius!!!", + Toast.LENGTH_LONG).show(); + } + + } catch (JSONException e) { + + e.printStackTrace(); + Log.e(TAG, "parseLocationResult: Error=" + e.getMessage()); + } + } } diff --git a/app/src/main/res/layout/activity_maps.xml b/app/src/main/res/layout/activity_maps.xml index 7f98416..45a980a 100644 --- a/app/src/main/res/layout/activity_maps.xml +++ b/app/src/main/res/layout/activity_maps.xml @@ -1,8 +1,20 @@ -<fragment xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:map="http://schemas.android.com/apk/res-auto" +<?xml version="1.0" encoding="utf-8"?> + +<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" - android:id="@+id/map" - android:name="com.google.android.gms.maps.SupportMapFragment" + android:id="@+id/mainCoordinatorLayout" android:layout_width="match_parent" - android:layout_height="350dp" - tools:context="com.example.chan24.smartplanner.MapsActivity" /> + android:layout_height="match_parent" + android:fitsSystemWindows="true" + tools:context=".MapsActivity"> + + <fragment xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools" + android:id="@+id/map" + android:name="com.google.android.gms.maps.SupportMapFragment" + android:layout_width="match_parent" + android:layout_height="match_parent" + tools:context="com.example.chan24.smartplanner.MapsActivity" /> + +</android.support.design.widget.CoordinatorLayout> + -- GitLab