我正在尝试使用谷歌地图从一个位置向另一个位置指定用户。 我正在使用下面的代码,但我不知道为什么它不起作用。我无法弄清楚问题是否一切正常。
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();
}
}
答案 0 :(得分: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();
答案 1 :(得分: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"/>