关于使用google map实现周边搜索的功能

由于公司项目是针对美国市场,所以接入的是google定位

谷歌地图sdk不像高德地图或者百度地图那么好接入,一方面是纯英文,还有一方面国外文档习惯我们并不习惯,大多写得很简略

我的项目要实现附近宠物店的搜索和附近宠物医院的搜索,在接入谷歌地图用到了以下几个包:

"com.google.android.gms:play-services-maps:15.0.1"
"com.google.android.gms:play-services-location:15.0.1"
"com.google.android.gms:play-services-places:15.0.1"

此外还需要在清单文件中配置对应的

<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="@string/google_maps_key"/>

注:在string.xml中的谷歌地图的key的名字必须是google_maps_key

下面实现的搜索的功能:本质上调用的http接口来实现,比较坑的一点是同一个key一天调用的次数最多150000次,如果用户量较大时,要专门交费调整限制次数

1.首先初始化

 

private GoogleApiClient mGoogleApiClient;

private void getLocationList() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    //创建GoogleAPIClient实例
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addApi(Places.GEO_DATA_API)
                .addApi(Places.PLACE_DETECTION_API)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

}

2.调用接口进行请求地址数据:

 private void getGoogleLocation() {
        String baseUrl = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=";
//            String realUrl=baseUrl+mLat+","+mLng+"&radius="
//                    +5000+"&type=pet_store"+"&language=zh-CN"+"&key="+"你自己在谷歌的对应的key";
        String realUrl = null;
//            realUrl = baseUrl + mLat + "," + mLng + "&radius="
//                    + 20000 +"&rankby=distance"+
//                    "&types=" + searchType + "&key=" + "你自己在谷歌的对应的key";
        realUrl = baseUrl + mLat + "," + mLng +"&rankby=distance"+
                "&types=" + searchType + "&key=" + "你自己在谷歌对应的key";
        Call<ResponseBody> ca = HBClient.getService(MineService.class).listGoogleLocations(realUrl);
        ca.enqueue(new RequestCallBack<ResponseBody>() {
            @Override
            public void onFailed(Call<ResponseBody> call, Response<ResponseBody> response) {
                super.onFailed(call, response);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                super.onFailure(call, t);
            }

            @Override
            public void onSuccess(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String json = response.body().string();
                    LogUtil.e("周边地址的json为" + json);
                    if (json != null && !json.equals("")) {
                        googleLocationBean = GsonUtils.jsonToBean(json, GoogleLocationBean.class);
                        if (googleLocationBean == null) {
                            LogUtil.e("解析周边地址json为空");
                            showEmpty();
                            nextPageToken = null;
                        } else {
                            if (googleLocationBean.getStatus().equals("OK")) {
                                List<GoogleLocationBean.GoogleLocationData> results = googleLocationBean.getResults();
                                nextPageToken = googleLocationBean.getNext_page_token();
                                showSuccess();
                                mAdapter.setNewData(results);
                                LogUtil.e("长度为" + results.size());
//                                    for (int i = 0; i < results.size(); i++) {
//                                    getGoogleDetail(results.get(i),results,i,hasMore);
//                                    }
//                                    getGooglePhotos(results.get(1).getReference());
                            } else {
                                nextPageToken = null;
                                showEmpty();
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

3.当请求返回的数据中有

nextPageToken字段不为空时,就有多页数据,请求下一页数据时需要将该字段携带去请求

4.请求下一页数据时:

private void getGoogleLocationMore() {
        String baseUrl = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?pagetoken=";
        String realUrl = null;
        realUrl = baseUrl + nextPageToken + "&key=" + "你对应的谷歌的key";
            nextPageToken = null;
        Call<ResponseBody> ca = HBClient.getService(MineService.class).listGoogleLocations(realUrl);
        ca.enqueue(new RequestCallBack<ResponseBody>() {
            @Override
            public void onFailed(Call<ResponseBody> call, Response<ResponseBody> response) {
                super.onFailed(call, response);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                super.onFailure(call, t);
            }

            @Override
            public void onSuccess(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String json = response.body().string();
                    LogUtil.e("周边地址的json为" + json);
                    if (json != null && !json.equals("")) {
                        googleLocationBean = GsonUtils.jsonToBean(json, GoogleLocationBean.class);
                        if (googleLocationBean == null) {
                            LogUtil.e("解析周边地址json为空");
                            mAdapter.loadMoreEnd();
                            nextPageToken = null;
                        } else {
                            if (googleLocationBean.getStatus().equals("OK")) {
                                List<GoogleLocationBean.GoogleLocationData> results = googleLocationBean.getResults();
                                mAdapter.addData(results);
                                mAdapter.loadMoreEnd();
                                nextPageToken = googleLocationBean.getNext_page_token();
                                LogUtil.e("长度为" + results.size());
//                                    for (int i = 0; i < results.size(); i++) {
//                                    getGoogleDetail(results.get(i),results,i,hasMore);
//                                    }
//                                    getGooglePhotos(results.get(1).getReference());
                            } else {
                                mAdapter.loadMoreEnd();
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

5.请求某个地点对应的照片时:

private void getGooglePhotos(String photoreference) {
    String baseUrlPhoto = "https://maps.googleapis.com/maps/api/place/photo?";
    String realUrlPhoto = baseUrlPhoto + "maxwidth=480&photoreference=" + photoreference
            + "&key=" + "你的谷歌对应的key";
    HBClient.getService(MineService.class).listGooglePhotos(realUrlPhoto).enqueue(new RequestCallBack<ResponseBody>() {
        @Override
        public void onFailed(Call<ResponseBody> call, Response<ResponseBody> response) {
            super.onFailed(call, response);
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            super.onFailure(call, t);
        }

        @Override
        public void onSuccess(Call<ResponseBody> call, Response<ResponseBody> response) {
            try {
                String json = response.body().string();
                LogUtil.e("图片json为" + json);
                if (json != null && !json.equals("")) {
                    GoogleLocationBean bean = GsonUtils.jsonToBean(json, GoogleLocationBean.class);
                    if (bean == null) {
                        LogUtil.e("解析周边地址图片json为空");
                    } else {
                        if (bean.getStatus().equals("OK")) {
                            List<GoogleLocationBean.GoogleLocationData> results = bean.getResults();
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
}

6.上述请求对应地点照片采用的Places的web的api,也可以采用安卓的api,如下:

private void getPhoto(String placeId, GoogleApiClient mGoogleApiClient, ImageView imgLogo) {
    Places.GeoDataApi.getPlacePhotos(mGoogleApiClient, placeId)
            .setResultCallback(photos -> {
                if (!photos.getStatus().isSuccess()) {
                    return;
                }

                PlacePhotoMetadataBuffer photoMetadataBuffer = photos.getPhotoMetadata();
                if (photoMetadataBuffer.getCount() > 0) {
                    // Display the first bitmap in an ImageView in the size of the view
                    photoMetadataBuffer.get(0)
                            .getScaledPhoto(mGoogleApiClient, imgLogo.getWidth(),
                                    imgLogo.getHeight())
                            .setResultCallback(placePhotoResult -> {
                                LogUtil.e("请求图片回调-"+placePhotoResult.getStatus().isSuccess());
                                if (!placePhotoResult.getStatus().isSuccess()) {
                                    return;
                                }
                                imgLogo.setImageBitmap(placePhotoResult.getBitmap());

                            });
                }else {
                    LogUtil.e("查询到图片数量为0");
                }
                photoMetadataBuffer.release();
            });
}

 

7.关于谷歌地图的显示的补充:在Activity中实现OnMapReadyCallback接口

在onCreate方法中:注意

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // TODO: add setContentView(...) invocation
    ButterKnife.bind(this);
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}
    @Override
    public void onMapReady(GoogleMap googleMap) {
        LogUtil.e("googleMap");
        mMap = googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//        mMap.setOnMyLocationButtonClickListener(this);
//        mMap.setOnMarkerDragListener(this);
        UiSettings uiSettings = mMap.getUiSettings();
        uiSettings.setZoomControlsEnabled(true);
        uiSettings.setZoomGesturesEnabled(true);
        uiSettings.setCompassEnabled(true);
        uiSettings.setMyLocationButtonEnabled(true);//不显示定位按钮
//        enableMyLocation();
        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(item.getGeometry().getLocation().getLat(), item.getGeometry().getLocation().getLng());
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                MyApp.runOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        mMap.animateCamera(CameraUpdateFactory.
                                newLatLngZoom(new LatLng(item.getGeometry().getLocation().getLat(),
                                        item.getGeometry().getLocation().getLng()), 16));
                        Marker melbourne = mMap.addMarker(new MarkerOptions()
                                .position(sydney)
                                .title(item.getVicinity()));
                        melbourne.showInfoWindow();
                        CircleOptions circleOptions = new CircleOptions()
                                .center(sydney)
                                .radius(280); // In meters

                        Circle circle = mMap.addCircle(circleOptions);
                        circle.setFillColor(Color.argb(45, 0, 191, 255));
                        circle.setStrokeColor(Color.argb(65, 0, 191, 255));
                        circle.setStrokeWidth(6);
                    }
                });

            }
        }, 300);

    }
}

对应的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<com.zhy.autolayout.AutoLinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:fitsSystemWindows="true"
    android:clipToPadding="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
<include layout="@layout/include_title"/>
        <fragment
            android:id="@+id/map"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            class="com.google.android.gms.maps.SupportMapFragment"/>
</com.zhy.autolayout.AutoLinearLayout>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
好的,我了解你的问题了。那么,针对你的问题,我可以提供以下的解决方案: 1. 首先,在uniapp中使用map标签,进行地图定位搜索关键字查询功能开发。 2. 然后,使用Google Maps API,调用周边搜索功能,在地图上显示搜索结果。 下面,我将分步骤地详细介绍这个解决方案: 步骤1:使用map标签进行地图定位搜索关键字查询功能开发 在uniapp中,可以使用map标签进行地图开发。具体步骤如下: 1. 在uniapp的页面中引入map标签: ``` <map :id="map" :latitude="latitude" :longitude="longitude" :markers="markers" @markertap="markertap"></map> ``` 2. 在data中定义地图相关的变量: ``` data: { map: 'myMap', latitude: '', longitude: '', markers: [] } ``` 3. 在mounted生命周期中获取当前位置: ``` mounted() { uni.getLocation({ type: 'gcj02', success: res => { this.latitude = res.latitude; this.longitude = res.longitude; } }); } ``` 4. 在methods中定义搜索功能: ``` methods: { search(e) { let keyword = e.detail.value; if (!keyword) { return; } uni.request({ url: 'https://apis.map.qq.com/ws/place/v1/search', data: { keyword: keyword, location: `${this.latitude},${this.longitude}`, key: '你的key', radius: 1000 }, success: res => { let data = res.data; if (data.status === 0) { let markers = data.data.map(item => { return { id: item.id, latitude: item.location.lat, longitude: item.location.lng, title: item.title, iconPath: '/static/images/marker.png', width: 32, height: 32 }; }); this.markers = markers; } } }); }, markertap(e) { console.log(e.markerId); } } ``` 步骤2:使用Google Maps API调用周边搜索功能 1. 在Google Cloud Console中创建一个项目,并启用Maps JavaScript API。 2. 在uniapp中引入Google Maps API: ``` <script src="https://maps.googleapis.com/maps/api/js?key=你的API密钥"></script> ``` 3. 在methods中使用Google Maps API调用周边搜索功能: ``` methods: { search(e) { let keyword = e.detail.value; if (!keyword) { return; } let service = new google.maps.places.PlacesService(document.createElement('div')); let request = { location: new google.maps.LatLng(this.latitude, this.longitude), radius: 1000, query: keyword }; service.textSearch(request, (results, status) => { if (status === google.maps.places.PlacesServiceStatus.OK) { let markers = results.map(item => { return { id: item.id, latitude: item.geometry.location.lat(), longitude: item.geometry.location.lng(), title: item.name, iconPath: '/static/images/marker.png', width: 32, height: 32 }; }); this.markers = markers; } }); }, markertap(e) { console.log(e.markerId); } } ``` 以上就是使用Google Maps API实现周边搜索功能的具体步骤。希望能帮到你。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值