Get opening hours of place -Android

2019-09-09 17:05发布

问题:

How to get opening hours of the place in android, I have latitude and longitude of the current location.

Setp-1: I have get the place id by calling this API 'http://maps.googleapis.com/maps/api/geocode/json?latlng=39.7837304,-100.4458825&sensor=true'

The response of this api return the array of address, from this array will get the first address place ID.

Sept-2:-

After getting place id pass this place id into this API 'https://maps.googleapis.com/maps/api/place/details/json?placeid="+placeId+"&key=API_KEY'

Problem:- Above API not return opening_hours.

Please guide.

Thanks

回答1:

Summary

This is because you're not actually looking up the business(es) at that location, you're looking up the address, and addresses don't have opening hours.

Detailed explanation

You're using Reverse Geocoding for a Latitude/Longitude, which looks up an address. Addresses don't have opening hours. Businesses at addresses do, but those are distinct places with distinct Place IDs.

You can see this this pretty plainly in the example you link to: http://maps.googleapis.com/maps/api/geocode/json?latlng=39.7837304,-100.4458825 [note that sensor is a deprecated parameter, you should omit it]. In that response the types of the results are types like route, administrative_area_level_3, postal_code, etc, clearly all entities that don't have opening hours.

Alternative

As you're on Android, you probably want to use PlaceDetectionApi.getCurrentPlace() to get the current place, rather than a reverse geocode request. This can return businesses.



回答2:

Some locations simply do not have this field. This is logically required by them also not having hours recorded in the data store for this API.

Your code should look like this:

String uriPath = "https://maps.googleapis.com/maps/api/place/details/json";
String uriParams = "?placeid=" + currentPlaceID + 
    "&key=" + GOOGLE_MAPS_WEB_API_KEY;
String uriString = uriPath + uriParams;
// Using Volley library for networking.
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JSONObject response = null;
// Required for the following JsonObjectRequest, but not really used here.
Map<String, String> jsonParams = new HashMap<String, String>();                
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,
    uriString,
    new JSONObject(jsonParams),
    new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                if (response != null) {
                    // Retrieve the result (main contents).
                    JSONObject result =
                        response.getJSONObject("result");
                    // Acquire the hours of operation.
                    try {
                        JSONObject openingHoursJSON =
                            result.getJSONObject("opening_hours");
                        // Determine whether this location 
                        // is currently open.
                        boolean openNow = 
                            openingHoursJSON.getBoolean("open_now");
                        // Record this information somewhere, like this.
                        myObject.setOpenNow(openNow);
                    } catch (JSONException e) {
                        // This `Place` has no associated 
                        // hours of operation.
                        // NOTE: to record uncertainty in the open status,
                        // the variable being set here should be a Boolean 
                        // (not a boolean) to record it this way.
                        myObject.setOpenNow(null);
                    }
                }
                // There was no response from the server (response == null).
            } catch (JSONException e) {
                // This should only happen if assumptions about the returned
                // JSON structure are invalid.
                e.printStackTrace();
            }
        } // end of onResponse()
    }, // end of Response.Listener<JSONObject>()
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(LOG_TAG, "Error occurred ", error);
        }
    }); // end of new JsonObjectRequest(...)
// Add the request to the Volley request queue.
// VolleyRequestQueue is a singleton containing a Volley RequestQueue.
VolleyRequestQueue.getInstance(mActivity).addToRequestQueue(request);

This accounts for the possibility of open hours not being available for the current day. To be clear, this is an asynchronous operation. It can be made synchronous, but that is out of the scope of this answer (and asynchronous is usually preferred).



回答3:

private GoogleApiClient mGoogleApiClient;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

    mRootView = inflater.inflate(R.layout.view, container, false);


    buildGoogleApiClient();
    mGoogleApiClient.connect();
    PendingResult<PlaceLikelihoodBuffer> placeResult = Places.PlaceDetectionApi.getCurrentPlace(mGoogleApiClient, null);
    placeResult.setResultCallback(mUpdatePlaceDetailsCallback);


    return mRootView;
}


/**
 * Creates the connexion to the Google API. Once the API is connected, the
 * onConnected method is called.
 */
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .enableAutoManage(getActivity(),0, this)
            .addApi(Places.PLACE_DETECTION_API)
            .addOnConnectionFailedListener(this)
            .addConnectionCallbacks(this)
            .build();
}



/**
 * Callback for results from a Places Geo Data API query that shows the first place result in
 * the details view on screen.
 */
private ResultCallback<PlaceLikelihoodBuffer> mUpdatePlaceDetailsCallback = new ResultCallback<PlaceLikelihoodBuffer>() {
    @Override
    public void onResult(PlaceLikelihoodBuffer places) {

        progressDialog.dismiss();
        if (!places.getStatus().isSuccess()) {
            places.release();
            return;
        }

        PlaceLikelihood placeLikelihood = places.get(0);
        Place place = placeLikelihood.getPlace();

        /**
         * get the place detail by the place id
         */
        getPlaceOperatingHours(place.getId().toString());

        places.release();
    }
};

@Override
public void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

@Override
public void onStop() {
    super.onStop();
    mGoogleApiClient.disconnect();
}