【谷歌地图--PlacesSDK集成】

上网查了一些资料发现有关谷歌地图sdk集成的文章还是不少的,但是都缺乏系统性。这里做些系统整理,主要分以下篇幅讲解,希望对初始谷歌地图的你有所帮助:

  1. 【谷歌地图–集成准备】
  2. 【谷歌地图–MapsSDK集成】
  3. 【谷歌地图–DirectionsSDK集成】
  4. 【谷歌地图–PlacesSDK集成】

开始正文啦:

由于众所周知的的原因,集成谷歌地图sdk前首先你的pc端和移动端都是要翻墙的,不然后续的一些功能你都无法操作。

谷歌地图–PlacesSDK集成

开始正文之前,我们这里先做个说明哈:集成 Places 功能时,也是需要你的google地图开发者账号启用计费功能。

依赖添加

implementation 'com.google.android.libraries.places:places:2.4.0'

初始化:

public class InitApplication : Application() {
    
    

    override fun onCreate() {
    
    
        super.onCreate()
        ViseHttp.init(this);
   
        if (!Places.isInitialized()) {
    
    
            Places.initialize(applicationContext, Config.API_KAY)
        }

    }

}

当前位置获取附近地点

效果图:
在这里插入图片描述
关键代码:

         // 使用字段定义要返回的数据类型.
        val placeFields = listOf(Place.Field.NAME, Place.Field.ADDRESS, Place.Field.LAT_LNG)

            // Use the builder to create a FindCurrentPlaceRequest.
            val request = FindCurrentPlaceRequest.newInstance(placeFields)

            // 获取可能的位置-即与设备当前位置最匹配的商家和其他兴趣点。
            val placeResult = placesClient.findCurrentPlace(request)
            placeResult.addOnCompleteListener {
    
     task ->
                if (task.isSuccessful && task.result != null) {
    
    
                    val likelyPlaces = task.result

                  
                } else {
    
    
                    Log.e(TAG, "Exception: %s", task.exception)
                }
            }


地点搜索

官方搜索组件

效果图:
在这里插入图片描述
关键代码:

 val query = "潍坊";
    val countries = listOf("CN", "JP", "US");//国家/地区(例如CH,US,RO)
    val locationBias: LocationBias? = null //设置位置偏差
    lateinit var locationRestriction: LocationRestriction  //设置位置限制
    private fun placeSearch() {
    
    
        //val bounds = StringUtil.convertToLatLngBounds("", "")!!
        //locationRestriction = RectangularBounds.newInstance(bounds)

        //获取所有信息
         placeFields = listOf(*Place.Field.values())

        //AutocompleteActivityMode.OVERLAY
        val autocompleteIntent =
            Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, placeFields)
                .setInitialQuery(query)
                .setHint("请输入您要搜索的内容")
                .setCountries(countries)
                //.setLocationBias(locationBias)
                //.setLocationRestriction(locationRestriction)
                //.setTypeFilter(TypeFilter.ADDRESS) //设置类型过滤器
                .build(this)
        startActivityForResult(autocompleteIntent, AUTOCOMPLETE_REQUEST_CODE)

    }

ps:很显然我们这里启动了一个活动,然后我们在onActivityResult中获取结果值:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    
    
        if (requestCode == AUTOCOMPLETE_REQUEST_CODE && data != null) {
    
    
            when (resultCode) {
    
    
                AutocompleteActivity.RESULT_OK -> {
    
    
                    val place = Autocomplete.getPlaceFromIntent(data!!)
                    val result = StringUtil.stringifyAutocompleteWidget(place, true)
                    Log.i(TAG, "onActivityResult: result=${
      
      result}")
                    //Toast.makeText(this, "${result}", Toast.LENGTH_LONG).show()

                    mGoogleMap!!.addMarker(
                        MarkerOptions()
                            .position(place.latLng!!)
                            .title(place.name)
                            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE))
                            .snippet(place.address)
                    )
                    val viewport = place.viewport
                    mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(viewport, 50))

                    // Log.i(TAG, "onActivityResult: data=${data!!.extras.toString()}")
                }
                AutocompleteActivity.RESULT_ERROR -> {
    
    
                    val status = Autocomplete.getStatusFromIntent(data)
                    Log.i(TAG, "onActivityResult: status.statusMessage=${
      
      status.statusMessage}")
                }
                AutocompleteActivity.RESULT_CANCELED -> {
    
    
                    // The user canceled the operation.
                }
            }
        }


        super.onActivityResult(requestCode, resultCode, data)
    }

