Android Near by places over Google Map

Android Near by places over Google Map

Today I explain the code for the google map
Search a place near your location and you may switch a view between map and satellite-view


First thing you may have configure Google Play Services Library in Eclipse , then get the API key for the google map.

Do the following entries on the Android Manifest file on the application tag

<meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="--Your API Keys--" />
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" /> 
 
 

Now create a Layout with the google map as well as Auto Complete editView 

 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical" >

<FrameLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:gravity="top" >

<com.google.android.gms.maps.MapView
android:id="@+id/map_google"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/txt_totalHotels" />

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@color/white" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<com.packagename.views.CustomAutoCompleteTextView
android:id="@+id/edt_location"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/dist_five"
android:layout_marginRight="@dimen/dist_five"
android:layout_marginTop="@dimen/dist_five"
android:layout_weight="0.8"
android:background="@drawable/shape_searchbox"
android:hint="Search location "
android:padding="@dimen/dist_five"
android:singleLine="true"
android:textColor="@color/black"
android:textColorHint="@color/gray"
android:textCursorDrawable="@null"
android:textSize="@dimen/font_16" />

<ImageView
android:id="@+id/btn_delSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="0.005"
android:src="@drawable/close_icon"
android:visibility="invisible" />

<Button
android:id="@+id/btn_find"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_margin="@dimen/dist_two"
android:layout_toRightOf="@+id/edt_from"
android:layout_weight="0.2"
android:background="@color/light_grey"
android:text="@string/str_btn_find"
android:textAllCaps="true"
android:textSize="@dimen/font_14"
android:textStyle="bold" />
</LinearLayout>

<RadioGroup
android:id="@+id/rg_views"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:visibility="visible" >

<RadioButton
android:id="@+id/rb_normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="@string/str_rb_normal" />

<RadioButton
android:id="@+id/rb_satellite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/str_rb_satellite" />

<RadioButton
android:id="@+id/rb_terrain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
android:text="@string/str_rb_terrain" />
</RadioGroup>
</LinearLayout>

</FrameLayout>

</RelativeLayout>

 
Create a MainActivity as follows

public class MainActivity extends Activity implements OnClickListener,
OnMarkerClickListener {
  private GoogleMap googleMap;
   private MapView googleMapView;
   private static View view = null;
   private static GoogleMap mMap;
   private static Double latitude1, longitude1;
   List<Marker> markerList = new ArrayList<Marker>();
   Marker marker, location_marker = null;;
   float zoomCounter = 2.0f;
  
  private com.packagename.views.CustomAutoCompleteTextView edt_location;
  ImageView btn_delSearch;
  Button btn_find;
  RadioGroup rgViews ;
  
   PlacesTask placesTask;
   ParserTask parserTask;
 

@Override
public void onCreate(Bundle savedInstanceState) {                                                 super.onCreate(savedInstanceState);
           setContentView(R.layout.mapview);

          googleMapView = (MapView) findViewById(R.id.map_google);
          googleMapView.onCreate(savedInstanceState);
          googleMapView.onResume();

          btn_find = (Button) view.findViewById(R.id.btn_find);
          btn_find.setOnClickListener(this);
          edt_location = (com.packagename.views.CustomAutoCompleteTextView)
.         findViewById(R.id.edt_location);

          btn_delSearch = (ImageView) view.findViewById(R.id.btn_delSearch);       
          btn_delSearch.setOnClickListener(this);
      
          rgViews = (RadioGroup) findViewById(R.id.rg_views);
          rgViews.setOnCheckedChangeListener(new OnCheckedChangeListener() {
          @Override
         public void onCheckedChanged(RadioGroup group, int checkedId) {
              if(checkedId == R.id.rb_normal){
                    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
               }else if(checkedId == R.id.rb_satellite){
                      googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
               }else if(checkedId == R.id.rb_terrain){
                      googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
                }
             }
         });

            initilizeMap();
 
          edt_location.showDropDown();
          edt_location.addTextChangedListener(new TextWatcher() {

           @Override
           public void onTextChanged(CharSequence s, int start, int before,
                                         int count) {
                          // TODO Auto-generated method stub
                 if (s.length() > 0) {
                          btn_delSearch.setVisibility(View.VISIBLE);
                  } else {
                          btn_delSearch.setVisibility(View.INVISIBLE);
                  }
                  placesTask = new PlacesTask();
                  placesTask.execute(s.toString());
             }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                  int after) {
                  // TODO Auto-generated method stub
             }
             @Override
             public void afterTextChanged(Editable s) {
                  // TODO Auto-generated method stub
             }
        });
 
  }
  
