1. 程式人生 > >Android 百度地圖新增標記+定位+導航(從定位點開始導航到自己新增的點)

Android 百度地圖新增標記+定位+導航(從定位點開始導航到自己新增的點)

百度地圖的官方文件說的不是很清楚,我自己花幾天做了一個是新增標籤+定位+導航啊。僅供參考。

一.普通地圖,定位,新增標記,初始化導航SDK

package com.example.salesman;


import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.json.JSONException;
import org.json.JSONObject;


import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.baidu.lbsapi.auth.LBSAuthManagerListener;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.InfoWindow.OnInfoWindowClickListener;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.navisdk.BaiduNaviManager;
import com.baidu.navisdk.BNaviEngineManager.NaviEngineInitListener;
import com.example.salesman.application.MyApplication;
import com.example.salesman.data.NegotiationState;
import com.example.salesman.dialog.AddMerchantDialog;
import com.example.salesman.dialog.AddNoteDialog;
import com.example.salesman.map.MyOrientationListener;
import com.example.salesman.map.MyOrientationListener.OnOrientationListener;
import com.example.salesman.model.MapMerchantInfo;
import com.example.salesman.noVolley.network.http.HttpHelper;
import com.example.salesman.noVolley.network.http.RequestEntity;
import com.example.salesman.noVolley.network.http.ResponseJsonEntity;
import com.example.tools.DataRequestVolley;
import com.example.tools.HttpMethod;
import com.example.tools.JsonUtil;
import com.example.tools.RequestQueueSingleton;


public class MapActivity extends ActionBarActivity {
/**
* 地圖控制元件
*/
private MapView mMapView = null;
/**
* 地圖例項
*/
private BaiduMap mBaiduMap;
/**
* 定位的客戶端
*/
private LocationClient mLocationClient;
/**
* 定位的監聽器
*/
public MyLocationListener mMyLocationListener;
/**
* 當前定位的模式
*/
private LocationMode mCurrentMode = LocationMode.NORMAL;
/***
* 是否是第一次定位
*/
private volatile boolean isFristLocation = true;


/**
* 最新一次的經緯度
*/
private double mCurrentLantitude;
private double mCurrentLongitude;
/**
* 當前的經度
*/
private float mCurrentAccracy;
/**
* 方向感測器的監聽器
*/
private MyOrientationListener myOrientationListener;
/**
* 方向感測器X方向的值
*/
private int mXDirection;


/**
* 地圖定位的模式
*/
private String[] mStyles = new String[] { "地圖模式【正常】", "地圖模式【跟隨】",
"地圖模式【羅盤】" };
private int mCurrentStyle = 0;
// 初始化全域性 bitmap 資訊,不用時及時 recycle
private BitmapDescriptor markRed, markBluee, markGreen, markYellow,
markRedUn, markBlueeUn, markGreenUn, markYellowUn;
boolean mIsEngineInitSuccess = false;
/**
* 詳細資訊的 佈局
*/


Bundle send = new Bundle();
Button btLocation;
AddMerchantDialog merchantDialog;
ProgressDialog pd;
ProgressDialog changePd;
ProgressDialog deletePd;
MyApplication application;
List<MapMerchantInfo> merchanList;
List<BitmapDescriptor> bitmapList;
MapMerchantInfo currentMerchant;
FrameLayout frameLayout;
MapMerchantInfo mapMerchantInfo;
private String currentAddress = "";
View normalView;
String addCity = "";
String addProvince = "";


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SDKInitializer.initialize(getApplicationContext());
BaiduNaviManager.getInstance().initEngine(this, getSdcardDir(),
mNaviEngineInitListener, new LBSAuthManagerListener() {
@Override
public void onAuthResult(int status, String msg) {
String str = null;
if (0 == status) {
str = "key校驗成功!";
} else {
str = "key校驗失敗, " + msg;
}
Toast.makeText(MapActivity.this, str, Toast.LENGTH_LONG)
.show();
}
});
setContentView(R.layout.activity_map);


ActionBar actionBar = getSupportActionBar();
actionBar.hide();
application = (MyApplication) getApplication();
frameLayout = (FrameLayout) findViewById(R.id.fl_mapView);
initNormalView();
frameLayout.addView(normalView);


merchanList = new ArrayList<MapMerchantInfo>();
bitmapList = new ArrayList<BitmapDescriptor>();


pd = new ProgressDialog(MapActivity.this);
deletePd = new ProgressDialog(MapActivity.this);
changePd = new ProgressDialog(MapActivity.this);


currentMerchant = new MapMerchantInfo();


// 第一次定位
isFristLocation = true;
// 獲取地圖控制元件引用


// 獲得地圖的例項
mBaiduMap = mMapView.getMap();


/**
* 已稽核地圖圖示
*/


markRed = BitmapDescriptorFactory.fromResource(R.drawable.mark_red);// 紅色、未失敗
markBluee = BitmapDescriptorFactory.fromResource(R.drawable.mark_bluee);// 藍色、洽談中
markGreen = BitmapDescriptorFactory.fromResource(R.drawable.mark_green);// 綠色、洽談成功
markYellow = BitmapDescriptorFactory
.fromResource(R.drawable.mark_yellow);// 黃色、洽談失敗


bitmapList.add(markRed);
bitmapList.add(markBluee);
bitmapList.add(markGreen);
bitmapList.add(markYellow);


/**
* 未稽核圖示
*/


markRedUn = BitmapDescriptorFactory
.fromResource(R.drawable.mark_red_un);// 紅色、未失敗
markBlueeUn = BitmapDescriptorFactory
.fromResource(R.drawable.mark_bluee_un);// 藍色、洽談中
markGreenUn = BitmapDescriptorFactory
.fromResource(R.drawable.mark_green_un);// 綠色、洽談成功
markYellowUn = BitmapDescriptorFactory
.fromResource(R.drawable.mark_yellow_un);// 黃色、洽談失敗


bitmapList.add(markRedUn);
bitmapList.add(markBlueeUn);
bitmapList.add(markGreenUn);
bitmapList.add(markYellowUn);


MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);// 地圖比例
mBaiduMap.setMapStatus(msu);
// 初始化定位
initMyLocation();
// 初始化感測器
initOritationListener();
initMarkerClickEvent();
initMapClickEvent();
btLocation.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
initMyLocation();
center2myLoc();
}
});
showAll();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}


