【问题标题】:Getting the current location for Google Maps [duplicate]获取谷歌地图的当前位置[重复]
【发布时间】:2026-01-22 04:20:05
【问题描述】:

可能重复:
What is the simplest and most robust way to get the user’s current location in Android?

我有以下代码可以在手机上打开 Google 地图,并将目的地的经度 + 纬度和起始位置传递给它。我想知道是否有一种方法可以让我们不必手动在代码中输入起始位置,而是以某种方式让代码自动找出用户的位置?

add.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        Intent intent = new Intent (android.content.Intent.ACTION_VIEW,
            Uri.parse("http://maps.google.com/maps?saddr=" + 51.5171 +
                      "," + 0.1062 + "&daddr=" + 52.6342 + "," + 1.1385));

        intent.setComponent(
            new ComponentName ("com.google.android.apps.maps",
                               "com.google.android.maps.MapsActivity"));

        startActivity(intent);
    }
});

【问题讨论】:

    标签: java android google-maps latitude-longitude


    【解决方案1】:

    你可以使用这个方法:

    public LatLng getLocation(Context ctx) 
    {
        LocationManager lm = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
        List<String> providers = lm.getProviders(true);
    
        /*
         * Loop over the array backwards, and if you get an accurate location,
         * then break out the loop
         */
        Location l = null;
    
        for (int i = providers.size() - 1; i >= 0; i--) 
        {
            l = lm.getLastKnownLocation(providers.get(i));
            if (l != null)
                break;
        }
        return new LatLng(l.getLatitude(),l.getLongitude());
    }
    

    【讨论】:

    • 我在项目中使用过,但不知道在哪里找到的
    • 这可能有助于解决我的 SO 问题 - *.com/questions/14202062/…,但什么决定了代码的准确度?
    • 如果有 GPS 信息,它会使用它,如果没有,它会从网络获取信息。
    【解决方案2】:

    参考这个问题:What is the simplest and most robust way to get the user's current location on Android?

    基本上,一旦您获得了您的位置,您就可以使用 getLatitude()、getLongitude() 并将它们放入您的 url。

    我会推荐比 getLastKnownLocation 更强大的方法,因为它依赖于最后一个已知位置,该位置可能在数小时甚至数天内都不会更新。例如,如果您正在度假,这可能是在地球的错误一侧。

    也可以查看http://developer.android.com/guide/topics/location/strategies.html了解更多详情。

    【讨论】:

      【解决方案3】:

      您的问题的分步指南:

      http://www.androidcompetencycenter.com/?s=GPS

      希望对你有帮助

      【讨论】:

        最近更新 更多