private void initilizeMap() {
            if (googleMap == null) {
                try {
                  MapsInitializer.initialize(getActivity().getApplicationContext());
                } catch (Exception e) {
                       e.printStackTrace();
               }
                googleMap = googleMapView.getMap();
                googleMap.setMyLocationEnabled(false);
                googleMap.getUiSettings().setCompassEnabled(false);
                googleMap.getUiSettings().setRotateGesturesEnabled(false);
                googleMap.getUiSettings().setZoomControlsEnabled(false);
                googleMap.setOnMarkerClickListener(this);
               if(Parislat.size()>0 && Parislat.size()>0){
                  googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                  new LatLng(Parislat.get(Parislat.size() / 2), Parislog
                      .get(Parislat.size() / 2)), 7));
                  googleMap.animateCamera(CameraUpdateFactory.zoomTo(14), 2000, null);
                  
            }
        }
            setMarkers();
  }

public void setMarkers() {
            googleMap.addMarker(new MarkerOptions()
                 .position(new LatLng(93.13355456, 72.18549878))
                .icon(BitmapDescriptorFactory
                .fromResource(R.drawable.marker_icon))
                .draggable(false));
    }
  
    @Override
      public void onResume() {
          super.onResume();
            if (googleMapView != null)
                googleMapView.onResume();
         }

        @Override
          public void onPause() {
                super.onPause();
                if (googleMapView != null)
                      googleMapView.onPause();
           }

         @Override
          public void onDestroy() {
              super.onDestroy();
              if (googleMapView != null)
                   googleMapView.onDestroy();
           }
 
            @Override
            public void onLowMemory() {
                super.onLowMemory();
                 if (googleMapView != null)
                      googleMapView.onLowMemory();
           }

            
      // Fetches all places from GooglePlaces AutoComplete Web Service
          private class PlacesTask extends AsyncTask<String, Void, String> {
             @Override
              protected String doInBackground(String... place) {
               // For storing data from web service
                 String data = "";
                     // Obtain browser key from https://code.google.com/apis/console
                  String key = "key=AIzaSyCe8sFv84nUTd9ikhbdvl1swxtuImCAXR8";
                  String input = "";
                 try {
                       input = "input=" + URLEncoder.encode(place[0], "utf-8");
                   } catch (UnsupportedEncodingException e1) {
                        e1.printStackTrace();
               }
               // place type to be searched
               String types = "types=geocode";
                // Sensor enabled
               String sensor = "sensor=false";
                 // Building the parameters to the web service
               String parameters = input + "&" + types + "&" + sensor + "&" + key;
                // Output format
                String output = "json";
                // Building the url to the web service
                String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"
                            + output + "?" + parameters;
                 System.err.println("Google place url ==> "+url);
               try {
                   // Fetching the data from we service
                        data = downloadUrl(url);
                   } catch (Exception e) {
                     Log.d("Background Task", e.toString());
                 }
                 return data;
             }
             @Override
               protected void onPostExecute(String result) {
                super.onPostExecute(result);
                 System.err.println("result of PlacesTask " + result);
                 // Creating ParserTask
                 parserTask = new ParserTask();
                 // Starting Parsing the JSON string returned by Web Service
                parserTask.execute(result);
           }
}

         /** A class to parse the Google Places in JSON format */
          private class ParserTask extends
               AsyncTask<String, Integer, List<HashMap<String, String>>> {
                  JSONObject jObject;
             @Override
             protected List<HashMap<String, String>> doInBackground(
                     String... jsonData) {
             List<HashMap<String, String>> places = null;
             PlaceJSONParser_new placeJsonParser = new PlaceJSONParser_new();
          try {
                jObject = new JSONObject(jsonData[0]);
               // Getting the parsed data as a List construct
                places = placeJsonParser.parse(jObject);
             } catch (Exception e) {
                 Log.d("Exception", e.toString());
           }
           return places;
       }

       @Override
        protected void onPostExecute(List<HashMap<String, String>> result) {
               System.err.println("result of ParserTask " + result);
               String[] from = new String[] { "description" };
               int[] to = new int[] { R.id.txt_locationName };
               // Creating a SimpleAdapter for the AutoCompleteTextView
               SimpleAdapter adapter = new SimpleAdapter(getActivity(), result,
                   R.layout.item_list, from, to);
                // Setting the adapter
              edt_location.setAdapter(adapter);
              adapter.notifyDataSetChanged();
             // edt_location.showDropDown();
       }
   }


 
          private String downloadUrl(String strUrl) throws IOException {
             String data = "";
             InputStream iStream = null;
             HttpURLConnection urlConnection = null;
        try {
               URL url = new URL(strUrl);
               // Creating an http connection to communicate with url
               urlConnection = (HttpURLConnection) url.openConnection();
                  // Connecting to url
                urlConnection.connect();
                   // Reading data from url
                iStream = urlConnection.getInputStream();
               BufferedReader br = new BufferedReader(new InputStreamReader(
                       iStream));
                StringBuffer sb = new StringBuffer();
                String line = "";
                while ((line = br.readLine()) != null) {
                         sb.append(line);
                 }
                  data = sb.toString();
                  br.close();
              } catch (Exception e) {
                    Log.d("Exception while downloading url", e.toString());
            } finally {
                    iStream.close();
                    urlConnection.disconnect();
            }
          return data;
   }

 Write a button click event for the find button which will show the location with marker
    
      @Override
        public void onClick(View v) {
             switch (v.getId()) {
               case R.id.btn_find:
                     new GetLatLongName().execute();
               break;
              case R.id.btn_delSearch:
                    edt_location.setText("");
              break;
             default:
                   break;
             }
     }