private String getSdcardDir() {
if (Environment.getExternalStorageState().equalsIgnoreCase(
Environment.MEDIA_MOUNTED)) {
return Environment.getExternalStorageDirectory().toString();
}
return null;
}


private NaviEngineInitListener mNaviEngineInitListener = new NaviEngineInitListener() {


@Override
public void engineInitSuccess() {
// TODO Auto-generated method stub
mIsEngineInitSuccess = true;
}


@Override
public void engineInitStart() {
// TODO Auto-generated method stub


}


@Override
public void engineInitFail() {
// TODO Auto-generated method stub


}
};


public void initNormalView() {
normalView = getLayoutInflater().inflate(R.layout.normal_map_layout,
null);
btLocation = (Button) normalView.findViewById(R.id.bt_normal_location);
mMapView = (MapView) normalView.findViewById(R.id.normal_mapView);
}


@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {


new AlertDialog.Builder(this)
// .setIcon(R.drawable.services)
.setTitle("提醒")
.setMessage("是否退出")
.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
}
})
.setPositiveButton("退出",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
application.getmActivity().finish();
finish();
}
}).show();


return true;
} else {
return super.onKeyDown(keyCode, event);
}
}


private void initMapClickEvent() {
mBaiduMap.setOnMapClickListener(new OnMapClickListener() {


@Override
public boolean onMapPoiClick(MapPoi arg0) {
return false;
}


@Override
public void onMapClick(LatLng arg0) {
mBaiduMap.hideInfoWindow();
}
});
}


/**
* 初始化方向感測器
*/
private void initOritationListener() {
myOrientationListener = new MyOrientationListener(
getApplicationContext());
myOrientationListener
.setOnOrientationListener(new OnOrientationListener() {
@Override
public void onOrientationChanged(float x) {
mXDirection = (int) x;
// 構造定位資料
MyLocationData locData = new MyLocationData.Builder()
.accuracy(mCurrentAccracy)
// 此處設定開發者獲取到的方向資訊,順時針0-360
.direction(mXDirection)
.latitude(mCurrentLantitude)
.longitude(mCurrentLongitude).build();
// 設定定位資料
mBaiduMap.setMyLocationData(locData);
// 設定自定義圖示
BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
.fromResource(R.drawable.navi_map_gps_locked);


mBaiduMap
.setMyLocationConfigeration(new MyLocationConfiguration(
mCurrentMode, true, mCurrentMarker));


}
});
}


