【Google Maps--PlacesSDK Integration】

I checked some information on the Internet and found that there are still many articles about Google Maps SDK integration, but they are not systematic. Here are some systematic arrangements, which are mainly divided into the following sections, and I hope it will be helpful to you who are the initial Google Maps:

  1. 【Google Maps – Integration Preparation】
  2. [Google Maps – MapsSDK Integration]
  3. [Google Maps – DirectionsSDK Integration]
  4. [Google Maps – PlacesSDK Integration]

Let's start the text:

Due to well-known reasons, before integrating the Google Maps SDK, your PC and mobile terminals must first bypass the wall, otherwise you will not be able to operate some subsequent functions.

Google Maps – PlacesSDK Integration

Before starting the text, let’s make an explanation here: When integrating the Places function, you also need to enable the billing function in your Google Maps developer account.

Dependency added

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

initialization:

public class InitApplication : Application() {
    
    

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

    }

}

Current location Get nearby places

Effect picture:
insert image description here
key code:

         // 使用字段定义要返回的数据类型.
        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)
                }
            }


place search

Official Search Component

Effect picture:
insert image description here
key code:

 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: Obviously we start an activity here, and then we get the result value in 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)
    }

Custom Search Layout

key code:

ps: being supplemented...

search for nearby places

Renderings:
insert image description here

Like getting route information, searching for nearby points is also an http request:

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

key code:

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")
                }
            })


    }

Get information about places and photos

key code:

  //根据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")
        }


    }

Explanation: The space is limited, and only the key codes are posted in the article. Please click here for the complete project source code:

Project source address


Reference blog:

Official documentation:
https://developers.google.com/maps/documentation/directions/overview

Official demo:

Pick Coordinate System

[Google Maps – Extra Story android-maps-utils use]

Guess you like

Origin blog.csdn.net/da_caoyuan/article/details/109729586