可能重复:
What is the simplest and most robust way to get the user’s current location in Android?
我有以下代码在手机上打开谷歌地图,并传递目的地的经度+纬度并开始其位置。我想知道是否有一种方法,以便不必手动输入代码中的起始位置,如果我们可以以某种方式让代码自动找出用户在哪里?
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);
}
});
答案 0 :(得分:2)
您可以使用此方法:
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());
}
答案 1 :(得分:0)
请参阅此问题:What is the simplest and most robust way to get the user's current location on Android?
基本上,一旦获得了您的位置,您就可以使用getLatitude(),getLongitude()并将其放入您的网址。
我建议使用比getLastKnownLocation更强大的东西,因为它依赖于最后的已知位置,这些位置可能在几小时甚至几天内都没有更新。例如,如果你正在度假,这可能是在这个星球的错误方面。
还可以查看http://developer.android.com/guide/topics/location/strategies.html了解更多详情。
答案 2 :(得分:-1)