18034727885
2026-08-18 dab2f54542d151c92dcba04bd9833280e9728e2d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
package com.driver.igotrip.base.gaode
 
//import com.google.android.libraries.places.api.Places
//import com.google.android.libraries.places.api.model.*
//import com.google.android.libraries.places.api.net.FetchPlaceRequest
//import com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest
//import com.google.android.libraries.places.api.net.FindCurrentPlaceRequest
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Color
import android.location.LocationManager
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.core.content.ContextCompat
import cn.sinata.rxnetty.LogHelper
import cn.sinata.xldutils.utils.SPUtils
import com.driver.igotrip.R
import com.driver.igotrip.base.Const
import com.driver.igotrip.base.MyBaseActivity.TAG
import com.driver.igotrip.bean.GoogleBackBean
import com.driver.igotrip.bean.GoogleNearBean2
import com.driver.igotrip.bean.GoogleRouteBean
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.GoogleMapOptions
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.BitmapDescriptor
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.CameraPosition
import com.google.android.gms.maps.model.Circle
import com.google.android.gms.maps.model.CircleOptions
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.LatLngBounds
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.gms.maps.model.Polygon
import com.google.android.gms.maps.model.PolygonOptions
import com.google.android.gms.maps.model.Polyline
import com.google.android.gms.maps.model.PolylineOptions
import com.google.gson.Gson
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
 
 
object AMapKit {
 
//    @SuppressLint("MissingPermission")
//    fun initLocation(context: Context, function: (Place) -> Unit) {
//        val placesClient = Places.createClient(context)
//        val placeFields: List<Place.Field> = listOf(Place.Field.LAT_LNG,Place.Field.NAME,Place.Field.ADDRESS)
//
//// Use the builder to create a FindCurrentPlaceRequest.
//        val request: FindCurrentPlaceRequest = FindCurrentPlaceRequest.newInstance(placeFields)
//
//// Call findCurrentPlace and handle the response (first check that the user has granted permission).
//        if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) ==
//            PackageManager.PERMISSION_GRANTED) {
//
//            val placeResponse = placesClient.findCurrentPlace(request)
//            placeResponse.addOnCompleteListener { task ->
//                if (task.isSuccessful) {
//                    val response = task.result
//                    for (placeLikelihood: PlaceLikelihood in response?.placeLikelihoods ?: emptyList()) {
//                        Log.i(TAG, "Place '${placeLikelihood.place.name}' has likelihood: ${placeLikelihood.likelihood}")
//                    }
//                    if (response?.placeLikelihoods?.isNotEmpty() == true){
//                        function(response.placeLikelihoods[0].place)
//                    }
//                } else {
//                    val exception = task.exception
//                    if (exception is ApiException) {
//                        Log.e(TAG, "Place not found: ${exception.statusCode}"+"          statue" +exception.status)
//                    }
//                }
//            }
//        } else {
//            // A local method to request required permissions;
//            // See https://developer.android.com/training/permissions/requesting
////            Toast.makeText(context, "没有权限", Toast.LENGTH_SHORT).show()
////            getLocationPermission()
//        }
//    }
 
 
    fun initMap(mapView: SupportMapFragment, function: (GoogleMap) -> Unit) {
        val subscribe =
            RxPermissions(mapView.requireActivity()).request(Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe {
                    if (it) {
                        mapView.getMapAsync { p0 ->
                            val mMyLocationStyle = GoogleMapOptions()
                            p0.uiSettings.isMyLocationButtonEnabled = false
                            p0.setMinZoomPreference(6.0f);
                            p0.setMaxZoomPreference(16.0f);
                            //                mMyLocationStyle.interval(5000)
                            //                mMyLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER)
                            //                mMyLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.gps_point))
                            //                p0.setLocationSource() = mMyLocationStyle
                            //                p0.isMyLocationEnabled = false
                            //                p0.animateCamera(CameraUpdateFactory.zoomTo(aMap.maxZoomLevel - 3))
                            // 设置定位的类型为定位模式,有定位、跟随或地图根据面向方向旋转几种
                            //                p0.setMyLocationType(GoogleMap.LOCATION_TYPE_LOCATE)
                            //                val uiSettings: UiSettings = aMap.uiSettings
                            //                uiSettings.isZoomControlsEnabled = false
                            function(p0)
                        }
                    } else {
                        Log.e("map", "没有权限")
                    }
                }
    }
 
    /**
     * 初始化谷歌地图(SupportMapFragment 版本)
     * @param mapFragment 地图碎片实例(非 MapView)
     * @param onMapReady 地图加载完成后的回调(返回可用的 GoogleMap 实例)
     */
    fun initMaptest(
        mapFragment: SupportMapFragment,
        onMapReady: (GoogleMap) -> Unit
    ) {
        // 异步加载地图,处理回调参数空安全
        mapFragment.getMapAsync { googleMap ->
            googleMap ?: return@getMapAsync // 若实例为 null,直接返回,避免空指针
 
            // 1. 基础地图配置(保留你原本的合理配置,优化命名和语义)
            val uiSettings = googleMap.uiSettings
            uiSettings.isMyLocationButtonEnabled = false // 隐藏默认定位按钮
            uiSettings.isZoomControlsEnabled = false // 你原本注释里想关缩放控件,这里明确配置(可选)
 
            // 2. 缩放级别限制(保留你的配置,单位:f,范围 0-21,谷歌地图默认支持)
            googleMap.setMinZoomPreference(6.0f)
            googleMap.setMaxZoomPreference(16.0f)
 
            // 3. 可选:定位相关配置(如果需要显示用户位置,需先申请定位权限)
            // 注意:谷歌地图启用定位需先获取 ACCESS_FINE_LOCATION/ACCESS_COARSE_LOCATION 权限
            if (ContextCompat.checkSelfPermission(
                    mapFragment.requireContext(),
                    Manifest.permission.ACCESS_FINE_LOCATION
                ) == PackageManager.PERMISSION_GRANTED
            ) {
                googleMap.isMyLocationEnabled = true // 启用定位图层(显示用户位置蓝点)
                // 谷歌地图没有 setMyLocationType,如需自定义定位模式,需通过 LocationCallback 实现
            }
 
            // 4. 回调返回可用的 GoogleMap 实例
            onMapReady(googleMap)
        }
    }
 
    fun drawLine(context: Context, aMap: GoogleMap, start: LatLng, end: LatLng): Polyline? {
        val latLngs: MutableList<LatLng> = ArrayList()
        latLngs.add(start)
        latLngs.add(end)
        return aMap.addPolyline(
            PolylineOptions().addAll(latLngs).width(10f).color(
                ContextCompat.getColor(context, R.color.main_yellow_qia)
            )
        )
    }
 
    /***
     * 监听地图的移动
     */
    fun addMapMoveListener(aMap: GoogleMap, marker: Marker, finishPosition: (LatLng) -> Unit) {
        aMap.setOnCameraMoveListener { marker.position = aMap.cameraPosition.target }
 
        aMap.setOnCameraIdleListener {
            finishPosition(aMap.cameraPosition.target)
        }
    }
 
    fun drawLineAndMove(context: Context, aMap: GoogleMap, start: LatLng, end: LatLng, padd: Int) {
        drawLine(context, aMap, start, end)
        moveCamera(aMap, start, end, padd)
    }
 
 
    fun drawLine(context: Context, aMap: GoogleMap, latLngs: List<LatLng?>?): Polyline? {
        val options = PolylineOptions().addAll(latLngs!!).width(20f)
            .color(ContextCompat.getColor(context, cn.sinata.xldutils.R.color.qing))
        return aMap.addPolyline(options)
    }
 
    fun drawLine(
        context: Context,
        aMap: GoogleMap,
        latLngs: List<LatLng?>?,
        color: Int
    ): Polyline? {
        val options = PolylineOptions().addAll(latLngs!!).width(20f)
            .color(ContextCompat.getColor(context, color))
        return aMap.addPolyline(options)
    }
 
    fun moveCamera(aMap: GoogleMap, latlng: LatLng?) {
        val mCameraUpdate = CameraUpdateFactory.newCameraPosition(
            CameraPosition(latlng!!, 16f, 0f, 0f)
        )
        aMap.animateCamera(mCameraUpdate)
    }
 
    fun moveCamera(aMap: GoogleMap, latlng: LatLng?, zoom: Float) {
        val mCameraUpdate = CameraUpdateFactory.newCameraPosition(
            CameraPosition(latlng!!, zoom, 0f, 0f)
        )
        aMap.animateCamera(mCameraUpdate)
    }
 
    /***
     * LatLngBounds 此方法有可能错误了  start 和 end 的经纬度可能要拆分开来组合成 左上和右下的位置
     */
    fun moveCamera(aMap: GoogleMap, start: LatLng?, end: LatLng?) {
        var bounds: LatLngBounds? = null
//        if (start!!.latitude < end!!.latitude)
//            bounds = LatLngBounds(start!!, end!!)
//        else
//            bounds = LatLngBounds(end, start)
        var startX = LatLng(
            if (start!!.latitude < end!!.latitude) start.latitude else end.latitude,
            if (start!!.longitude < end!!.longitude) start.longitude else end.longitude
        )
        var startY = LatLng(
            if (start!!.latitude > end!!.latitude) start.latitude else end.latitude,
            if (start!!.longitude > end!!.longitude) start.longitude else end.longitude
        )
        bounds = LatLngBounds(startX, startY)
 
        val mCameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 200)
        aMap.animateCamera(mCameraUpdate)
    }
 
