2011-11-22 146 views
0

我正试图给用户使用谷歌地图从一个位置到另一个位置的方向。 我正在使用代码波纹管,但我不知道为什么它不起作用。我无法弄清楚问题一切似乎正确。Android:从谷歌地图获取路线

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(); 
       }   
      } 

回答

1

其实我得到它的工作,这里是我使用的代码,

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(); 
} 

不要忘记添加premission找到你体现用户的位置,包括它上面,

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 
0

首先,您需要用try/catch块将您的呼叫包装到LocationManager中,并抓住您要拨出的任何异常。看看下面。这会调用并捕获异常。一旦你知道它为什么会返回NULL,就从那里开始。无论出于何种原因,使用模拟器获取位置地址都会遇到问题。此外,谷歌并不总是与geopoints返回所以在模拟器我已经循环,直到它回来了..不是一个好主意

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(); 
+0

实际上,我在实际设备上运行此。我也试图给出经度和纬度,而不是当前的位置谷歌的uri,但它没有工作!所以我不认为获取当前位置是问题 – Mona