/**
* 初始化定位相關程式碼
*/
private void initMyLocation() {
// 定位初始化
mLocationClient = new LocationClient(this);
mMyLocationListener = new MyLocationListener();
mLocationClient.registerLocationListener(mMyLocationListener);
// 設定定位的相關配置
LocationClientOption option = new LocationClientOption();
option.setIsNeedAddress(true);// 返回的定位結果包含地址資訊
option.setNeedDeviceDirect(true);// 返回的定位結果包含手機機頭的方向
option.setOpenGps(true);// 開啟gps
option.setCoorType("bd09ll"); // 設定座標型別
option.setScanSpan(1000);
mLocationClient.setLocOption(option);
mLocationClient.start();
mLocationClient.requestLocation();
}


/**
* 初始化圖層
*/
public void addInfosOverlay() {
initMyLocation();
center2myLoc();
AddMerchantDialog updateDialog = new AddMerchantDialog(
MapActivity.this, mCurrentLongitude, mCurrentLantitude, true,
addCity, addProvince);
updateDialog.show();
updateDialog.setOnDismissListener(new OnDismissListener() {


@Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
showAll();
}
});
}


/**
* 實現實位回撥監聽
*/
public class MyLocationListener implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {


// map view 銷燬後不在處理新接收的位置
if (location == null || mMapView == null)
return;
// 構造定位資料
MyLocationData locData = new MyLocationData.Builder()
.accuracy(location.getRadius())
// 此處設定開發者獲取到的方向資訊,順時針0-360
.direction(mXDirection).latitude(location.getLatitude())
.longitude(location.getLongitude()).build();
mCurrentAccracy = location.getRadius();
// 設定定位資料
mBaiduMap.setMyLocationData(locData);
mCurrentLantitude = location.getLatitude();
mCurrentLongitude = location.getLongitude();
addProvince = location.getProvince();
addCity = location.getCity();
// 設定自定義圖示
BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
.fromResource(R.drawable.navi_map_gps_locked);
mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(
mCurrentMode, true, mCurrentMarker));
// 第一次定位時,將地圖位置移動到當前位置
if (isFristLocation) {
isFristLocation = false;
LatLng ll = new LatLng(location.getLatitude(),
location.getLongitude());
MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
mBaiduMap.animateMapStatus(u);
}


}


}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.map, menu);
return super.onCreateOptionsMenu(menu);
}


/**
* 預設點選menu選單,選單項不現實圖示,反射強制其顯示
*/
@Override
public boolean onMenuOpened(int featureId, Menu menu) {


if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
try {
Method m = menu.getClass().getDeclaredMethod(
"setOptionalIconsVisible", Boolean.TYPE);
m.setAccessible(true);
m.invoke(menu, true);
} catch (Exception e) {
}
}


}
return super.onMenuOpened(featureId, menu);
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {


switch (item.getItemId()) {
case R.id.id_menu_map_showAll:
showAll();
break;
case R.id.id_menu_map_addMaker:
addInfosOverlay();
break;
case R.id.id_menu_map_traffic:
// 開啟交通圖


if (mBaiduMap.isTrafficEnabled()) {
item.setTitle("開啟實時交通");
mBaiduMap.setTrafficEnabled(false);
} else {
item.setTitle("關閉實時交通");
mBaiduMap.setTrafficEnabled(true);
}
break;
case R.id.id_menu_map_style:
mCurrentStyle = (++mCurrentStyle) % mStyles.length;
item.setTitle(mStyles[mCurrentStyle]);
// 設定自定義圖示
switch (mCurrentStyle) {
case 0:
mCurrentMode = LocationMode.NORMAL;
break;
case 1:
mCurrentMode = LocationMode.FOLLOWING;
break;
case 2:
mCurrentMode = LocationMode.COMPASS;
break;
}
BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
.fromResource(R.drawable.navi_map_gps_locked);
mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(
mCurrentMode, true, mCurrentMarker));
break;
}


