Advertisement
Guest User

Untitled

a guest
Apr 30th, 2015
332
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.31 KB | None | 0 0
  1. package com.lw276.justdine;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6.  
  7. import org.apache.http.HttpEntity;
  8. import org.apache.http.HttpResponse;
  9. import org.apache.http.StatusLine;
  10. import org.apache.http.client.HttpClient;
  11. import org.apache.http.client.methods.HttpGet;
  12. import org.apache.http.impl.client.DefaultHttpClient;
  13. import org.json.JSONArray;
  14. import org.json.JSONException;
  15. import org.json.JSONObject;
  16.  
  17. import android.app.Activity;
  18. import android.app.Dialog;
  19. import android.content.Context;
  20. import android.content.Intent;
  21. import android.location.Location;
  22. import android.location.LocationListener;
  23. import android.location.LocationManager;
  24. import android.net.ConnectivityManager;
  25. import android.net.NetworkInfo;
  26. import android.os.AsyncTask;
  27. import android.os.Bundle;
  28. import android.util.Log;
  29. import android.view.Menu;
  30. import android.view.MenuItem;
  31. import android.widget.Toast;
  32.  
  33. import com.google.android.gms.common.ConnectionResult;
  34. import com.google.android.gms.common.GooglePlayServicesUtil;
  35. import com.google.android.gms.maps.CameraUpdate;
  36. import com.google.android.gms.maps.CameraUpdateFactory;
  37. import com.google.android.gms.maps.MapFragment;
  38. import com.google.android.gms.maps.model.BitmapDescriptorFactory;
  39. import com.google.android.gms.maps.model.LatLng;
  40. import com.google.android.gms.maps.model.LatLngBounds;
  41. import com.google.android.gms.maps.model.Marker;
  42. import com.google.android.gms.maps.model.MarkerOptions;
  43.  
  44. public class GoogleMap extends Activity implements LocationListener{
  45.  
  46. private com.google.android.gms.maps.GoogleMap map;
  47. private LatLng gpsLocation;
  48. private double lat;
  49. private double lon;
  50. final Activity context = this;
  51. private LocationManager locationManager;
  52. private String API_KEY = "API_KEY";
  53. private int radius =0;
  54. private int sortType =1;
  55. private boolean opennow = false;
  56. private int intentRadius =0;
  57. private int locManDist = 10;
  58. private int locManTime = 5000;
  59. private int intentMap= 0;
  60. private String keyWord = "";
  61.  
  62. private String advancedSearch = "";
  63. CameraUpdate update;
  64. String googlePlaces;
  65.  
  66. @Override
  67. protected void onCreate(Bundle savedInstanceState) {
  68. super.onCreate(savedInstanceState);
  69. setContentView(R.layout.activity_google_map);
  70.  
  71. if ( getIntent().getExtras().getString("onItemSelected") != null ){
  72. keyWord = getIntent().getExtras().getString("onItemSelected");
  73. if (keyWord.equals("Show All")){
  74. keyWord ="";
  75. }
  76. }
  77. Log.d("GoogleMap keyWordIntent", keyWord);
  78. intentMap = getIntent().getExtras().getInt("mapType");
  79. Log.d("onCreateIntentMap", Integer.toString(intentMap));
  80.  
  81. if (canConnectToGooglePlay() && canConnectToInternet()
  82. && canFindGPSLocation()) {
  83. setMap();
  84. }
  85. }
  86. public void setMap(){
  87. map = ((MapFragment) getFragmentManager()
  88. .findFragmentById(R.id.map)).getMap();
  89. map.addMarker(new MarkerOptions()
  90. .position(gpsLocation)
  91. .title("This is you!")
  92. .icon(BitmapDescriptorFactory
  93. .defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
  94. if (intentMap==1||intentMap==2||intentMap==4){
  95. map.setMapType(intentMap);
  96. } else {
  97. map.setMapType(com.google.android.gms.maps.GoogleMap.MAP_TYPE_NORMAL);
  98. }
  99. update = CameraUpdateFactory.newLatLngZoom(gpsLocation, 15);
  100. map.animateCamera(update);
  101. updatePlaces();
  102. }
  103.  
  104. public void updatePlaces(){
  105. radius = Settings.getRadius();
  106. intentRadius = getIntent().getExtras().getInt("radius");
  107. Log.d("updatePlacesIntentRadius", Integer.toString(intentRadius));
  108. sortType = getIntent().getExtras().getInt("sortType");
  109. opennow = getIntent().getExtras().getBoolean("opennow");
  110. Log.d("updatePlacesIntSort", Integer.toString(sortType));
  111. if ( getIntent().getExtras().getString("advancedSearch") != null){
  112. advancedSearch = getIntent().getExtras().getString("advancedSearch");
  113. }
  114. canFindGPSLocation();
  115. Log.d("updatePlacesRadius", Integer.toString(radius));
  116. if (radius!=intentRadius && intentRadius > 0){
  117. radius = intentRadius;
  118. } else if (radius==0){
  119. radius= 2000;
  120. }
  121. if (advancedSearch.equals("")){
  122. if (sortType==1||sortType==0){
  123. // googlePlaces = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?keyword="+keyWord+"&location=" + lat +"," + lon+"&radius=" + radius +"&sensor=true&types=restaurant&key="+API_KEY;
  124. // googlePlaces = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?keyword="+keyWord+"&opennow=true&location="+lat + "," + lon+"&radius="+radius+"&sensor=true&types=restaurant&key="+API_KEY;
  125. googlePlaces = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?keyword="+keyWord+"&location="+lat + "," + lon+"&radius="+radius+"&sensor=true&types=restaurant&key="+API_KEY;
  126. Log.d("GooglePlaces HTTP: ", googlePlaces);
  127. } else {
  128. // googlePlaces = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?keyword="+keyWord+"&location=" + lat +"," + lon+"&rankby=distance&sensor=true&types=restaurant&key="+API_KEY;
  129. googlePlaces = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?keyword="+keyWord+"&opennow=" + opennow + "&location=" + lat +"," + lon+ "&rankby=distance&sensor=true&types=restaurant&key="+API_KEY;
  130. // googlePlaces = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?keyword=chinese&opennow=true&location=50.8443991,-0.119416&rankby=distance&sensor=true&types=restaurant&key=AIzaSyD4COhtG8l3ojgv2Epm6coqKfwA_Vmugkg";
  131.  
  132. Log.d("GooglePlaces HTTP: ", googlePlaces);
  133. }
  134. } else {
  135. advancedSearch = advancedSearch.replaceAll(" ", "+");
  136. googlePlaces = "https://maps.googleapis.com/maps/api/place/details/json?placeid="+advancedSearch+"&key="+API_KEY;
  137. Log.w("Advanced Search has been used", googlePlaces);
  138. }
  139. SearchPlaces mySP = new SearchPlaces();
  140. mySP.execute(null,null,null);
  141. locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
  142. locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, locManTime, locManDist, this);
  143. }
  144. private class SearchPlaces extends AsyncTask<String, Void, String> {
  145.  
  146. private Marker[] placeMarkers;
  147. private final int MAX_PLACES = 20;
  148. private MarkerOptions[] places;
  149. boolean missingValue=false;
  150.  
  151.  
  152. @Override
  153. protected String doInBackground(String... arg0) {
  154. Log.d("SearchPlaces: ", "Entered");
  155. StringBuilder placesBuilder = new StringBuilder();
  156. HttpClient placesClient = new DefaultHttpClient();
  157. try {
  158. Log.d("SearchPlacesTry: ", "Entered");
  159. Log.d("GooglePlaces HTTP Link doInBackground: ", googlePlaces);
  160. HttpGet placesGet = new HttpGet(googlePlaces);
  161. HttpResponse placesResponse = placesClient.execute(placesGet);
  162. StatusLine placeSearchStatus = placesResponse.getStatusLine();
  163. if (placeSearchStatus.getStatusCode() == 200) {
  164. HttpEntity placesEntity = placesResponse.getEntity();
  165. InputStream placesContent = placesEntity.getContent();
  166. InputStreamReader placesInput = new InputStreamReader(placesContent);
  167. BufferedReader placesReader = new BufferedReader(placesInput);
  168. String lineIn;
  169. while ((lineIn = placesReader.readLine()) != null) {
  170. placesBuilder.append(lineIn);
  171. }
  172. Log.d("SearchPlaces2: ",placesBuilder.toString());
  173. return placesBuilder.toString();
  174. }
  175. }
  176. catch(Exception e){
  177. e.printStackTrace();
  178. }
  179. return null;
  180. }
  181.  
  182. protected void onPostExecute(String result){
  183. placeMarkers = new Marker[MAX_PLACES];
  184. if(placeMarkers!=null){
  185. for(int i=0; i<placeMarkers.length; i++){
  186. if(placeMarkers[i]!=null)
  187. placeMarkers[i].remove();
  188. }
  189. }
  190. try{
  191. JSONObject resultObject = new JSONObject(result);
  192. JSONArray placesArray = resultObject.getJSONArray("results");
  193. places = new MarkerOptions[placesArray.length()];
  194. for ( int j=0;j<placesArray.length();j++){
  195. LatLng placeLL=null;
  196. String placeName="";
  197. String vicinity="";
  198. // String open ="";
  199. try{
  200. JSONObject placeObject = placesArray.getJSONObject(j);
  201. JSONObject loc = placeObject.getJSONObject("geometry").getJSONObject("location");
  202. placeLL = new LatLng(
  203. Double.valueOf(loc.getString("lat")),
  204. Double.valueOf(loc.getString("lng")));
  205. // open = placeObject.getString("open_now");
  206. vicinity = placeObject.getString("vicinity");
  207. placeName = placeObject.getString("name");
  208. }
  209. catch(JSONException jse){
  210. missingValue=true;
  211. jse.printStackTrace();
  212. }
  213. if(missingValue) places[j]=null;
  214. else
  215. places[j]=new MarkerOptions()
  216. .position(placeLL)
  217. .title(placeName)
  218. .snippet(vicinity);
  219. // .snippet("This is" + open);
  220. }
  221. } catch (Exception e){
  222. e.printStackTrace();
  223. }
  224. boolean added = false;
  225. LatLngBounds.Builder builder = new LatLngBounds.Builder();
  226. if(places!=null && placeMarkers!=null){
  227. for(int p=0; p<places.length && p<placeMarkers.length; p++){
  228. //will be null if a value was missing
  229. if(places[p]!=null){
  230. placeMarkers[p]=map.addMarker(places[p]);
  231. builder.include(places[p].getPosition());
  232. if (!added){
  233. builder.include(gpsLocation);
  234. added = true;
  235. }
  236. }
  237. }
  238. // builder.include(gpsLocation);
  239. }
  240. try{
  241. LatLngBounds bounds = builder.build();
  242. CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 200);
  243. map.animateCamera(cu);
  244. } catch (Exception e) {
  245. Toast.makeText(context, "No restaurants found", Toast.LENGTH_SHORT).show();
  246. }
  247. }
  248. }
  249.  
  250. public boolean canConnectToGooglePlay() {
  251. // Checking to see if Google Play Services are available
  252. int googleStatus = GooglePlayServicesUtil
  253. .isGooglePlayServicesAvailable(getBaseContext());
  254. if (googleStatus != ConnectionResult.SUCCESS) {
  255. Log.d("Status: ", String.valueOf(googleStatus));
  256. if (GooglePlayServicesUtil.isUserRecoverableError(googleStatus)) {
  257. Dialog error = GooglePlayServicesUtil.getErrorDialog(
  258. googleStatus, GoogleMap.this, 1);
  259. if (error != null) {
  260. error.show();
  261. }
  262. }
  263. } else {
  264. Log.d("googleStatus: ", "Successful");
  265. return true;
  266. }
  267. Log.d("WARNING: ", "Cannot Connect to Google Play");
  268. return false;
  269. }
  270.  
  271. public boolean canConnectToInternet() {
  272. ConnectivityManager connectivity = (ConnectivityManager) context
  273. .getSystemService(Context.CONNECTIVITY_SERVICE);
  274. if (connectivity != null) {
  275. NetworkInfo[] info = connectivity.getAllNetworkInfo();
  276. if (info != null)
  277. for (int i = 0; i < info.length; i++)
  278. if (info[i].getState() == NetworkInfo.State.CONNECTED) {
  279. return true;
  280. }
  281. }
  282. Log.d("WARNING: ", "No internet connectivity");
  283. return false;
  284. }
  285.  
  286. public boolean canFindGPSLocation() {
  287. // Checking to see if JustDine has access to GPS
  288. GPS g = new GPS(this);
  289. try {
  290. if (g.getLocation() != null) {
  291. lat = g.getLatitude();
  292. lon = g.getLongitude();
  293. Log.d("gpsStatus(lat / lon): ", String.valueOf(lat) + " / "
  294. + String.valueOf(lon));
  295. gpsLocation = new LatLng(lat, lon);
  296. return true;
  297.  
  298. } else {
  299. Log.d("gpsStatus: ", "0x00000000");
  300. // gpsLocation = new LatLng(50.844436, -0.119069); //Debugging
  301. // Cockcroft Location
  302. return true;
  303. }
  304. } catch (Exception e) {
  305. e.getMessage();
  306. Log.d("gpsStatus: ", e.getMessage());
  307. }
  308. Log.d("WARNING: ", "Cannot find GPS location");
  309. return false;
  310. }
  311.  
  312. @Override
  313. public boolean onCreateOptionsMenu(Menu menu) {
  314. // Inflate the menu; this adds items to the action bar if it is present.
  315. getMenuInflater().inflate(R.menu.google_map, menu);
  316. return true;
  317. }
  318.  
  319. @Override
  320. public boolean onOptionsItemSelected(MenuItem item) {
  321. // Handle action bar item clicks here. The action bar will
  322. // automatically handle clicks on the Home/Up button, so long
  323. // as you specify a parent activity in AndroidManifest.xml.
  324. int id = item.getItemId();
  325. if (id == R.id.action_settings) {
  326. Intent i = new Intent(context, Settings.class);
  327. i.putExtra("onItemSelected", keyWord);
  328. startActivity(i);
  329. return true;
  330. } else if ( id == R.id.action_advanced_search) {
  331. Intent i = new Intent(context, AdvancedSearch.class);
  332. startActivity(i);
  333. return true;
  334. }
  335. return super.onOptionsItemSelected(item);
  336. }
  337. @Override
  338. public void onLocationChanged(Location arg0) {
  339. Log.d("onLocationChanged: ", "Location has changed!");
  340. updatePlaces();
  341. }
  342. @Override
  343. public void onProviderDisabled(String arg0) {
  344. Log.d("onProviderDisabled: ","Provider has been disabled!");
  345. if(map!=null){
  346. locationManager.removeUpdates(this);
  347. }
  348. }
  349. @Override
  350. public void onProviderEnabled(String arg0) {
  351. Log.d("onProviderEnabled: ","Provider has been enabled!");
  352. locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, locManTime, locManDist, this);
  353. }
  354. @Override
  355. public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
  356. Log.d("onStatusChanged: ","A change of status has been made!");
  357. }
  358. @Override
  359. protected void onResume() {
  360. super.onResume();
  361. if(map!=null){
  362. locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, locManTime, locManDist, this);
  363. }
  364. }
  365. @Override
  366. protected void onPause() {
  367. super.onPause();
  368. if(map!=null){
  369. locationManager.removeUpdates(this);
  370. }
  371. }
  372. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement