Android知识Android开发Android开发

Google Map 开发(一):中获取兴趣点 (POI) 信息

2018-04-10  本文已影响0人  天兵公园

首先来说,Google Map 的集成其实非常简单,如果使用了 Google Play Service 了可能就几行代码调用的事,不过在我集成的过程中,发现虽然基于 Service SDK 的集成虽然简单,但是功能少了很多,比如基于 POI 信息获取的方法函数中,就没有传递半径区域的方法,这就需要使用到 Places API Web Service 了。

打开官方文档主页,就已经是 POI 应用的一个实例了。

可以看到需要传递的参数包括当前坐标,搜索区域半径,POI 类型,关键字等,以及需要申请一个 APP KEY,这个很简单,在开发者控制台申请好就行。

设计到 WebAPI 的调用,在 Android 上有很多可选的网络请求方案,上 Github 搜索 HTTP,然后按照 Start 倒序一排,这就是我说的面向 Github 编程。

我们选择 Retrofit 这个就行了,OkHttp 可以不用看了,不是说它不好,只是封装的还不够友好,Retrofit 是把 OkHttp 和 RxJava 糅到一起,使 OkHttp 更为丝滑。在这之前我一直是用 android-async-http,这个 Http 库也是非常强大。

对于任何 Http 框架,由于我们最终返回的是 Json,所以需要实体类,当然面对这一堆 Json 我们没必要自己去写实体类,网上已经有很多 Json 转 Javabean 的工具了。

在项目中集成 Retrofit 非常简单:

 implementation 'com.squareup.retrofit2:retrofit:2.4.0'

然后把生成的 Bean 导入项目,并编写 API 调用接口:

public interface GoogleMapApi {

    @GET("/maps/api/place/nearbysearch/json")
    Call<GooglePoiBean> listRepos(@Query("location") String location,
                                  @Query("radius") int radius,
                                  @Query("types") String types,
                                  @Query("name") String name,
                                  @Query("key") String key);

}

然后创建一个服务主调用类,因为如果接口多了,还可以方便统一管理。

public class GoogleAPIService {

    private static final String GOOGLE_SERVICE_API_KEY  = "AIzaSyBP6nc-FJl7xZtZJP3dTXxeCNr7lWaM3yM";

    private Retrofit retrofit;

    public GoogleAPIService() {

        retrofit = new Retrofit.Builder()
                .baseUrl("https://maps.googleapis.com/")
                .build();

    }

    public void getPoi(double lat, double lng, int radius, String type, Callback<GooglePoiBean> callback) {

        GoogleMapApi googleMapApi = retrofit.create(GoogleMapApi.class);
        Call<GooglePoiBean> googlePoiBeanCall = googleMapApi.listRepos(lat + "," + lng, radius, type, "", GOOGLE_SERVICE_API_KEY);
        googlePoiBeanCall.enqueue(callback);

    }
}

调用非常简单,调用如下:

 GoogleAPIService googleAPIService = new GoogleAPIService();
 googleAPIService.getPoi(30.223, 114.232, 20000, "酒店", new Callback<GooglePoiBean>() {
     @Override
     public void onResponse(Call<GooglePoiBean> call, Response<GooglePoiBean> response) {
     }
     @Override
     public void onFailure(Call<GooglePoiBean> call, Throwable t) {
     }
 });

至此,就已经实现了 Google Map WebService API 的 POI 功能集成了,就算没有 Play Service ,这个功能还是能正常使用的,前提是能访问 Google Map 服务了,不过,国内好像都不能访问的,我也不太清楚什么原因,如果你知道,可以告诉我 。→_→

上一篇下一篇

猜你喜欢

热点阅读