return super.onOptionsItemSelected(item);
}


/**
* 地圖移動到我的位置,此處可以重新發定位請求,然後定位; 直接拿最近一次經緯度,如果長時間沒有定位成功,可能會顯示效果不好
*/
private void center2myLoc() {
LatLng ll = new LatLng(mCurrentLantitude, mCurrentLongitude);
MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
mBaiduMap.animateMapStatus(u);
}


public void showAll() {


String url = "";
int method = HttpMethod.POST;
DataRequestVolley requestVolley = new DataRequestVolley(method, url,
mResponseSuccess, mErrorListener) {
protected java.util.Map<String, String> getParams()
throws AuthFailureError {


Map<String, String> map = new HashMap<String, String>();
map.put("token", "o484pgd0nf3d4mtjc0dmaid265");
return map;


};
};
RequestQueueSingleton.getInstance(MapActivity.this).addToRequestQueue(
requestVolley);
pd = ProgressDialog.show(MapActivity.this, "", "重新整理資料中...");
}


private Response.Listener<String> mResponseSuccess = new Response.Listener<String>() {


@Override
public void onResponse(String response) {
// TODO Auto-generated method stub
mBaiduMap.clear();
pd.dismiss();
Log.i("響應", response);
String jsonStr = JsonUtil.getJsonValueByKey(response, "list");
merchanList = JsonUtil.toObjectList(jsonStr, MapMerchantInfo.class);
for (MapMerchantInfo merchantInfo : merchanList) {
LatLng latLng = null;
OverlayOptions overlayOptions = null;
Marker marker = null;
// 位置
if (!"".equals(merchantInfo.getPOSLAT())
&& !"".equals(merchantInfo.getPOSLNG())) {
latLng = new LatLng(
Double.valueOf(merchantInfo.getPOSLAT()),
Double.valueOf(merchantInfo.getPOSLNG()));
} else {
latLng = new LatLng(Double.valueOf(0.0),
Double.valueOf(0.0));
}


// 圖示判斷
switch (merchantInfo.allyStatus) {
case "0": {
if (merchantInfo.getPermit() == "0") {
overlayOptions = new MarkerOptions().position(latLng)
.icon(bitmapList.get(0)).zIndex(5);
} else {
overlayOptions = new MarkerOptions().position(latLng)
.icon(bitmapList.get(4)).zIndex(5);
}
}


break;
case "1": {
if (merchantInfo.getPermit() == "0") {
overlayOptions = new MarkerOptions().position(latLng)
.icon(bitmapList.get(1)).zIndex(5);
} else {
overlayOptions = new MarkerOptions().position(latLng)
.icon(bitmapList.get(5)).zIndex(5);
}
}


break;
case "2": {
if (merchantInfo.getPermit() == "0") {
overlayOptions = new MarkerOptions().position(latLng)
.icon(bitmapList.get(2)).zIndex(5);
} else {
overlayOptions = new MarkerOptions().position(latLng)
.icon(bitmapList.get(6)).zIndex(5);
}
}


break;
case "3": {
if (merchantInfo.getPermit() == "0") {
overlayOptions = new MarkerOptions().position(latLng)
.icon(bitmapList.get(3)).zIndex(5);
} else {
overlayOptions = new MarkerOptions().position(latLng)
.icon(bitmapList.get(7)).zIndex(5);
}
}


break;
default:
overlayOptions = new MarkerOptions().position(latLng)
.icon(bitmapList.get(4)).zIndex(5);


break;
}


marker = (Marker) (mBaiduMap.addOverlay(overlayOptions));
Bundle bundle = new Bundle();
bundle.putSerializable("merchantInfo", merchantInfo);
marker.setExtraInfo(bundle);
// 將地圖移到到最後一個經緯度位置
MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(latLng);
mBaiduMap.setMapStatus(u);
center2myLoc();
}
}


};


private Response.ErrorListener mErrorListener = new Response.ErrorListener() {


@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
mBaiduMap.clear();
pd.dismiss();


Toast.makeText(MapActivity.this, error.getMessage(),
Toast.LENGTH_SHORT).show();
}


};