    /***
     * LatLngBounds 此方法有可能错误了  start 和 end 的经纬度可能要拆分开来组合成 左上和右下的位置
     */
    fun moveCamera(aMap: GoogleMap, start: LatLng?, end: LatLng?, padd: Int) {
//        val bounds = LatLngBounds(start!!, end!!)
        var bounds: LatLngBounds? = null
//        if (start!!.latitude < end!!.latitude)
//            bounds = LatLngBounds(start!!, end!!)
//        else
//            bounds = LatLngBounds(end, start)
        var startX = LatLng(
            if (start!!.latitude < end!!.latitude) start.latitude else end.latitude,
            if (start!!.longitude < end!!.longitude) start.longitude else end.longitude
        )
        var startY = LatLng(
            if (start!!.latitude > end!!.latitude) start.latitude else end.latitude,
            if (start!!.longitude > end!!.longitude) start.longitude else end.longitude
        )
        bounds = LatLngBounds(startX, startY)
        val mCameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, padd)
        aMap.animateCamera(mCameraUpdate)
    }
 
    fun getOption(
        latLng: LatLng,
        view: View
    ): MarkerOptions {
        return MarkerOptions().anchor(0.5f, 1f)
            .position(latLng)
            .icon(BitmapDescriptorFactory.fromBitmap(convertViewToBitmap(view)!!))
            .draggable(true).flat(true)
    }
 
    /***
     * 修改marker的view
     */
    fun getIcon(view: View): BitmapDescriptor {
        return BitmapDescriptorFactory.fromBitmap(convertViewToBitmap(view)!!)
    }
 
    /**
     * 吧iew转化为bitmap
     *
     * @param view
     * @return
     */
    fun convertViewToBitmap(view: View): Bitmap? {
        view.isDrawingCacheEnabled = true
        view.measure(
            View.MeasureSpec.makeMeasureSpec(
                0,
                View.MeasureSpec.UNSPECIFIED
            ),
            View.MeasureSpec.makeMeasureSpec(
                0,
                View.MeasureSpec.UNSPECIFIED
            )
        )
        view.layout(0, 0, view.measuredWidth, view.measuredHeight)
        view.buildDrawingCache()
        val mCacheBitmap = view.drawingCache
        return Bitmap.createBitmap(mCacheBitmap)
    }
 
    /**
     * 添加marker点
     */
    fun addMarker(
        aMap: GoogleMap,
        mLat: Double,
        mLng: Double,
        view: View,
        peopleId: String
    ): Marker? {
        val options: MarkerOptions = getOption(LatLng(mLat, mLng), view)
        val marker: Marker = aMap.addMarker(options)!!
        if (!TextUtils.isEmpty(peopleId)) {
            marker.tag = peopleId
        }
        return marker
    }
 
    fun getTance(context: Context, tance: Float): String {
        if (tance == 0f) {
            return context.getString(R.string.zero_tance)
        }
        return if (tance > 1000) {
            String.format("%.1f " + context.getString(R.string.公里), (tance / 1000f))
        } else {
            String.format("%.1f " + context.getString(R.string.米), tance)
        }
    }
 
