简体   繁体   English

使用Google Places API查找附近的地方

[英]find nearby places using Google Places api

I followed a tut regarding finding nearby places using places api and tried to integrate it in my app. 我跟随一个关于使用place api查找附近地点的教程,尝试将其集成到我的应用程序中。 The nearyplaceactivity is runninng but place results are not showing up. Nearyplaceactivity正在运行,但是放置结果未显示。 Dont know wat is wrong coz the code is almost same as what the tutorial mentioned. 不知道wat是错误的,因为代码与本教程中提到的几乎相同。 Below is my code. 下面是我的代码。 If anyone could help, i would be really grateful... The tut link is http://www.androidhive.info/2012/08/android-working-with-google-places-and-maps-tutorial/ 如果有人可以帮忙,我将非常感激... tut链接为http://www.androidhive.info/2012/08/android-working-with-google-places-and-maps-tutorial/

NearbyPlacesActivity.java 附近的地方活动.java

package com.example.travelplanner;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;


public class NearbyPlacesActivity extends Activity {

    // flag for Internet connection status
    Boolean isInternetPresent = false;

    // Connection detector class
    ConnectionDetector cd;

    // Alert Dialog Manager
    AlertDialogManager alert = new AlertDialogManager();

    // Google Places
    GooglePlaces googlePlaces;

    // Places List
    PlacesList nearPlaces;

    // GPS Location
    GPSTracker gps;

    // Button
    Button btnShowOnMap;

    // Places Listview
    ListView lv;

    // ListItems data
    ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();


    // KEY Strings
    public static String KEY_REFERENCE = "reference"; // id of the place
    public static String KEY_NAME = "name"; // name of the place
    public static String KEY_VICINITY = "vicinity"; // Place area name

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

        cd = new ConnectionDetector(getApplicationContext());

        // Check if Internet present
        isInternetPresent = cd.isConnectingToInternet();
        if (!isInternetPresent) {
            // Internet Connection is not present
            alert.showAlertDialog(NearbyPlacesActivity.this, "Internet Connection Error",
                    "Please connect to working Internet connection", false);
            // stop executing code by return
            return;
        }

        // creating GPS Class object
        gps = new GPSTracker(this);

        // check if GPS location can get
        if (gps.canGetLocation()) {
            Log.d("Your Location", "latitude:" + gps.getLatitude() + ", longitude: " + gps.getLongitude());
        } else {
            // Can't get user's current location
            alert.showAlertDialog(NearbyPlacesActivity.this, "GPS Status",
                    "Couldn't get location information. Please enable GPS",
                    false);
            // stop executing code by return
            return;
        }

        // Getting listview
        lv = (ListView) findViewById(R.id.list);

        // button show on map
        btnShowOnMap = (Button) findViewById(R.id.btn_show_map);

        // calling background Async task to load Google Places
        // After getting places from Google all the data is shown in listview
        new LoadPlaces().execute();

        /** Button click event for shown on map */
        btnShowOnMap.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent i = new Intent(getApplicationContext(),
                        PlacesMapActivity.class);
                // Sending user current geo location
                i.putExtra("user_latitude", Double.toString(gps.getLatitude()));
                i.putExtra("user_longitude", Double.toString(gps.getLongitude()));

                // passing near places to map activity
                i.putExtra("near_places", nearPlaces);
                // staring activity
                startActivity(i);
            }
        });


        /**
         * ListItem click event
         * On selecting a listitem SinglePlaceActivity is launched
         * */
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String reference = ((TextView) view.findViewById(R.id.reference)).getText().toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        SinglePlaceActivity.class);

                // Sending place refrence id to single place activity
                // place refrence id used to get "Place full details"
                in.putExtra(KEY_REFERENCE, reference);
                startActivity(in);
            }
        });
    }

    /**
     * Background Async Task to Load Google places
     * */
    class LoadPlaces extends AsyncTask<String, String, String> {

        // Progress dialog
        ProgressDialog pDialog;
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(NearbyPlacesActivity.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 = "cafe|restaurant"; // Listing places only cafes, restaurants

                // Radius in meters - increase this value if you don't find any places
                double radius = 1000; // 1000 meters 

                // get nearest places
                nearPlaces = googlePlaces.search(gps.getLatitude(),
                        gps.getLongitude(), radius, types);


            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        /**
         * 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
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed Places into LISTVIEW
                     * */
                    // Get json response status
                    String status = nearPlaces.status;

                    // Check for all possible status
                    if(status.equals("OK")){
                        // Successfully got places details
                        if (nearPlaces.results != null) {
                            // loop through each place
                            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);


                                // adding HashMap to ArrayList
                                placesListItems.add(map);
                            }
                            // list adapter
                            ListAdapter adapter = new SimpleAdapter(NearbyPlacesActivity.this, placesListItems,
                                    R.layout.list_item,
                                    new String[] { KEY_REFERENCE, KEY_NAME}, new int[] {
                                            R.id.reference, R.id.name });

                            // Adding data into listview
                            lv.setAdapter(adapter);
                        }
                    }
                    else if(status.equals("ZERO_RESULTS")){
                        // Zero results found
                        alert.showAlertDialog(NearbyPlacesActivity.this, "Near Places",
                                "Sorry no places found. Try to change the types of places",
                                false);
                    }
                    else if(status.equals("UNKNOWN_ERROR"))
                    {
                        alert.showAlertDialog(NearbyPlacesActivity.this, "Places Error",
                                "Sorry unknown error occured.",
                                false);
                    }
                    else if(status.equals("OVER_QUERY_LIMIT"))
                    {
                        alert.showAlertDialog(NearbyPlacesActivity.this, "Places Error",
                                "Sorry query limit to google places is reached",
                                false);
                    }
                    else if(status.equals("REQUEST_DENIED"))
                    {
                        alert.showAlertDialog(NearbyPlacesActivity.this, "Places Error",
                                "Sorry error occured. Request is denied",
                                false);
                    }
                    else if(status.equals("INVALID_REQUEST"))
                    {
                        alert.showAlertDialog(NearbyPlacesActivity.this, "Places Error",
                                "Sorry error occured. Invalid Request",
                                false);
                    }
                    else
                    {
                        alert.showAlertDialog(NearbyPlacesActivity.this, "Places Error",
                                "Sorry error occured.",
                                false);
                    }
                }
            });

        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.nearby_places, menu);
        return true;
    }



}