private void changeCollectState() {


AlertDialog.Builder builder = new AlertDialog.Builder(MapActivity.this);
builder.setIcon(R.drawable.ic_launcher);
builder.setTitle("選擇洽談狀態");
// 指定下拉列表的顯示資料
final String[] state = { NegotiationState.NOT_NEGOTIATION,
NegotiationState.GOING_NEGOTIATION,
NegotiationState.NEGOTIATION_SUCCESS,
NegotiationState.NEGOTIATION_FALSE };
// 設定一個下拉的列表選擇項
builder.setItems(state, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, final int which) {


changePd = ProgressDialog.show(MapActivity.this, "",
"正在上傳狀態...");
new ChangeState(which).execute();
}
});
builder.show();
}


public class ChangeState extends AsyncTask<Void, Void, Void> {
int upToState;
String msg;


public ChangeState(int upToState) {
this.upToState = upToState;
}


@Override
protected Void doInBackground(Void... params) {


String url = "";


Map<String, Object> map = new HashMap<String, Object>();
map.put("id", Integer.parseInt(currentMerchant.getId()));

RequestEntity entity = new RequestEntity(url, HttpMethod.POST, map);
String json = "";
try {
json = HttpHelper.execute(entity);
ResponseJsonEntity responseJsonEntity = ResponseJsonEntity
.fromJSON(json);
if (responseJsonEntity.getStatus() == 0) {
String data = responseJsonEntity.getData();
Log.i("響應資料", data);
msg = responseJsonEntity.getMessage();
} else {
msg = responseJsonEntity.getMessage();
Log.i("響應資料", msg);
}
} catch (Exception e) {
e.printStackTrace();
}


return null;
}


@Override
protected void onPostExecute(Void result) {
changePd.dismiss();
Toast.makeText(MapActivity.this, msg, Toast.LENGTH_SHORT).show();
showAll();
super.onPostExecute(result);
}


}


private void changeOrDeleteMerchant() {
String permit = currentMerchant.getPermit();
if (permit == "0") {


AlertDialog.Builder builder = new AlertDialog.Builder(
MapActivity.this);
builder.setIcon(R.drawable.ic_launcher);
builder.setTitle("選擇洽談狀態");
// 指定下拉列表的顯示資料
final String[] state = { "修改洽談狀態", "修改商家資訊", "刪除商家資訊", "實時導航",
"取消操作", };
// 設定一個下拉的列表選擇項
builder.setItems(state, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, final int which) {
switch (which) {
case 0:
changeCollectState();
break;
case 1: {
AddMerchantDialog addDialog = new AddMerchantDialog(
MapActivity.this, mCurrentLongitude,
mCurrentLantitude, false, currentMerchant,
addCity, addProvince);
addDialog.show();
addDialog.setOnDismissListener(new OnDismissListener() {


@Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
showAll();
}
});
}
break;
case 2:
deleteMerchantInfo();
break;
case 3:


{
Intent intent = new Intent(MapActivity.this,
MapNavigation.class);


double X = Double.valueOf(currentMerchant.getPOSLAT());
double Y = Double.valueOf(currentMerchant.getPOSLNG());
String name = currentMerchant.getMerchantName();
double endLa = mCurrentLantitude;
double endLong = mCurrentLongitude;
intent.putExtra("X", X);
intent.putExtra("Y", Y);
intent.putExtra("name", name);
intent.putExtra("endLa", endLa);
intent.putExtra("endLong", endLong);
startActivity(intent);
}


case 4:
break;
}


}
});
builder.show();


} else {


AlertDialog.Builder builder = new AlertDialog.Builder(
MapActivity.this);
builder.setIcon(R.drawable.ic_launcher);
builder.setTitle("選擇洽談狀態");
// 指定下拉列表的顯示資料
final String[] state = { "新增備註", "實時導航", "取消操作", };
// 設定一個下拉的列表選擇項
builder.setItems(state, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, final int which) {
switch (which) {
case 0:
new AddNoteDialog(MapActivity.this, currentMerchant)
.show();
break;
case 1: {
Intent intent = new Intent(MapActivity.this,
MapNavigation.class);


double X = Double.valueOf(currentMerchant.getPOSLAT());
double Y = Double.valueOf(currentMerchant.getPOSLNG());
String name = currentMerchant.getMerchantName();
double endLa = mCurrentLantitude;
double endLong = mCurrentLongitude;
intent.putExtra("X", X);
intent.putExtra("Y", Y);
intent.putExtra("name", name);
intent.putExtra("endLa", endLa);
intent.putExtra("endLong", endLong);
startActivity(intent);
}
break;


case 2:
break;
}


}
});
builder.show();


}


}


