0

我正在尝试使用谷歌地图从一个位置到另一个位置给用户一个方向。我正在使用下面的代码,但我不知道为什么它不起作用。我无法弄清楚一切似乎都正确的问题。

final double latitude = 37.894404;
final double longitude = -122.0660386;

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                Criteria criteria = new Criteria();
                criteria.setAccuracy(Criteria.ACCURACY_FINE);
                criteria.setAltitudeRequired(false);
                Location lastKnownLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, true));

                if(lastKnownLocation != null){

                    double lat = lastKnownLocation.getLatitude();
                    double longi = lastKnownLocation.getLongitude();

                    Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr="+lat+","+longi+"&daddr="+latitude+","+longitude));

                    startActivity(intent);

                }else{

                    Toast.makeText(contactus.this,"Coudn't get provider", Toast.LENGTH_SHORT).show();
                }           
            }
4

2 回答 2

0

首先,您需要使用 try/catch 块来包装对 LocationManager 的调用,并获取您在通话结束时出现的任何异常。看看下面。这将进行调用并捕获异常。一旦你知道它为什么返回NULL,就从那里开始。无论出于何种原因,您将始终无法使用模拟器获取位置地理点。此外,谷歌并不总是返回地理点,所以在模拟器中我一直循环直到它回来.. 不是一个好主意

    try{
                 Location lastKnownLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, true));
                }
                catch(IOException e) {
                 Log.e("IOException", e.getMessage());

                 //Toaster on high-----------------//
                 Context context = getApplicationContext();
                 CharSequence text = "IOException:  " + e.getMessage();
                 int dur = Toast.LENGTH_LONG;
                    Toast.makeText(context, text, dur).show();
于 2011-11-23T00:09:46.770 回答
0

我实际上让它工作了,这是我使用的代码,

final double latitude = 45.894404;
final double longitude = -112.0660386;

LocationManager lManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
String towers = lManager.getBestProvider(crit, false);
Location userCurrentLocation = lManager.getLastKnownLocation(towers);

if(userCurrentLocation != null){

     double lat = userCurrentLocation.getLatitude();
     double longi = userCurrentLocation.getLongitude();

     Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr="+lat+","+longi+"&daddr="+latitude+","+longitude));
     startActivity(intent);

}else{

    Toast.makeText(contactus.this, "Couldn't locate a provider to find your location", Toast.LENGTH_LONG).show();
}

不要忘记在清单中添加查找用户位置的权限,将其包含在上面,

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
于 2011-11-23T20:14:32.210 回答