【问题标题】:Google Maps API using Retrofit GET call使用 Retrofit GET 调用的 Google Maps API
【发布时间】:2018-02-18 20:26:04
【问题描述】:

我想将纬度和经度值传递给 Google Maps Autocomplete API 调用的 location 属性,但我不知道如何在 Retrofit 中形成 GET 调用。 URL 最终应如下所示:

https://maps.googleapis.com/maps/api/place/autocomplete/json?&types=address&input=user_input&location=37.76999,-122.44696&radius=50000&key=API_KEY

我目前在我的 Retrofit 界面中有什么:

public interface GooglePlacesAutoCompleteAPI
{
    String BASE_URL = "https://maps.googleapis.com/maps/api/place/autocomplete/";
    String API_KEY = "mykey";  //not the actual key obviously

    //This one works fine
    @GET("json?&types=(cities)&key=" + API_KEY)
    Call<PlacesResults> getCityResults(@Query("input") String userInput);

    //This is the call that does not work
    @GET("json?&types=address&key=" + API_KEY)
    Call<PlacesResults> getStreetAddrResults(@Query("input") String userInput, 
                                             @Query("location") double latitude, double longitude,
                                             @Query("radius") String radius);
}

我的错误是:java.lang.IllegalArgumentException: No Retrofit annotation found. (parameter #3) for method GooglePlacesAutoCompleteAPI.getStreetAddrResults

那么如何正确设置getStreetAddrResults() 的GET 方法?

另外,我的数据类型对于纬度/经度和半径是否正确?感谢您的帮助!

【问题讨论】:

    标签: android google-maps retrofit google-places-api


    【解决方案1】:

    你的界面应该是这样的:

    public interface API {
        String BASE_URL = "https://maps.googleapis.com";
    
        @GET("/maps/api/place/autocomplete/json")
        Call<PlacesResults> getCityResults(@Query("types") String types, @Query("input") String input, @Query("location") String location, @Query("radius") Integer radius, @Query("key") String key);
    }
    

    并像这样使用它:

    Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(API.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
    
    API service = retrofit.create(API.class);
    
    
    service.getCityResults(types, input, location, radius, key).enqueue(new Callback<PlacesResults>() {
        @Override
        public void onResponse(Call<PlacesResults> call, Response<PlacesResults> response) {
            PlacesResults places = response.body();
        }
    
        @Override
        public void onFailure(Call<PlacesResults> call, Throwable t) {
            t.printStackTrace();
        }
    });
    

    当然你应该给参数一个值。

    【讨论】:

    • 正如您所回答的那样,我刚刚想通了。关键是用纬度和经度值制作一个字符串。试图将它们作为两个单独的参数传递会导致问题。感谢您的深入回答,我得到了它的工作:]
    猜你喜欢
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    • 2016-11-05
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多