private void deleteMerchantInfo() {
deletePd = ProgressDialog.show(MapActivity.this, "", "正在刪除資料...");
String url = "";
int method = HttpMethod.POST;
DataRequestVolley requestVolley = new DataRequestVolley(method, url,
deleteResponseSuccess, deleteErrorListener) {
protected java.util.Map<String, String> getParams()
throws AuthFailureError {


Map<String, String> map = new HashMap<String, String>();
map.put("id", currentMerchant.getId());
return map;
};
};
RequestQueueSingleton.getInstance(MapActivity.this).addToRequestQueue(
requestVolley);


}


private Response.Listener<String> deleteResponseSuccess = new Response.Listener<String>() {


@Override
public void onResponse(String response) {
// TODO Auto-generated method stub
deletePd.dismiss();
showAll();
}


};


private Response.ErrorListener deleteErrorListener = new Response.ErrorListener() {


@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub


deletePd.dismiss();
try {
JSONObject jsonObject = new JSONObject(error.getMessage());


boolean isnull = true;
isnull = jsonObject.getBoolean("return");
if (!isnull) {
mBaiduMap.clear();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


};


private void initMarkerClickEvent() {
// 對Marker的點選
mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {
@Override
public boolean onMarkerClick(final Marker marker) {
// 獲得marker中的資料
InfoWindow mInfoWindow;
// 生成一個TextView使用者在地圖中顯示InfoWindow
TextView location = new TextView(getApplicationContext());
location.setBackgroundResource(R.drawable.location_tips);
location.setPadding(30, 20, 30, 50);
mapMerchantInfo = (MapMerchantInfo) marker.getExtraInfo().get(
"merchantInfo");
currentMerchant = mapMerchantInfo;
currentAddress = currentMerchant.getMerchantAddress();
location.setText(mapMerchantInfo.getMerchantName()
+ "\n"
+ "電話:"
+ mapMerchantInfo.getMerchantPhone()
+ "\n"
+ "地址:"
+ mapMerchantInfo.getMerchantAddress()
+ "\n"
+ "洽談狀態:"
+ new NegotiationState()
.getNegotiationStateString(mapMerchantInfo
.getAllyStatus()));
// 將marker所在的經緯度的資訊轉化成螢幕上的座標
final LatLng ll = marker.getPosition();
Point p = mBaiduMap.getProjection().toScreenLocation(ll);
p.y -= 47;
LatLng llInfo = mBaiduMap.getProjection().fromScreenLocation(p);
// 為彈出的InfoWindow新增點選事件
mInfoWindow = new InfoWindow(location, llInfo,
new OnInfoWindowClickListener() {


@Override
public void onInfoWindowClick() {
// 編輯商家資訊
changeOrDeleteMerchant();
}
});
// 顯示InfoWindow
mBaiduMap.showInfoWindow(mInfoWindow);
// 設定詳細資訊佈局為可見
return true;
}
});
}


@Override
protected void onStart() {
// 開啟圖層定位
mBaiduMap.setMyLocationEnabled(true);
if (!mLocationClient.isStarted()) {
mLocationClient.start();
}
// 開啟方向感測器
myOrientationListener.start();
super.onStart();
}


@Override
protected void onStop() {
// 關閉圖層定位
mBaiduMap.setMyLocationEnabled(false);
mLocationClient.stop();


// 關閉方向感測器
myOrientationListener.stop();
super.onStop();
}


@Override
protected void onDestroy() {
super.onDestroy();
// 在activity執行onDestroy時執行mMapView.onDestroy(),實現地圖生命週期管理
mMapView.onDestroy();
for (BitmapDescriptor descriptor : bitmapList) {
descriptor.recycle();
}
mMapView = null;


}


@Override
protected void onResume() {
super.onResume();
// 在activity執行onResume時執行mMapView. onResume (),實現地圖生命週期管理
mMapView.onResume();


}


@Override
protected void onPause() {


super.onPause();
// 在activity執行onPause時執行mMapView. onPause (),實現地圖生命週期管理
mMapView.onPause();


}


/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {


public PlaceholderFragment() {
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_map, container,
false);
return rootView;
}
}


}