//    fun drawFenceByCity(context: Context, city: String, va1: GeoFenceListener) {
//        val mGeoFenceClient = GeoFenceClient(context)
//        mGeoFenceClient.setActivateAction(GeoFenceClient.GEOFENCE_IN)
//        mGeoFenceClient.addGeoFence(city, "");
//        mGeoFenceClient.setGeoFenceListener(va1);
//
//    }
 
    fun drawFace(context: Context, aMap: GoogleMap, latLngs: List<LatLng?>?): Polygon? {
        var po = PolygonOptions().addAll(latLngs!!)
            .fillColor(ContextCompat.getColor(context, R.color.l_transparent_10)).strokeColor(
                Color.RED
            ).strokeWidth(1f)
        return aMap.addPolygon(po)
    }
 
    fun drawCricle(context: Context, aMap: GoogleMap, latLng: LatLng, bg: Double): Circle? {
        return aMap.addCircle(
            CircleOptions().center(latLng).radius(bg)
                .fillColor(ContextCompat.getColor(context, R.color.l_transparent_10))
                .strokeColor(Color.RED).strokeWidth(1f)
        );
    }
 
    fun getTimeType(num: Int): String {
        if (num in 0..60) {
            return num.toString() + "s"
        }
        if (num in 60..60 * 60) {
            return (num / 60).toString() + ":" + (num % 60).toString() + "s"
        }
        if (num in 60..60 * 60 * 24) {
            return (num / 3600).toString() + ":" + ((num % 3600) / 60).toString() + ":" + (((num % 3600) % 60) % 60).toString() + "s"
        }
        return ""
    }
 
    fun initRouteLine(
        context: Context,
        start: LatLng, end: LatLng,
        onClick: (latLngs: MutableList<LatLng>, lineTance: Float, lineTime: Long) -> Unit
    ) {
        initRouteLine(context, start, end, null, onClick)
    }
 
    fun initRouteLine(
        context: Context,
        start: LatLng, end: LatLng, centerPoint: List<LatLng>?,
        onClick: (latLngs: MutableList<LatLng>, lineTance: Float, lineTime: Long) -> Unit
    ) {
        //https://maps.googleapis.com/maps/api/directions/json?origin=39.99709957757345,116.31184045225382&destination=39.949158391497214,116.4154639095068&sensor=false&mode=driving
        var language = SPUtils.getString(Const.language)
        var centerStr = getPointStr(centerPoint ?: arrayListOf())
        var url = "https://maps.googleapis.com/maps/api/directions/json" +
                "?origin=" + start.latitude.toString() + "," + start.longitude.toString() +
                "&destination=" + end.latitude.toString() + "," + end.longitude.toString() +
                "&waypoints=" + centerStr +
                "&region=" + language +
                "&key=" + Const.google_key
 
        getClient(url) {
            var googleBean = Gson().fromJson<GoogleRouteBean>(it, GoogleRouteBean::class.java)
            var time = 0 //秒
            var tance = 0 //米
            var allPoint = arrayListOf<LatLng>()
            val decode =
                PolyUtil.decode(googleBean.routes?.firstOrNull()?.overview_polyline?.points ?: "")
 
            for (routes in googleBean.routes ?: arrayListOf()) {
                if (routes.legs.isNullOrEmpty()) {
                    Log.i(TAG, "initRouteLine: 无路线")
                    return@getClient
                }
                time = routes.legs[0].duration?.value ?: 0
                tance = routes.legs[0].distance?.value ?: 0
 
            }
            allPoint.addAll(decode)
            onClick(allPoint, tance.toFloat(), time.toLong() / 60)
        }
 
    }
 
    private fun getPointStr(centerPoint: List<LatLng>): String {
        var s = ""
        for (item in centerPoint) {
            if (s.isEmpty()) {
                s += item.latitude.toString() + "," + item.longitude.toString()
            } else {
                s += "|" + item.latitude.toString() + "," + item.longitude.toString()
            }
        }
        return s
    }
 
    /***
     * 是否开启gps
     */
    public fun isLocServiceEnable(context: Context): Boolean {
        val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        var gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
        var network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
        if (gps || network) {
            return true
        }
        return false
    }
 
    fun getClient(url: String, retryCount: Int = 3, function: (String) -> Unit) {
        val client = OkHttpClient().newBuilder().build()
        val request: Request = Request.Builder()
            .url(url)
            .method("GET", null)
            .build()
        LogHelper.logRecord("请求谷歌服务器 $url")
        val subscribe = Observable.just(request)
            .map { request -> client.newCall(request).execute().body?.string() ?: "" }
            .retry(retryCount.toLong())   // 最多额外重试 3 次(加上首次共 4 次尝试)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                try {
                    if (it.isEmpty()) {
                        LogHelper.logRecord("请求谷歌服务器成功 获取结果异常为空")
                        return@subscribe
                    }
                    function(it)
                    LogHelper.logRecord("请求谷歌服务器成功")
                } catch (e: Exception) {
                    e.printStackTrace()
                    LogHelper.logRecord("请求谷歌服务器成功,获取结果异常报错 message:${e.message},stackTrace:${e.stackTraceToString()}")
                }
            }, { throwable ->
                throwable.printStackTrace()
                LogHelper.logRecord("请求谷歌服务器异常报错 message:${throwable.message},stackTrace:${throwable.stackTraceToString()}")
            })
    }
 
    /***
     * 周边检索
     * @param lat
     * @param lng
     */
    fun searchPoint(
        context: Context,
        lat: Double,
        lng: Double,
        function: (List<GoogleNearBean2.ResultsBean>) -> Unit
    ) {
        var language = SPUtils.getString(Const.language)
        var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json" +
                "?location=" + lat.toString() + "," + lng.toString() +
                "&radius=1500" +
//                "&type=restaurant" +
                "&language=" + language +
                "&key=" + Const.google_key
        getClient(url) {
            var near = Gson().fromJson<GoogleNearBean2>(it, GoogleNearBean2::class.java)
            if (near.results!!.isNotEmpty() && near.results!!.size > 1) {
                function(near.results ?: arrayListOf())
            }
        }
    }
 