public class GetLatLongName extends AsyncTask<Void, Void, Void> {
    List<LatLng> ll_from;
    List<LatLng> ll_to;
    String location_from;
    ProgressDialog progressDialog;
    String location_to;
    public GetLatLongName() {
    }

   @Override
    protected void onPreExecute() {
      // TODO Auto-generated method stub
       super.onPreExecute();
        progressDialog = ProgressDialog.show(getActivity(), "Wait",
           "Synchronizing...");
         progressDialog.setContentView(R.layout.map_loader);
     }
       @Override
       protected Void doInBackground(Void... params) {
           // TODO Auto-generated method stub
        try {
             if (Geocoder.isPresent()) {
                 try {
                      System.err.println("lenght of location   text"+edt_location.getText().toString().length());
   {
           location_from = edt_location.getText().toString();
          Geocoder gc_from = new Geocoder(getActivity(),
          Locale.getDefault());
          List<Address> addresses_from = gc_from.getFromLocationName(location_from, 1);
          ll_from = new ArrayList<LatLng>( addresses_from.size());
          for (Address a : addresses_from) {
          if (a.hasLatitude() && a.hasLongitude()) {
                  ll_from.add(new LatLng(a.getLatitude(), a.getLongitude()));
         }
  }
          for (int i = 0; i < ll_from.size(); i++) {
             System.err.println("lat " + ll_from.get(i).latitude + " long "
                  + ll_from.get(i).longitude);
        }
         location_to = edt_location.getText().toString();
          Geocoder gc_to = new Geocoder(getActivity(),
           Locale.getDefault());
           List<Address> addresses_to = gc_to.getFromLocationName(location_to, 1);
            ll_to = new ArrayList<LatLng>(addresses_to.size()); 
           for (Address a : addresses_to) {
               if (a.hasLatitude() && a.hasLongitude()) {
                    ll_to.add(new LatLng(a.getLatitude(), a.getLongitude()));
             }
   }
        for (int i = 0; i < ll_to.size(); i++) {
               System.err.println("lat "+ ll_to.get(i).latitude + " long "
                 + ll_to.get(i).longitude);
         }
     }
  } catch (IOException e) {
        // handle the exception
           e.printStackTrace();
      }
   }
  } catch (Exception e) {
   e.printStackTrace();
}
return null;
}

           @Override
             protected void onPostExecute(Void result) {
              // TODO Auto-generated method stub
             super.onPostExecute(result);
                Display_route(ll_from, ll_to, location_from, location_to);
                 progressDialog.dismiss();
     }
}

 Write a Display Rout function which will draw the marker for the resultant place

 
GMapV2Direction md;

      private void Display_route(List<LatLng> ll_from2, List<LatLng> ll_to2,
                String str_from, String str_to) {
                  // TODO Auto-generated method stub

             LatLng fromPosition = new LatLng(ll_from2.get(0).latitude,
                           ll_from2.get(0).longitude);

             LatLng toPosition = new LatLng(ll_to2.get(0).latitude,
                           ll_to2.get(0).longitude);
                md = new GMapV2Direction();

                 googleMap.clear();
             
              LatLng coordinates = new LatLng(ll_from2.get(0).latitude,
              ll_from2.get(0).longitude);

              location_marker = googleMap.addMarker(new MarkerOptions().position(
               fromPosition).title(str_from));

             googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 4));
             googleMap.animateCamera(CameraUpdateFactory.zoomTo(13), 2000, null);

    }

 

}
 
Following is the output 


 
 
 
The above red marker indicate the selected place from the drop down
 
 
 
             
                                       Thanks

               

                
            
        

        

        
        

Comments

Popular posts from this blog

API calling using AsyncHttpClient

Android Interview Material

Crypto JS Encryption & Decryption in Android