普通地圖頁佈局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.salesman.MapActivity"
    tools:ignore="MergeRootFrame" >


    <FrameLayout
        android:id="@+id/fl_mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="true" />


</RelativeLayout>

二。導航頁

package com.example.salesman;


import com.baidu.lbsapi.auth.LBSAuthManagerListener;
import com.baidu.navisdk.BaiduNaviManager;
import com.baidu.navisdk.BNaviEngineManager.NaviEngineInitListener;
import com.baidu.navisdk.BaiduNaviManager.OnStartNavigationListener;
import com.baidu.navisdk.comapi.mapcontrol.BNMapController;
import com.baidu.navisdk.comapi.mapcontrol.MapParams.Const.LayerMode;
import com.baidu.navisdk.comapi.routeplan.BNRoutePlaner;
import com.baidu.navisdk.comapi.routeplan.RoutePlanParams.NE_RoutePlan_Mode;
import com.baidu.navisdk.comapi.tts.BNTTSPlayer;
import com.baidu.navisdk.comapi.tts.BNavigatorTTSPlayer;
import com.baidu.navisdk.comapi.tts.IBNTTSPlayerListener;
import com.baidu.navisdk.model.datastruct.LocData;
import com.baidu.navisdk.model.datastruct.SensorData;
import com.baidu.navisdk.ui.routeguide.BNavigator;
import com.baidu.navisdk.ui.routeguide.IBNavigatorListener;
import com.baidu.navisdk.ui.widget.RoutePlanObserver;
import com.baidu.navisdk.ui.widget.RoutePlanObserver.IJumpToDownloadListener;
import com.baidu.navisdk.util.common.ScreenUtil;
import com.baidu.nplatform.comapi.map.MapGLSurfaceView;


import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import android.os.Build;


public class MapNavigation extends ActionBarActivity {


Bundle bundle = new Bundle();
private MapGLSurfaceView nMapView;
boolean mIsEngineInitSuccess = false;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BaiduNaviManager.getInstance().initEngine(this, getSdcardDir(),
mNaviEngineInitListener, new LBSAuthManagerListener() {
@Override
public void onAuthResult(int status, String msg) {
String str = null;
if (0 == status) {
str = "key校驗成功!";
} else {
str = "key校驗失敗, " + msg;
}
Toast.makeText(MapNavigation.this, str,
Toast.LENGTH_LONG).show();
}
});
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
navigationTest();


}


private String getSdcardDir() {
if (Environment.getExternalStorageState().equalsIgnoreCase(
Environment.MEDIA_MOUNTED)) {
return Environment.getExternalStorageDirectory().toString();
}
return null;
}


private NaviEngineInitListener mNaviEngineInitListener = new NaviEngineInitListener() {


@Override
public void engineInitSuccess() {
// TODO Auto-generated method stub
mIsEngineInitSuccess = true;
}


@Override
public void engineInitStart() {
// TODO Auto-generated method stub


}


@Override
public void engineInitFail() {
// TODO Auto-generated method stub


}
};