自定义搜索布局

关键代码:

ps:正在补充中…

搜索附近地点

效果图:
在这里插入图片描述

和获取路线信息一样,搜索附近点也是一个http请求:

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=36.70686554888466,119.17656641453506&radius=1500&key=your_api_kay

关键代码:

private fun getNearbyPlace(mLatLng: LatLng) {
    
    

        ViseHttp.GET("place/nearbysearch/json")
            .tag(TAG)

            .addParam("location", "${
      
      mLatLng.latitude},${
      
      mLatLng.longitude}")
            .addParam("radius", "1000") //半径1000 米
            //.addParam("type", "restaurant")  //搜索结果期望的类型,例如:超市,咖啡馆,学校等等 https://developers.google.cn/places/web-service/supported_types
            // .addParam("keyword", "cruise")//搜索结果期望包含的关键字

            .addParam("language", "zh-CN")
            .addParam("key", Config.API_KAY)

            .request(object : ACallback<NearbyModel?>() {
    
    
                override fun onSuccess(mBean: NearbyModel?) {
    
    
                    //请求成功,AuthorModel为解析服务器返回数据的对象,可以是String,按需定义即可
                    // Log.i(TAG, " mBeanStr=${mBean}")

                    if (mBean!!.status == "OK") {
    
    
                        val resultList = mBean.results
                        val name = resultList[0].name
                        Log.i(TAG, "onSuccess: name=> $name")
                        mNearbyPlaceAdapter.setNewData(resultList)
                    } else {
    
    
                        Log.i(TAG, " errCode=${
      
      mBean!!.status}")
                    }

                }

                override fun onFail(errCode: Int, errMsg: String) {
    
    
                    //请求失败,errCode为错误码,errMsg为错误描述
                    Log.i(TAG, " errCode=${
      
      errCode} errMsg=$errMsg")
                }
            })


    }

获取地点和照片相关信息

关键代码:

  //根据placeId,可以获取 地点 和 照片 等相关信息
    private fun getPlaceInfo(placeId: String) {
    
    
        val argsd = arrayOf("1", "2", "3")
        val argsd1 = arrayOf(1, 2, 3)


        //获取所有信息
        //placeFields = listOf(*Place.Field.values())


        val request = FetchPlaceRequest.newInstance(placeId, placeFields)
        val placeTask = placesClient.fetchPlace(request)
        placeTask.addOnSuccessListener {
    
     response: FetchPlaceResponse ->
            Log.i(TAG, "getPlaceInfo: addOnSuccessListener response=$response")
            val address = response.place.address
            val name = response.place.name
            val latLng = response.place.latLng
            Log.i(TAG, "getPlaceInfo: addOnSuccessListener address=$address")
            //Toast.makeText(this, "${response}", Toast.LENGTH_LONG).show()

            selectMarker = mGoogleMap!!.addMarker(
                MarkerOptions()
                    .position(latLng!!)
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
            )
            selectMarker!!.title = "$name"
            selectMarker!!.snippet = "评分:${
      
      response.place.rating}    总评分:${
      
      response.place.userRatingsTotal}"
            selectMarker!!.showInfoWindow()

            // responseView.text = StringUtil.stringify(response, isDisplayRawResultsChecked)
        }
        placeTask.addOnFailureListener {
    
     exception: Exception ->
            exception.printStackTrace()
            Log.i(TAG, "getPlaceInfo: exception.message=${
      
      exception.message}")
        }
        placeTask.addOnCompleteListener {
    
    
            Log.i(TAG, "getPlaceInfo: addOnCompleteListener")
        }


    }

说明:篇幅有限,文章中也只是贴出了关键代码。完整项目源码请点击这里:

项目源码地址


参考博客:

官方文档:
https://developers.google.com/maps/documentation/directions/overview

官方demo:

拾取坐标系统

【谷歌地图–番外篇 android-maps-utils的使用 】

猜你喜欢

转载自blog.csdn.net/da_caoyuan/article/details/109729586