Google地图未显示使用Google API的所有药房?

时间:2013-10-24 18:17:09

标签: android google-maps

我正在创建一个地图应用程序来显示附近的所有药房和医院。它没有显示所有药房和医院。请帮忙? 我试图降低半径,我也尝试将附近的搜索添加到我的PLACES_SEARCH_URL。 这是使用Android Google Maps API V2和Google Places API。 这是我的代码: 我的Google商家信息搜索java:

@SuppressWarnings("deprecation")
public class GooglePlaces {

        /** Global instance of the HTTP transport. */
        private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

        // Google API Key
        private static final String API_KEY = "";

        // Google Places serach url's
        private static final String PLACES_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?";
        private static final String PLACES_TEXT_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?";
        private static final String PLACES_DETAILS_URL = "https://maps.googleapis.com/maps/api/place/details/json?";

        private double _latitude;
        private double _longitude;
        private double _radius;

        /**
         * Searching places
         * @param latitude - latitude of place
         * @params longitude - longitude of place
         * @param radius - radius of searchable area
         * @param types - type of place to search
         * @return list of places
         * */
        public PlacesList search(double latitude, double longitude, double radius, String types)
                throws Exception {

            this._latitude = latitude;
            this._longitude = longitude;
            this._radius = radius;

            try {

                HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
                HttpRequest request = httpRequestFactory
                        .buildGetRequest(new GenericUrl(PLACES_SEARCH_URL));
                request.getUrl().put("key", API_KEY);
                request.getUrl().put("location", _latitude + "," + _longitude);
                request.getUrl().put("radius", _radius); // in meters
                request.getUrl().put("sensor", "false");
                if(types != null)
                    request.getUrl().put("types", types);

                PlacesList list = request.execute().parseAs(PlacesList.class);
                // Check log cat for places response status
                if(list.next_page_token != null || list.next_page_token != "")
                {
                     Thread.sleep(4000);
                     /*Since the token can be used after a short time it has been generated*/
                     request.getUrl().put("pagetoken",list.next_page_token);
                     PlacesList temp = request.execute().parseAs(PlacesList.class);
                     list.results.addAll(temp.results);

                      if(temp.next_page_token!=null||temp.next_page_token!="")
                      {
                        Thread.sleep(4000);
                        request.getUrl().put("pagetoken",temp.next_page_token);
                        PlacesList tempList =  request.execute().parseAs(PlacesList.class);
                        list.results.addAll(tempList.results);
                     }
                }
                Log.d("Places Status", "" + list.status);
                return list;

            } catch (HttpResponseException e) {
                Log.e("Error:", e.getMessage());
                return null;
            }

        }

        /**
         * Searching single place full details
         * @param refrence - reference id of place
         *                 - which you will get in search api request
         * */
        public PlaceDetails getPlaceDetails(String reference) throws Exception {
            try {

                HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
                HttpRequest request = httpRequestFactory
                        .buildGetRequest(new GenericUrl(PLACES_DETAILS_URL));
                request.getUrl().put("key", API_KEY);
                request.getUrl().put("reference", reference);
                request.getUrl().put("sensor", "false");

                PlaceDetails place = request.execute().parseAs(PlaceDetails.class);

                return place;

            } catch (HttpResponseException e) {
                Log.e("Error in Perform Details", e.getMessage());
                throw e;
            }
        }

        /**
         * Creating http request Factory
         * */
        public static HttpRequestFactory createRequestFactory(
                final HttpTransport transport) {
            return transport.createRequestFactory(new HttpRequestInitializer() {
                public void initialize(HttpRequest request) {
                    GoogleHeaders headers = new GoogleHeaders();
                    headers.setApplicationName("AndroidHive-Places-Test");
                    request.setHeaders(headers);
                    JsonHttpParser parser = new JsonHttpParser(new JacksonFactory());
                    request.addParser(parser);
                }
            });
        }

        public static String getPlacesTextSearchUrl() {
            return PLACES_TEXT_SEARCH_URL;
        }

}

我的主要活动java:

public class MainActivity 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 btnList;
    Button btnHospital;
    Button btnPharmacy;

    // Progress dialog
    ProgressDialog pDialog;

    // Places Listview
    ListView lv;

 // Google Map
    private GoogleMap googleMap;

    double latitude;
    double longitude;

    // 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


    ListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    cd = new ConnectionDetector(getApplicationContext());

    // Check if Internet present
    isInternetPresent = cd.isConnectingToInternet();
    if (!isInternetPresent) {
        // Internet Connection is not present
        alert.showAlertDialog(MainActivity.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(MainActivity.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
    Button btnHospital = (Button) findViewById(R.id.buttonHospital);
    Button btnList = (Button) findViewById(R.id.buttonList);
    Button btnPharmacy = (Button) findViewById(R.id.buttonPharmacy);

    // 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 */
    btnHospital.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent i = new Intent(MainActivity.this,
                    HospitalActivity.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);
        }
    });

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

        @Override
        public void onClick(View arg0) {
            Intent i = new Intent(MainActivity.this,
                    PharmacyActivity.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);
        }
    });

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

        @Override
        public void onClick(View arg0) {
            Intent i = new Intent(MainActivity.this,
                    DisplayPlacesListActivity.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> {

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

            // Radius in meters - increase this value if you don't find any places
            double radius = 50000; // 90000 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);
                        }

                        // Adding data into listview
//                        lv.setAdapter(adapter);

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

        try {
            // Loading map
            initilizeMap();

        } catch (Exception e) {
            e.printStackTrace();
        }
        double lat;
        double lng;

        lat = gps.getLatitude();
        lng = gps.getLongitude();
        // Show user’s current location on the map
     // create marker
            MarkerOptions markerC = new MarkerOptions().position(new LatLng(lat,lng));

            // Changing marker icon
            markerC.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_grey));

        // adding marker
        googleMap.addMarker(markerC);

        CameraPosition cameraPosition = new CameraPosition.Builder().target(

               new LatLng(lat,lng)).zoom(10).build();

        //Double.toString(gps.getLongitude()

        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        // My location button will be used to move map to your current location
        googleMap.getUiSettings().setMyLocationButtonEnabled(false);

        // check for null in case it is null
        if (nearPlaces.results != null) {
            // loop through all the places
            for (Place place : nearPlaces.results) {
                latitude = place.geometry.location.lat; // latitude
                longitude = place.geometry.location.lng; // longitude

                // create marker
                MarkerOptions markerP = new MarkerOptions().position(new LatLng(latitude, longitude)).title(place.name + ", " + place.vicinity);

                 if (place.types.get(0).equals("hospital")) {

                    // Changing marker icon
                        markerP.icon(BitmapDescriptorFactory.fromResource(R.drawable.redcross3));
                    }
                    else
                    {
                        markerP.icon(BitmapDescriptorFactory.fromResource(R.drawable.rxblue2));
                    }
                // adding marker
                googleMap.addMarker(markerP);
            }
        }
    }       
}
/**
 * function to load map. If map is not created it will create it for you
 * */
private void initilizeMap() {
    if (googleMap == null) {
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();

        // check if map is created successfully or not
        if (googleMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

0 个答案:

没有答案