当前位置: 首页 > 知识库问答 >
问题:

如何在google map android中获取当前位置

蓟清野
2023-03-14
    if (googleMap == null) {
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();

        // check if map is created successfully or not
        if (googleMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }
    }
    googleMap.setMyLocationEnabled(true);
    Location myLocation = googleMap.getMyLocation();  //Nullpointer exception.........
    LatLng myLatLng = new LatLng(myLocation.getLatitude(),
            myLocation.getLongitude());

    CameraPosition myPosition = new CameraPosition.Builder()
            .target(myLatLng).zoom(17).bearing(90).tilt(30).build();
    googleMap.animateCamera(
        CameraUpdateFactory.newCameraPosition(myPosition));

共有1个答案

赖鸿羲
2023-03-14

从Google Sample(CurrentPlaceDetailsOnMap)中为KotlinbyFusedLocationProviderClient,以便SetonMyLocationChangeListener不推荐使用

首先,将实现'com.google.android.libraries.places:places:2.4.0'添加到依赖项

接下来,在片段中添加以下变量

private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
private var lastKnownLocation: Location? = null

接下来,在onviewcreated中添加

    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(requireContext())

onmapready中调用此方法

private fun getDeviceLocation() {
    /*
     * Get the best and most recent location of the device, which may be null in rare
     * cases when a location is not available.
     */
    try {
            val locationResult = fusedLocationProviderClient.lastLocation
            locationResult.addOnCompleteListener(context as Activity) { task ->
                if (task.isSuccessful) {
                    // Set the map's camera position to the current location of the device.
                    lastKnownLocation = task.result
                    if (lastKnownLocation != null) {
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                                LatLng(lastKnownLocation!!.latitude,
                                        lastKnownLocation!!.longitude), DEFAULT_ZOOM.toFloat()))
                    }
                } else {
                    logD("Current location is null. Using defaults.")
                    logD("Exception: ${task.exception}")
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(35.6892, 51.3890), 15.toFloat()))
                    mMap.uiSettings?.isMyLocationButtonEnabled = false
                }
            }
    } catch (e: SecurityException) {
        logD("Exception: ${e.message}")
    }
}
fun requestLocation(context: Context) {
        val mLocationRequest = LocationRequest.create()
        mLocationRequest.interval = 60000
        mLocationRequest.fastestInterval = 5000
        mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        val mLocationCallback: LocationCallback = object : LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult) {
                for (location in locationResult.locations) {
                    if (location != null && lastKnownLocation == null) {
                        lastKnownLocation = location
                    }
                }
            }
        }
        LocationServices.getFusedLocationProviderClient(context)
            .requestLocationUpdates(mLocationRequest, mLocationCallback, null)
    }
mMap.isMyLocationEnabled = true
mMap.uiSettings.isMyLocationButtonEnabled = false
 类似资料:
  • 问题内容: 我在使用android定位系统的NETWORK提供程序获取当前位置坐标时遇到麻烦。 已经阅读了很多教程,并为我的项目实现了4到5个现有的类,所有这些类都给了我最后的坐标,而不是当前的坐标。 我很确定这个问题是我遗漏的根本问题,但是我无法理解到底是什么。 我现在正在使用的代码: 这是我的主要活动 这是我用于跟踪的课程: 这是我的AndroidManifest.xml 实际上,GPS定位工

  • 我试图实现当前位置地图应用程序,我正在加载地图碎片,但它需要纬度和经度值来定位地址...如何实现当前位置地图功能...提前感谢.. 这是我的地图片段。

  • 问题内容: 在我的应用程序中,我在打开应用程序时获得了当前位置的纬度和经度,但是在关闭应用程序时却没有得到。 我正在使用Service类在应用程序中获取当前位置的纬度和经度。 请告诉我即使关闭应用程序也如何获取当前位置的纬度和经度 问题答案: 几个月前,我创建了GPSTracker库来帮助我获取GPS位置。如果您需要查看GPSTracker> getLocation AndroidManifest

  • 问题内容: 我想要这样的当前时间戳: 但是,当我这样做时: 它返回这样的值: 如何以所需格式访问当前时间戳记?我从这里检查日期: 问题答案: 您似乎正在寻找C#中的内容,即自0001-01-01开始的时间以100纳秒为间隔测量。 您提供的链接Swift中的代码:将NSDate转换为c#刻度可以轻松地转换为Swift: 示例(快速3): 或作为字符串: 而在此期间,从滴答声到的反向转换 将是 示例(

  • 问题内容: 我用来发出几个http请求(显然)。现在,我需要发出请求并从最终URL中提取一些查询字符串(存在重定向)。 因此,问题是如何找到URL(如果重定向了客户端,则为最终URL)?Response中没有这样的字段。 请注意,我不需要停止重定向…仅在请求后查找URL是什么 问题答案: 您将回调添加到 然后,您可以在发生新请求时对其进行检查。只要确保设置某种限制来防止重定向循环(如文档中所述,默