Logcat: Logcat:

06-30 09:52:03.457: E/Trace(911): error opening trace file: No such file or directory (2)
06-30 09:52:54.746: E/AndroidRuntime(911): FATAL EXCEPTION: AsyncTask #1
06-30 09:52:54.746: E/AndroidRuntime(911): java.lang.RuntimeException: An error occured while executing doInBackground()
06-30 09:52:54.746: E/AndroidRuntime(911):  at android.os.AsyncTask$3.done(AsyncTask.java:299)
06-30 09:52:54.746: E/AndroidRuntime(911):  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
06-30 09:52:54.746: E/AndroidRuntime(911):  at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
06-30 09:52:54.746: E/AndroidRuntime(911):  at java.util.concurrent.FutureTask.run(FutureTask.java:239)
06-30 09:52:54.746: E/AndroidRuntime(911):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
06-30 09:52:54.746: E/AndroidRuntime(911):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
06-30 09:52:54.746: E/AndroidRuntime(911):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
06-30 09:52:54.746: E/AndroidRuntime(911):  at java.lang.Thread.run(Thread.java:856)
06-30 09:52:54.746: E/AndroidRuntime(911): Caused by: java.lang.NoClassDefFoundError: com.google.common.base.Preconditions
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.google.api.client.util.ClassInfo.<init>(ClassInfo.java:148)
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.google.api.client.util.ClassInfo.of(ClassInfo.java:71)
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.google.api.client.util.GenericData.<init>(GenericData.java:58)
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.google.api.client.http.HttpHeaders.<init>(HttpHeaders.java:40)
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.google.api.client.http.HttpRequest.<init>(HttpRequest.java:72)
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.google.api.client.http.HttpTransport.buildRequest(HttpTransport.java:98)
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.google.api.client.http.HttpRequestFactory.buildRequest(HttpRequestFactory.java:104)
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.google.api.client.http.HttpRequestFactory.buildGetRequest(HttpRequestFactory.java:135)
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.example.travelplanner.GooglePlaces.search(GooglePlaces.java:52)
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.example.travelplanner.NearbyPlacesActivity$LoadPlaces.doInBackground(NearbyPlacesActivity.java:186)
06-30 09:52:54.746: E/AndroidRuntime(911):  at com.example.travelplanner.NearbyPlacesActivity$LoadPlaces.doInBackground(NearbyPlacesActivity.java:1)
06-30 09:52:54.746: E/AndroidRuntime(911):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
06-30 09:52:54.746: E/AndroidRuntime(911):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
06-30 09:52:54.746: E/AndroidRuntime(911):  ... 4 more

I had a similar problem running the tutorial. 我在运行本教程时遇到了类似的问题。 I changed the code in GooglePlaces.java as follows: 我将GooglePlaces.java中的代码更改如下:

/**
 * Creating http request Factory
 * */
public static HttpRequestFactory createRequestFactory(
        final HttpTransport transport) {
    return transport.createRequestFactory(new HttpRequestInitializer() {
        public void initialize(HttpRequest request) {
            JsonObjectParser parser = new JsonObjectParser(new JacksonFactory());
            request.setParser(parser);
        }
    });
}

This seemed to work for me. 这似乎对我有用。 It seems as though some of the client api's that were used in the tutorial have been deprecated. 似乎已弃用了本教程中使用的某些客户端api。 This code fixed my problem, hope it helps others out in the future. 这段代码解决了我的问题,希望以后能对其他人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM