Implementing Google Places Api
I have been trying for the last couple days to find a simple tutorial on this but it seems like there is no such thing as simple with google's API. Here is what I know so far step
Solution 1:
Here is reference for all you need ..
https://developers.google.com/places/documentation/ANDhttps://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/MapFragment
And you can use same some thing like undermentioned ..
Check this simple class that implements all you need
publicclassMainActivityextendsFragmentActivityimplementsOnClickListener {
private GoogleMap myMap;
Polyline line;
Context context;
Location location;
booleancheck_provider_enabled=false;
// Static LatLngLatLngstartLatLng=newLatLng(30.707104, 76.690749);
LatLngendLatLng=newLatLng(30.721419, 76.730017);
publicvoidonCreate(Bundle bd) {
super.onCreate(bd);
setContentView(R.layout.activity_main);
context = MainActivity.this;
// GoogleMap myMap
myMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
/*
// Construct a CameraPosition focusing on Mountain View and animate the camera to that position.
CameraPosition cameraPosition = new CameraPosition.Builder()
//.target(endLatLng) // Sets the center of the map to Mountain View
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(30) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
myMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));*/
myMap.setMyLocationEnabled(true);
myMap.moveCamera(CameraUpdateFactory.newLatLng(startLatLng));
myMap.animateCamera(CameraUpdateFactory.zoomTo(12));
myMap.getUiSettings().setZoomControlsEnabled(false);
LocationManagerservice= (LocationManager) getSystemService(LOCATION_SERVICE);
booleanenabled= service.isProviderEnabled(LocationManager.GPS_PROVIDER);
location = service.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// check if enabled and if not send user to the GSP settings// Better solution would be to display a dialog and suggesting to // go to the settingsif (!enabled) {
/*Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);*/Intentintent=newIntent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Enable GPS servcies to use this app.", Toast.LENGTH_LONG).show();
} else{
try{
finalLatLngPERTH=newLatLng(-31.90, 115.86);
Markerperth= myMap.addMarker(newMarkerOptions()
.position(PERTH)
.anchor((float)0.5,(float)0.5)
.rotation((float)90.0));
StringurlTopass= makeURL(startLatLng.latitude,
startLatLng.longitude, endLatLng.latitude,
endLatLng.longitude);
// new connectAsyncTask(urlTopass).execute();
}catch(Exception e){
e.printStackTrace();
}
}
/* if (myMap!=null){
Marker hamburg = myMap.addMarker(new MarkerOptions().position(startLatLng)
.title("Hamburg"));
Marker kiel = myMap.addMarker(new MarkerOptions()
.position(endLatLng)
.title("Vivek")
.snippet("VIVEK's ANDROID HACKER")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.one)));
}*/// Now auto clicking the button// btntemp.performClick();
}
/*
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_pass_home_call_temp:
String urlTopass = makeURL(startLatLng.latitude,
startLatLng.longitude, endLatLng.latitude,
endLatLng.longitude);
new connectAsyncTask(urlTopass).execute();
break;
default:
break;
}
}*/privateclassconnectAsyncTaskextendsAsyncTask<Void, Void, String> {
private ProgressDialog progressDialog;
String url;
connectAsyncTask(String urlPass) {
url = urlPass;
}
@OverrideprotectedvoidonPreExecute() {
// TODO Auto-generated method stubsuper.onPreExecute();
progressDialog = newProgressDialog(context);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
@Overrideprotected String doInBackground(Void... params) {
JSONParserjParser=newJSONParser();
Stringjson= jParser.getJSONFromUrl(url);
return json;
}
@OverrideprotectedvoidonPostExecute(String result) {
super.onPostExecute(result);
progressDialog.hide();
if (result != null) {
drawPath(result);
}
}
}
public String makeURL(double sourcelat, double sourcelog, double destlat,
double destlog) {
StringBuilderurlString=newStringBuilder();
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append(Double.toString(sourcelat));
urlString.append(",");
urlString.append(Double.toString(sourcelog));
urlString.append("&destination=");// to
urlString.append(Double.toString(destlat));
urlString.append(",");
urlString.append(Double.toString(destlog));
urlString.append("&sensor=false&mode=driving&alternatives=true");
return urlString.toString();
}
publicclassJSONParser {
InputStreamis=null;
JSONObjectjObj=null;
Stringjson="";
// constructorpublicJSONParser() {
}
public String getJSONFromUrl(String url) {
// Making HTTP requesttry {
// defaultHttpClientDefaultHttpClienthttpClient=newDefaultHttpClient();
HttpPosthttpPost=newHttpPost(url);
HttpResponsehttpResponse= httpClient.execute(httpPost);
HttpEntityhttpEntity= httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReaderreader=newBufferedReader(
newInputStreamReader(is, "iso-8859-1"), 8);
StringBuildersb=newStringBuilder();
Stringline=null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
publicvoiddrawPath(String result) {
if (line != null) {
myMap.clear();
}
myMap.addMarker(newMarkerOptions().position(endLatLng).icon(
BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
myMap.addMarker(newMarkerOptions().position(startLatLng).icon(
BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
try {
// Tranform the string into a json objectfinalJSONObjectjson=newJSONObject(result);
JSONArrayrouteArray= json.getJSONArray("routes");
JSONObjectroutes= routeArray.getJSONObject(0);
JSONObjectoverviewPolylines= routes
.getJSONObject("overview_polyline");
StringencodedString= overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);
PolylineOptionsoptions=newPolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (intz=0; z < list.size(); z++) {
LatLngpoint= list.get(z);
options.add(point);
}
line = myMap.addPolyline(options);
/*for (int z = 0; z < list.size() - 1; z++) {
LatLng src = list.get(z);
LatLng dest = list.get(z + 1);
line = myMap.addPolyline(new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude),
new LatLng(dest.latitude, dest.longitude))
.width(5).color(Color.BLUE).geodesic(true));
}*/
} catch (Exception e) {
e.printStackTrace();
}
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = newArrayList<LatLng>();
intindex=0, len = encoded.length();
intlat=0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
intdlat= ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
intdlng= ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLngp=newLatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
@OverridepublicvoidonClick(View arg0) {
// TODO Auto-generated method stub
}
/*@Override
public void onMarkerDrag(Marker marker) {
//add the marker's latlng in a arraylist of LatLng and pass it to the loop
for (int i = 0; i < arraylistoflatlng.size(); i++) {
myMap.addPolyline(new PolylineOptions()
.addAll(arraylistoflatlng)
.width(5)
.color(Color.RED));
}
}*/
}
That's it. You are good to go. Cheers!
Solution 2:
here is the code for implementing google places. Following is the xml file
<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
<RelativeLayoutandroid:layout_width="0dp"android:layout_height="fill_parent"android:layout_weight="1"android:padding="10dp"><ListViewandroid:id="@+id/list"android:layout_width="fill_parent"android:layout_height="250dp" /></RelativeLayout></LinearLayout>
here is the code that has to be written in the java file
ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
// KEY Stringspublicstatic String KEY_REFERENCE = "reference"; // id of the placepublicstatic String KEY_NAME = "name"; // name of the placepublicstatic String KEY_VICINITY = "vicinity"; // Place area name
lv = (ListView) findViewById(R.id.list);
// calling background Async task to load Google Places// After getting places from Google all the data is shown in listviewnew LoadPlaces().execute();
classLoadPlacesextendsAsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protectedvoidonPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(PlacesActivity.this);
pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */protected String doInBackground(String... args) {
// creating Places class object
googlePlaces = new GooglePlaces();
try {
// Separeate your place types by PIPE symbol "|"// If you want all types places make it as null// Check list of types supported by google//
String types; // Listing places only cafes, restaurantsif(searchtype.equals("hotel"))
types = "cafe|restaurant|bakery|lodging|meal_delivery|meal_takeaway|";
// Radius in meters - increase this value if you don't find any placesdouble radius = 1000; // 1000 meters // get nearest places
nearPlaces = googlePlaces.search(gps.getLatitude(),
gps.getLongitude(), radius, types);
} catch (Exception e) {
e.printStackTrace();
}
returnnull;
}
/**
* After completing background task Dismiss the progress dialog
* and show the data in UI
* Always use runOnUiThread(new Runnable()) to update UI from background
* thread, otherwise you will get error
* **/protectedvoidonPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
publicvoidrun() {
/**
* Updating parsed Places into LISTVIEW
* */// Get json response status
String status = nearPlaces.status;
// Check for all possible statusif(status.equals("OK")){
// Successfully got places detailsif (nearPlaces.results != null) {
// loop through each place
SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
GoogleMap Mmap=mapFrag.getMap();
LatLng start=new LatLng(gps.getLatitude(), gps.getLongitude());
md.showmap(Mmap, start);
sm.setmarker(PlacesActivity.this, Mmap,gps.getLatitude(), gps.getLongitude(), "You", R.drawable.mark_blue);
for (Place p : nearPlaces.results) {
HashMap<String, String> map = new HashMap<String, String>();
// Place reference won't display in listview - it will be hidden// Place reference is used to get "place full details"
map.put(KEY_REFERENCE, p.reference);
// Place name
map.put(KEY_NAME, p.name);
sm.setmarker(PlacesActivity.this, Mmap, p.geometry.location.lat, p.geometry.location.lng, p.name, R.drawable.mark_red);
// adding HashMap to ArrayList
placesListItems.add(map);
}
// list adapter
ListAdapter adapter = new SimpleAdapter(PlacesActivity.this, placesListItems,
R.layout.list_item,
new String[] { KEY_REFERENCE, KEY_NAME}, newint[] {
R.id.reference, R.id.name });
// Adding data into listview
lv.setAdapter(adapter);
}
}
elseif(status.equals("ZERO_RESULTS")){
// Zero results found
alert.showAlertDialog(PlacesActivity.this, "Near Places",
"Sorry no places found. Try to change the types of places",
false);
}
elseif(status.equals("UNKNOWN_ERROR"))
{
alert.showAlertDialog(PlacesActivity.this, "Places Error",
"Sorry unknown error occured.",
false);
}
elseif(status.equals("OVER_QUERY_LIMIT"))
{
alert.showAlertDialog(PlacesActivity.this, "Places Error",
"Sorry query limit to google places is reached",
false);
}
elseif(status.equals("REQUEST_DENIED"))
{
alert.showAlertDialog(PlacesActivity.this, "Places Error",
"Sorry error occured. Request is denied",
false);
}
elseif(status.equals("INVALID_REQUEST"))
{
alert.showAlertDialog(PlacesActivity.this, "Places Error",
"Sorry error occured. Invalid Request",
false);
}
else
{
alert.showAlertDialog(PlacesActivity.this, "Places Error",
"Sorry error occured.",
false);
}
}
});
}
}
Post a Comment for "Implementing Google Places Api"