Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.lw276.justdine;
- import java.io.BufferedReader;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.StatusLine;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
- import android.app.Activity;
- import android.app.Dialog;
- import android.content.Context;
- import android.content.Intent;
- import android.location.Location;
- import android.location.LocationListener;
- import android.location.LocationManager;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.Menu;
- import android.view.MenuItem;
- import android.widget.Toast;
- import com.google.android.gms.common.ConnectionResult;
- import com.google.android.gms.common.GooglePlayServicesUtil;
- import com.google.android.gms.maps.CameraUpdate;
- import com.google.android.gms.maps.CameraUpdateFactory;
- import com.google.android.gms.maps.MapFragment;
- import com.google.android.gms.maps.model.BitmapDescriptorFactory;
- import com.google.android.gms.maps.model.LatLng;
- import com.google.android.gms.maps.model.LatLngBounds;
- import com.google.android.gms.maps.model.Marker;
- import com.google.android.gms.maps.model.MarkerOptions;
- public class GoogleMap extends Activity implements LocationListener{
- private com.google.android.gms.maps.GoogleMap map;
- private LatLng gpsLocation;
- private double lat;
- private double lon;
- final Activity context = this;
- private LocationManager locationManager;
- private String API_KEY = "API_KEY";
- private int radius =0;
- private int sortType =1;
- private boolean opennow = false;
- private int intentRadius =0;
- private int locManDist = 10;
- private int locManTime = 5000;
- private int intentMap= 0;
- private String keyWord = "";
- private String advancedSearch = "";
- CameraUpdate update;
- String googlePlaces;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_google_map);
- if ( getIntent().getExtras().getString("onItemSelected") != null ){
- keyWord = getIntent().getExtras().getString("onItemSelected");
- if (keyWord.equals("Show All")){
- keyWord ="";
- }
- }
- Log.d("GoogleMap keyWordIntent", keyWord);
- intentMap = getIntent().getExtras().getInt("mapType");
- Log.d("onCreateIntentMap", Integer.toString(intentMap));
- if (canConnectToGooglePlay() && canConnectToInternet()
- && canFindGPSLocation()) {
- setMap();
- }
- }
- public void setMap(){
- map = ((MapFragment) getFragmentManager()
- .findFragmentById(R.id.map)).getMap();
- map.addMarker(new MarkerOptions()
- .position(gpsLocation)
- .title("This is you!")
- .icon(BitmapDescriptorFactory
- .defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
- if (intentMap==1||intentMap==2||intentMap==4){
- map.setMapType(intentMap);
- } else {
- map.setMapType(com.google.android.gms.maps.GoogleMap.MAP_TYPE_NORMAL);
- }
- update = CameraUpdateFactory.newLatLngZoom(gpsLocation, 15);
- map.animateCamera(update);
- updatePlaces();
- }
- public void updatePlaces(){
- radius = Settings.getRadius();
- intentRadius = getIntent().getExtras().getInt("radius");
- Log.d("updatePlacesIntentRadius", Integer.toString(intentRadius));
- sortType = getIntent().getExtras().getInt("sortType");
- opennow = getIntent().getExtras().getBoolean("opennow");
- Log.d("updatePlacesIntSort", Integer.toString(sortType));
- if ( getIntent().getExtras().getString("advancedSearch") != null){
- advancedSearch = getIntent().getExtras().getString("advancedSearch");
- }
- canFindGPSLocation();
- Log.d("updatePlacesRadius", Integer.toString(radius));
- if (radius!=intentRadius && intentRadius > 0){
- radius = intentRadius;
- } else if (radius==0){
- radius= 2000;
- }
- if (advancedSearch.equals("")){
- if (sortType==1||sortType==0){
- // googlePlaces = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?keyword="+keyWord+"&location=" + lat +"," + lon+"&radius=" + radius +"&sensor=true&types=restaurant&key="+API_KEY;
- // 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;
- googlePlaces = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?keyword="+keyWord+"&location="+lat + "," + lon+"&radius="+radius+"&sensor=true&types=restaurant&key="+API_KEY;
- Log.d("GooglePlaces HTTP: ", googlePlaces);
- } else {
- // googlePlaces = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?keyword="+keyWord+"&location=" + lat +"," + lon+"&rankby=distance&sensor=true&types=restaurant&key="+API_KEY;
- 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;
- // 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";
- Log.d("GooglePlaces HTTP: ", googlePlaces);
- }
- } else {
- advancedSearch = advancedSearch.replaceAll(" ", "+");
- googlePlaces = "https://maps.googleapis.com/maps/api/place/details/json?placeid="+advancedSearch+"&key="+API_KEY;
- Log.w("Advanced Search has been used", googlePlaces);
- }
- SearchPlaces mySP = new SearchPlaces();
- mySP.execute(null,null,null);
- locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
- locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, locManTime, locManDist, this);
- }
- private class SearchPlaces extends AsyncTask<String, Void, String> {
- private Marker[] placeMarkers;
- private final int MAX_PLACES = 20;
- private MarkerOptions[] places;
- boolean missingValue=false;
- @Override
- protected String doInBackground(String... arg0) {
- Log.d("SearchPlaces: ", "Entered");
- StringBuilder placesBuilder = new StringBuilder();
- HttpClient placesClient = new DefaultHttpClient();
- try {
- Log.d("SearchPlacesTry: ", "Entered");
- Log.d("GooglePlaces HTTP Link doInBackground: ", googlePlaces);
- HttpGet placesGet = new HttpGet(googlePlaces);
- HttpResponse placesResponse = placesClient.execute(placesGet);
- StatusLine placeSearchStatus = placesResponse.getStatusLine();
- if (placeSearchStatus.getStatusCode() == 200) {
- HttpEntity placesEntity = placesResponse.getEntity();
- InputStream placesContent = placesEntity.getContent();
- InputStreamReader placesInput = new InputStreamReader(placesContent);
- BufferedReader placesReader = new BufferedReader(placesInput);
- String lineIn;
- while ((lineIn = placesReader.readLine()) != null) {
- placesBuilder.append(lineIn);
- }
- Log.d("SearchPlaces2: ",placesBuilder.toString());
- return placesBuilder.toString();
- }
- }
- catch(Exception e){
- e.printStackTrace();
- }
- return null;
- }
- protected void onPostExecute(String result){
- placeMarkers = new Marker[MAX_PLACES];
- if(placeMarkers!=null){
- for(int i=0; i<placeMarkers.length; i++){
- if(placeMarkers[i]!=null)
- placeMarkers[i].remove();
- }
- }
- try{
- JSONObject resultObject = new JSONObject(result);
- JSONArray placesArray = resultObject.getJSONArray("results");
- places = new MarkerOptions[placesArray.length()];
- for ( int j=0;j<placesArray.length();j++){
- LatLng placeLL=null;
- String placeName="";
- String vicinity="";
- // String open ="";
- try{
- JSONObject placeObject = placesArray.getJSONObject(j);
- JSONObject loc = placeObject.getJSONObject("geometry").getJSONObject("location");
- placeLL = new LatLng(
- Double.valueOf(loc.getString("lat")),
- Double.valueOf(loc.getString("lng")));
- // open = placeObject.getString("open_now");
- vicinity = placeObject.getString("vicinity");
- placeName = placeObject.getString("name");
- }
- catch(JSONException jse){
- missingValue=true;
- jse.printStackTrace();
- }
- if(missingValue) places[j]=null;
- else
- places[j]=new MarkerOptions()
- .position(placeLL)
- .title(placeName)
- .snippet(vicinity);
- // .snippet("This is" + open);
- }
- } catch (Exception e){
- e.printStackTrace();
- }
- boolean added = false;
- LatLngBounds.Builder builder = new LatLngBounds.Builder();
- if(places!=null && placeMarkers!=null){
- for(int p=0; p<places.length && p<placeMarkers.length; p++){
- //will be null if a value was missing
- if(places[p]!=null){
- placeMarkers[p]=map.addMarker(places[p]);
- builder.include(places[p].getPosition());
- if (!added){
- builder.include(gpsLocation);
- added = true;
- }
- }
- }
- // builder.include(gpsLocation);
- }
- try{
- LatLngBounds bounds = builder.build();
- CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 200);
- map.animateCamera(cu);
- } catch (Exception e) {
- Toast.makeText(context, "No restaurants found", Toast.LENGTH_SHORT).show();
- }
- }
- }
- public boolean canConnectToGooglePlay() {
- // Checking to see if Google Play Services are available
- int googleStatus = GooglePlayServicesUtil
- .isGooglePlayServicesAvailable(getBaseContext());
- if (googleStatus != ConnectionResult.SUCCESS) {
- Log.d("Status: ", String.valueOf(googleStatus));
- if (GooglePlayServicesUtil.isUserRecoverableError(googleStatus)) {
- Dialog error = GooglePlayServicesUtil.getErrorDialog(
- googleStatus, GoogleMap.this, 1);
- if (error != null) {
- error.show();
- }
- }
- } else {
- Log.d("googleStatus: ", "Successful");
- return true;
- }
- Log.d("WARNING: ", "Cannot Connect to Google Play");
- return false;
- }
- public boolean canConnectToInternet() {
- ConnectivityManager connectivity = (ConnectivityManager) context
- .getSystemService(Context.CONNECTIVITY_SERVICE);
- if (connectivity != null) {
- NetworkInfo[] info = connectivity.getAllNetworkInfo();
- if (info != null)
- for (int i = 0; i < info.length; i++)
- if (info[i].getState() == NetworkInfo.State.CONNECTED) {
- return true;
- }
- }
- Log.d("WARNING: ", "No internet connectivity");
- return false;
- }
- public boolean canFindGPSLocation() {
- // Checking to see if JustDine has access to GPS
- GPS g = new GPS(this);
- try {
- if (g.getLocation() != null) {
- lat = g.getLatitude();
- lon = g.getLongitude();
- Log.d("gpsStatus(lat / lon): ", String.valueOf(lat) + " / "
- + String.valueOf(lon));
- gpsLocation = new LatLng(lat, lon);
- return true;
- } else {
- Log.d("gpsStatus: ", "0x00000000");
- // gpsLocation = new LatLng(50.844436, -0.119069); //Debugging
- // Cockcroft Location
- return true;
- }
- } catch (Exception e) {
- e.getMessage();
- Log.d("gpsStatus: ", e.getMessage());
- }
- Log.d("WARNING: ", "Cannot find GPS location");
- return false;
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.google_map, menu);
- return true;
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- // Handle action bar item clicks here. The action bar will
- // automatically handle clicks on the Home/Up button, so long
- // as you specify a parent activity in AndroidManifest.xml.
- int id = item.getItemId();
- if (id == R.id.action_settings) {
- Intent i = new Intent(context, Settings.class);
- i.putExtra("onItemSelected", keyWord);
- startActivity(i);
- return true;
- } else if ( id == R.id.action_advanced_search) {
- Intent i = new Intent(context, AdvancedSearch.class);
- startActivity(i);
- return true;
- }
- return super.onOptionsItemSelected(item);
- }
- @Override
- public void onLocationChanged(Location arg0) {
- Log.d("onLocationChanged: ", "Location has changed!");
- updatePlaces();
- }
- @Override
- public void onProviderDisabled(String arg0) {
- Log.d("onProviderDisabled: ","Provider has been disabled!");
- if(map!=null){
- locationManager.removeUpdates(this);
- }
- }
- @Override
- public void onProviderEnabled(String arg0) {
- Log.d("onProviderEnabled: ","Provider has been enabled!");
- locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, locManTime, locManDist, this);
- }
- @Override
- public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
- Log.d("onStatusChanged: ","A change of status has been made!");
- }
- @Override
- protected void onResume() {
- super.onResume();
- if(map!=null){
- locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, locManTime, locManDist, this);
- }
- }
- @Override
- protected void onPause() {
- super.onPause();
- if(map!=null){
- locationManager.removeUpdates(this);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement