2011-11-22 178 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