android實現簡單的路線導航功能
藉助google map,實現了一個簡單的android導航功能。
開始的介面還是這個:
增加了交通方式的選擇:
比如選擇乘車:
載入資料需要等待一下。
會給出備選路線:
選擇比如第一條備選路線。
選擇在地圖上顯示。注意,如果使用android 1.5,則沒有“在地圖上顯示”菜單條目,其他都差不多。
其實整個上面的應用,自己寫的代碼很少,看到的路線選擇和顯示,都是google地圖提供的功能了。
完成的Activity代碼:
package proto.geo;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class HomeActivity extends Activity {
Button button;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) this.findViewById(R.id.Button01);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final CharSequence[] items = { "乘車", "步行", "駕車" };
AlertDialog.Builder builder = new AlertDialog.Builder(
HomeActivity.this);
builder.setTitle("選擇交通方式");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
StringBuilder params = new StringBuilder().append("&dirflg=");
switch (item) {
case 0:
params.append("r");
break;
case 1:
params.append("w");
break;
case 2:
params.append("d");
break;
default:
break;
}
getMap(params.toString());
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
protected void getMap(String params) {
Intent i = new Intent(
Intent.ACTION_VIEW,
Uri
.parse("http://ditu.google.cn/maps?f=d&source=s_d&saddr=31.249351,121.45905&daddr=31.186371,121.489885&hl=zh&t=m&"
+ params));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
& Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
i.setClassName("com.google.android.apps.maps",
"com.google.android.maps.MapsActivity");
startActivity(i);
}
}
這裡要注意的是,dirflg這個參數,如果預設不填寫的話,呼叫瀏覽器顯示地圖將是駕車方式,但是如果調用google地圖,則使用上次選擇的方式,有可能是步行或者乘車了。在google的mapki官方文檔中也沒有給出駕車的參數,如果使用t或者h,都沒有作用,因為這是限制參數,不是型別參數。
於是我想,如果是我,可能會定一個d參數,drive嘛,結果生效了,哈哈。
引用文章:
http://marshal.easymorse.com/archives/2590