Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android:使用Google places API查找附近的地点_Android_Google Maps_Google Places Api - Fatal编程技术网

Android:使用Google places API查找附近的地点

Android:使用Google places API查找附近的地点,android,google-maps,google-places-api,Android,Google Maps,Google Places Api,我正在尝试使用GooglePlacesAPI获取附近地方的列表。我已经从Google Devloper控制台启用了Required API,并拥有一个有效的API密钥。我能得到我的正确位置。在我得到我的当前位置后,我试图得到附近的位置列表,但它返回为空 我也尝试过给出nullPlaceFilter,但它给出了相同的结果 private class MyGoogleMapOnMyLocationListener implements OnMyLocationChangeLi

我正在尝试使用GooglePlacesAPI获取附近地方的列表。我已经从Google Devloper控制台启用了Required API,并拥有一个有效的API密钥。我能得到我的正确位置。在我得到我的当前位置后,我试图得到附近的位置列表,但它返回为空

我也尝试过给出
null
PlaceFilter
,但它给出了相同的结果

private class MyGoogleMapOnMyLocationListener implements
            OnMyLocationChangeListener,
            ConnectionCallbacks,
            OnConnectionFailedListener {
        private GoogleApiClient mGoogleApiClient;

        @Override
        public void onMyLocationChange(Location location) {
            if (!hasLastLocation) {
                hasLastLocation = true;
                mLastLocation = location;
                Log.d(LOG_TAG, "Location: " + location.toString());

                if (googleMap != null ) {
                    googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                            new LatLng(location.getLatitude(), location.getLongitude()), 16.0f));

                    if (mGoogleApiClient == null) {
                        mGoogleApiClient = new GoogleApiClient
                                .Builder(getActivity())
                                .addApi(Places.GEO_DATA_API)
                                .addApi(Places.PLACE_DETECTION_API)
                                .addConnectionCallbacks(this)
                                .addOnConnectionFailedListener(this)
                                .build();
                        mGoogleApiClient.connect();
                    }
                }
            }
        }

        @Override
        public void onConnected(Bundle bundle) {
            Log.d(LOG_TAG, "Google Api Client connected.");

            if (mGoogleApiClient != null) {
                Log.d(LOG_TAG, "Getting nearby places...");

                PendingResult<PlaceLikelihoodBuffer> result =
                        Places.PlaceDetectionApi.getCurrentPlace(mGoogleApiClient, null);

                result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
                    @Override
                    public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
                        Log.d(LOG_TAG, "Got results: " + likelyPlaces.getCount() + " place found.");

                        for (PlaceLikelihood placeLikelihood : likelyPlaces) {
                            Log.i(LOG_TAG, String.format("Place '%s' has likelihood: %g",
                                    placeLikelihood.getPlace().getName(),
                                    placeLikelihood.getLikelihood()));
                        }

                        likelyPlaces.release();
                    }
                });
            }
        }

        @Override
        public void onConnectionSuspended(int i) {

        }

        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {

        }
    }
私有类MyGoogleMapOnMyLocationListener实现
OnMyLocationChangeListener,
连接回调,
OnConnectionFailedListener{
私人GoogleapClient MGoogleapClient;
@凌驾
公共void onMyLocationChange(位置){
如果(!hasLastLocation){
hasLastLocation=true;
mLastLocation=位置;
Log.d(Log_标记,“Location:+Location.toString());
if(谷歌地图!=null){
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
新的LatLng(location.getLatitude(),location.getLongitude()),16.0f);
if(mGoogleApiClient==null){
mgoogleapclient=新的Googleapclient
.Builder(getActivity())
.addApi(Places.GEO_数据_API)
.addApi(Places.PLACE\u DETECTION\u API)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.build();
mGoogleApiClient.connect();
}
}
}
}
@凌驾
未连接的公共空间(捆绑包){
d(Log_标签,“GoogleAPI客户端已连接”);
if(mGoogleApiClient!=null){
Log.d(Log_标签,“到达附近的地方…”);
Pendingreult结果=
Places.PlaceDetectionApi.getCurrentPlace(mgoogleapClient,null);
result.setResultCallback(新的ResultCallback(){
@凌驾
public void onResult(PlaceLikelihoodBuffer likelyPlaces){
Log.d(Log_标记,“Got results:+likelyPlaces.getCount()+“place found”);
for(place可能性place可能性:likelyPlaces){
Log.i(Log_标记,String.format(“位置“%s”的可能性为:%g”),
place.getPlace().getName(),
placelikelibility.getlikelibility());
}
likelyPlaces.release();
}
});
}
}
@凌驾
公共空间连接暂停(int i){
}
@凌驾
公共无效onConnectionFailed(ConnectionResult ConnectionResult){
}
}
这是我的