//    /***
//     * 输入内容自动提示
//     * @param str
//     * @param var1
//     */
//    fun searchSite(context: Context, content: String?, cityName: String, function: (List<AutocompletePrediction>) -> Unit) {
//        val placesClient = Places.createClient(context)
//        var language = SPUtils.getString(Const.language)
//        if (language.isEmpty()){
//            language = Const.Language.ENGLISH
//        }
//        val token = AutocompleteSessionToken.newInstance()
////        val bounds = RectangularBounds.newInstance(
////            LatLng(-33.880490, 151.184363), LatLng(-33.858754, 151.229596))
//        val request = FindAutocompletePredictionsRequest.builder() // Call either setLocationBias() OR setLocationRestriction().
////                .setLocationBias(bounds)
//                .setOrigin(LatLng(MyApplication.aMapLocation!!.latLng!!.latitude, MyApplication.aMapLocation!!.latLng!!.longitude))
//                .setCountries(language)
//                .setTypeFilter(TypeFilter.ADDRESS)
//                .setSessionToken(token)
//                .setQuery(content)
//                .build()
//
//        placesClient.findAutocompletePredictions(request).addOnSuccessListener { response ->
//            function(response.autocompletePredictions)
//
//        }.addOnFailureListener { exception ->
//            if (exception is ApiException) {
//                Log.e(TAG, "Place not found: " + exception.statusCode)
//            }
//        }
//
//    }
 