public void navigationTest() {


double X = getIntent().getDoubleExtra("X", 0.0);
double Y = getIntent().getDoubleExtra("Y", 0.0);
double endLa = getIntent().getDoubleExtra("endLa", 0.0);
double endLong = getIntent().getDoubleExtra("endLong", 0.0);
String name = getIntent().getStringExtra("name");
// 這裡給出一個起終點示例,實際應用中可以通過POI檢索、外部POI來源等方式獲取起終點座標
BaiduNaviManager.getInstance().launchNavigator(this, endLa, endLong,
"當前位置", X, Y, name, NE_RoutePlan_Mode.ROUTE_PLAN_MOD_MIN_TIME, // 算路方式
true, // 真實導航
BaiduNaviManager.STRATEGY_FORCE_ONLINE_PRIORITY, // 在離線策略
new OnStartNavigationListener() { // 跳轉監聽


@Override
public void onJumpToNavigator(Bundle configParams) {
bundle = configParams;
}


@Override
public void onJumpToDownloader() {
}
});


// 建立NmapView
if (Build.VERSION.SDK_INT < 14) {
BaiduNaviManager.getInstance().destroyNMapView();
}
MapGLSurfaceView nMapView = BaiduNaviManager.getInstance()
.createNMapView(this);


// 建立導航檢視
View navigatorView = BNavigator.getInstance().init(MapNavigation.this,
bundle, nMapView);
setContentView(navigatorView);
// // 填充檢視
// setContentView(navigatorView);
BNavigator.getInstance().setListener(mBNavigatorListener);
BNavigator.getInstance().startNav();


// 初始化TTS. 開發者也可以使用獨立TTS模組,不用使用導航SDK提供的TTS
BNTTSPlayer.initPlayer();
// 設定TTS播放回調
BNavigatorTTSPlayer.setTTSPlayerListener(new IBNTTSPlayerListener() {


@Override
public int playTTSText(String arg0, int arg1) {
// 開發者可以使用其他TTS的API
return BNTTSPlayer.playTTSText(arg0, arg1);
}


@Override
public void phoneHangUp() {
// 手機結束通話
}


@Override
public void phoneCalling() {
// 通話中
}


@Override
public int getTTSState() {
// 開發者可以使用其他TTS的API,
return BNTTSPlayer.getTTSState();
}
});


BNRoutePlaner.getInstance().setObserver(
new RoutePlanObserver(this, new IJumpToDownloadListener() {


@Override
public void onJumpToDownloadOfflineData() {
// TODO Auto-generated method stub


}
}));


}


private IBNavigatorListener mBNavigatorListener = new IBNavigatorListener() {


@Override
public void onYawingRequestSuccess() {
// TODO 偏航請求成功


}


@Override
public void onYawingRequestStart() {
// TODO 開始偏航請求


}


@Override
public void onPageJump(int jumpTiming, Object arg) {
// TODO 頁面跳轉回調
if (IBNavigatorListener.PAGE_JUMP_WHEN_GUIDE_END == jumpTiming) {
finish();
} else if (IBNavigatorListener.PAGE_JUMP_WHEN_ROUTE_PLAN_FAIL == jumpTiming) {
finish();
}
}


@Override
public void notifyGPSStatusData(int arg0) {
// TODO Auto-generated method stub


}


@Override
public void notifyLoacteData(LocData arg0) {
// TODO Auto-generated method stub


}


@Override
public void notifyNmeaData(String arg0) {
// TODO Auto-generated method stub


}


@Override
public void notifySensorData(SensorData arg0) {
// TODO Auto-generated method stub


}


@Override
public void notifyStartNav() {
// TODO Auto-generated method stub
BaiduNaviManager.getInstance().dismissWaitProgressDialog();
}


@Override
public void notifyViewModeChanged(int arg0) {
// TODO Auto-generated method stub


}


};


@Override
public boolean onCreateOptionsMenu(Menu menu) {


// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map_navigation, menu);
return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}


/**
* A placeholder fragment containing a simple view.
*/


@Override
protected void onStart() {
// 開啟圖層定位


super.onStart();
}


@Override
protected void onStop() {
// 關閉圖層定位


}


@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();


}


@Override
protected void onDestroy() {
super.onDestroy();
// 在activity執行onDestroy時執行mMapView.onDestroy(),實現地圖生命週期管理


BaiduNaviManager.getInstance().destroyNMapView();
}


@Override
protected void onResume() {
super.onResume();
// 在activity執行onResume時執行mMapView. onResume (),實現地圖生命週期管理


BNavigator.getInstance().resume();
BNMapController.getInstance().onResume();
initMapView();
}


private void initMapView() {
if (Build.VERSION.SDK_INT < 14) {
BaiduNaviManager.getInstance().destroyNMapView();
}


nMapView = BaiduNaviManager.getInstance().createNMapView(this);
BNMapController.getInstance().setLevel(14);
BNMapController.getInstance().setLayerMode(
LayerMode.MAP_LAYER_MODE_BROWSE_MAP);
updateCompassPosition();


}


/**
* 更新指南針位置
*/
private void updateCompassPosition() {
int screenW = this.getResources().getDisplayMetrics().widthPixels;
BNMapController.getInstance().resetCompassPosition(
screenW - ScreenUtil.dip2px(this, 30),
ScreenUtil.dip2px(this, 126), -1);
}


}