这是我的地图

我遵循了来自中国的指示

我试着接受这个问题的答案:


更新
我已经从Google开发者控制台启用了其他与地图相关的API,并且它工作正常。

您可以参考给定的代码和完整的API

import org.apache.http.client.HttpResponseException;
导入android.util.Log;
导入com.google.api.client.googleapis.GoogleHeaders;
导入com.google.api.client.http.GenericUrl;
导入com.google.api.client.http.HttpRequest;
导入com.google.api.client.http.HttpRequestFactory;
导入com.google.api.client.http.HttpRequestInitializer;
导入com.google.api.client.http.HttpTransport;
导入com.google.api.client.http.javanet.NetHttpTransport;
导入com.google.api.client.http.json.JsonHttpParser;
导入com.google.api.client.json.jackson.JacksonFactory;
@抑制警告(“弃用”)
公共类谷歌场所{
/**HTTP传输的全局实例*/
私有静态最终HttpTransport HTTP_TRANSPORT=new NetHttpTransport();
//谷歌API密钥
私有静态最终字符串API_KEY=“”;
//Google放置serach url的
私有静态最终字符串PLACES\u SEARCH\u URL=”https://maps.googleapis.com/maps/api/place/search/json?";
私有静态最终字符串PLACES\u TEXT\u SEARCH\u URL=”https://maps.googleapis.com/maps/api/place/search/json?";
私有静态最终字符串PLACES\u DETAILS\u URL=”https://maps.googleapis.com/maps/api/place/details/json?";
私人双纬度;
私人双经度;
私人双半径;
/**
*搜寻地点
*@param纬度-地点纬度
*@params经度-地点经度
*@param radius-可搜索区域的半径
*@param types-要搜索的位置类型
*@返回名额表
* */
公共场所列表搜索(双纬度、双经度、双半径、字符串类型)
抛出异常{
这个._纬度=纬度;
这是经度;
这个。_半径=半径;
试一试{
HttpRequestFactory HttpRequestFactory=createRequestFactory(HTTP_传输);
HttpRequest请求=httpRequestFactory
.buildGetRequest(新的GenericUrl(PLACES\u SEARCH\u URL));
request.getUrl().put(“key”,API_key);
request.getUrl().put(“位置”、“纬度+”、“+”经度);
request.getUrl().put(“半径”、_半径);//以米为单位
request.getUrl().put(“传感器”、“假”);
if(类型!=null)
request.getUrl().put(“类型”,类型);
PlacesList list=request.execute().parseAs(PlacesList.class);
//检查cat日志以了解位置响应状态
Log.d(“位置状态”,“列表状态”);
退货清单;
}捕获(HttpResponseException e){
Log.e(“错误:,e.getMessage());
返回null;
}
}
/**
import org.apache.http.client.HttpResponseException;

import android.util.Log;

import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.json.JsonHttpParser;
import com.google.api.client.json.jackson.JacksonFactory;

@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 = "<Your KEY>";

    // Google Places serach url's
    private static final String PLACES_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/search/json?";
    private static final String PLACES_TEXT_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/search/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
            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);
            }
        });
    }

}