//    fun getPlanceIdDetail(context: Context,id:String,function: (Place) -> Unit){
//        val placesClient = Places.createClient(context)
//        val placeFields = Arrays.asList(Place.Field.ID, Place.Field.NAME)
//        val request = FetchPlaceRequest.newInstance(id, placeFields)
//        placesClient.fetchPlace(request).addOnSuccessListener { response ->
//            val place: Place = response.place
//            function(place)
//        }.addOnFailureListener { exception ->
//            if (exception is ApiException) {
//                Log.e(TAG, "Place not found: " + exception.message)
//                val statusCode = exception.statusCode
//
//            }
//        }
//    }
 
 
    /***
     * 逆地址编码
     */
    fun getAddress(context: Context, lat: Double, lon: Double, function: (String) -> Unit) {
        var language = SPUtils.getString(Const.language)
        var url = "https://maps.googleapis.com/maps/api/geocode/json" +
                "?latlng=" + lat.toString() + "," + lon.toString() +
                "&language=" + language +
                "&result_type=postal_code" +
                "&key=" + Const.google_key
        getClient(url) {
            var bean = Gson().fromJson<GoogleBackBean>(it, GoogleBackBean::class.java)
            if (!bean.results.isNullOrEmpty() && bean.results!![0].types.isNotEmpty())
                function(bean.results!![0].address_components!![0].short_name!!)
        }
 
    }
 
    fun getAddressName(context: Context, lat: Double, lon: Double, function: (String) -> Unit) {
        var language = SPUtils.getString(Const.language)
        var url = "https://maps.googleapis.com/maps/api/geocode/json" +
                "?latlng=" + lat.toString() + "," + lon.toString() +
                "&language=" + language +
                "&result_type=street_address" +
                "&key=" + Const.google_key
        getClient(url) {
            var bean = Gson().fromJson<GoogleBackBean>(it, GoogleBackBean::class.java)
            if (!bean.results.isNullOrEmpty() && bean.results!![0].types.isNotEmpty())
                function(bean.results!![0].address_components!![3].short_name!!)
        }
    }
 
    fun startNavi(
        context: Context,
        startLat: Double,
        startLon: Double,
        endLat: Double,
        endLon: Double
    ) {
        val intent = Intent(context, NaviGoogleActivity::class.java)
        intent.putExtra("lat", endLat)
        intent.putExtra("lon", endLon)
        context.startActivity(intent)
    }
}