此處是爲了打車軟件路徑顯示效果而做的一個demo,如下圖所示:
上圖中起點是定位點座標,由於是實時導航GPS的時候所用,在移動情況下才會顯示出小車在規劃好的路徑上面行駛(即藍色線上),若不按線上的移動則會重新規劃路徑,由於沒有對座標點進行保存,所以移動效果是跳動的,不連貫。由於接觸的接觸地圖的時間比較的端,所以有些功能還不是很完善,在項目完成後會對代碼進行相應的操作。
其實現的部分主要代碼如下(代碼中對GPS連接及網絡連接做了相應的判斷):
/**
* 定位成功後回調函數
*/
@Override
public void onLocationChanged(AMapLocation amapLocation) {
if (mListener != null && amapLocation != null) {
if (amapLocation != null && amapLocation.getErrorCode() == 0) {
mListener.onLocationChanged(amapLocation);// 顯示系統小藍點
mLatitude = amapLocation.getLatitude();
mLongitude = amapLocation.getLongitude();
aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(mLatitude, mLongitude)));
aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
startPoint = new LatLonPoint(mLatitude, mLongitude);
mStartTxt.setText(amapLocation.getPoiName());
speed = amapLocation.getSpeed();
sp = (int) amapLocation.getSpeed();
Log.e("????????????????", "asihdfoiash" + sp);
}
} else {
String errText = "定位失敗," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
Log.e("AmapErr", errText);
}
}
/**
* 激活定位
*/
@Override
public void activate(OnLocationChangedListener listener) {
mListener = listener;
if (mLocationClient == null) {
mLocationClient = new AMapLocationClient(this);
mLocationOption = new AMapLocationClientOption();
//設置定位監聽
mLocationClient.setLocationListener(this);
//設置爲高精度定位模式
mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
mLocationOption.setInterval(5000);// 注意設置合適的定位時間的間隔(最小間隔支持爲2000ms)
// // 設置是否允許模擬位置,默認爲false,不允許模擬位置
// mLocationOption.setMockEnable(true);
//設置定位參數
mLocationClient.setLocationOption(mLocationOption);
// 此方法爲每隔固定時間會發起一次定位請求,爲了減少電量消耗或網絡流量消耗,
// 在定位結束後,在合適的生命週期調用onDestroy()方法
// 在單次定位情況下,定位無論成功與否,都無需調用stopLocation()方法移除請求,定位sdk內部會移除
mLocationClient.startLocation();
}
}
/**
* 停止定位
*/
@Override
public void deactivate() {
mListener = null;
if (mLocationClient != null) {
mLocationClient.stopLocation();
mLocationClient.onDestroy();
}
mLocationClient = null;
}
//點擊事件
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.end_address_txt:
Intent intentEnd = new Intent(this, AddressChildActivity.class);
startActivityForResult(intentEnd, 1);
break;
case R.id.navi_road_btn:
// initGPS();
searchRouteResult(startPoint, endPoint);
// turnGPSOn();
break;
case R.id.call_navi_btn:
Intent intent = new Intent(MainActivity.this, NavigationInterfaceActivity.class);
Bundle bundle = new Bundle();
bundle.putDouble("startLatitude", startPoint.getLatitude());
bundle.putDouble("startLongitude", startPoint.getLongitude());
bundle.putDouble("endLatitude", endPoint.getLatitude());
bundle.putDouble("endLongitude", endPoint.getLongitude());
bundle.putFloat("speed", speed);
intent.putExtras(bundle);
startActivity(intent);
break;
}
}
/**
* 判斷GPS是否打開,若開啓狀態則不做任何操作
* 若未開啓狀態則彈出對話框,點擊取消下次繼續彈出,點擊確定則跳轉到GPS控制界面,返回後繼續後繼操作
*/
private void initGPS() {
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// 判斷GPS模塊是否開啓,如果沒有則開啓
if (!locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
Toast.makeText(MainActivity.this, "請打開GPS", Toast.LENGTH_SHORT).show();
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("請打開GPS連接");
dialog.setMessage("爲方便司機更容易接到您,請先打開GPS");
dialog.setPositiveButton("設置", new android.content.DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// 轉到手機設置界面,用戶設置GPS
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
Toast.makeText(MainActivity.this, "打開後直接點擊返回鍵即可,若不打開返回下次將再次出現", Toast.LENGTH_SHORT).show();
startActivityForResult(intent, 0); // 設置完成後返回到原來的界面
}
});
dialog.setNeutralButton("取消", new android.content.DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
arg0.dismiss();
}
});
dialog.show();
} else {
searchRouteResult(startPoint, endPoint);//路徑規劃
// 彈出Toast
// Toast.makeText(TrainDetailsActivity.this, "GPS is ready",Toast.LENGTH_LONG).show();
// // 彈出對話框
// new AlertDialog.Builder(this).setMessage("GPS is ready").setPositiveButton("OK", null).show();
}
}
/**
* 判斷網絡連接是否已開
* true 已打開 false 未打開
*/
public static boolean isConn(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null) {
return mNetworkInfo.isAvailable();
}
searchNetwork(context);//彈出提示對話框
}
return false;
}
/**
* 判斷網絡是否連接成功,連接成功不做任何操作
* 未連接則彈出對話框提示用戶設置網絡連接
*/
public static void searchNetwork(final Context context) {
//提示對話框
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("網絡設置提示").setMessage("網絡連接不可用,是否進行設置?").setPositiveButton("設置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = null;
//判斷手機系統的版本 即API大於10 就是3.0或以上版本
if (android.os.Build.VERSION.SDK_INT > 10) {
intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
} else {
intent = new Intent();
ComponentName component = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
intent.setComponent(component);
intent.setAction("android.intent.action.VIEW");
}
context.startActivity(intent);
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
/**
* 強制開啓GPS方法,此方法在4.0及以上版本都不能使用
*/
public void turnGPSOn() {
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) { //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.sendBroadcast(poke);
}
}
/**
* 接受 選擇地址 的值
*/
private double longitude; //終點緯度
private double latitude; //終點經度
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Cantant.ADDRESSID_MAP) {
Bundle b = data.getExtras();
String address = b.getString("addressName");
longitude = b.getDouble("longitude");
latitude = b.getDouble("latitude");
Toast.makeText(this, address + "(" + longitude + "," + latitude + ")", Toast.LENGTH_SHORT).show();
endPoint = new LatLonPoint(latitude, longitude);
mEndTxt.setText(address);
} else if (resultCode == 0) {
// Toast.makeText(MainActivity.this, "請重新開始導航", Toast.LENGTH_SHORT).show();
// searchRouteResult(startPoint, endPoint);
// initGPS();
}
}
/**
* 開始搜索路徑規劃
*/
public void searchRouteResult(LatLonPoint startPoint, LatLonPoint endPoint) {
final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(startPoint, endPoint);
RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, drivingMode, null, null, "");// 第一個參數表示路徑規劃的起點和終點,第二個參數表示駕車模式,第三個參數表示途經點,第四個參數表示避讓區域,第五個參數表示避讓道路
routeSearch.calculateDriveRouteAsyn(query);// 異步路徑規劃駕車模式查詢
}
//公交路徑規劃
@Override
public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {
}
/**
* 駕車路徑規劃回調接口
*/
private NaviLatLng startLL;
private NaviLatLng endLL;
@Override
public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {
aMap.clear();// 清理地圖上的所有覆蓋物
if (i == 0) {
if (driveRouteResult != null && driveRouteResult.getPaths() != null && driveRouteResult.getPaths().size() > 0) {
driveResult = driveRouteResult;
DrivePath drivePath = driveRouteResult.getPaths().get(0);
startLL = new NaviLatLng(driveRouteResult.getStartPos().getLatitude(), driveRouteResult.getStartPos().getLongitude());
endLL = new NaviLatLng(driveRouteResult.getTargetPos().getLatitude(), driveRouteResult.getTargetPos().getLongitude());
mStartPoints.add(startLL);
mEndPoints.add(endLL);
boolean isSuccess = aMapNavi.calculateDriveRoute(mStartPoints, mEndPoints, null, PathPlanningStrategy.DRIVING_DEFAULT);
if (!isSuccess) {
Toast.makeText(this, "路線計算失敗,檢查參數情況", Toast.LENGTH_SHORT).show();
}
DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(this, aMap, drivePath, driveRouteResult.getStartPos(), driveRouteResult.getTargetPos());
drivingRouteOverlay.removeFromMap();
drivingRouteOverlay.addToMap();
drivingRouteOverlay.zoomToSpan();
} else {
ToastUtil.show(this, R.string.no_result);
}
} else if (i == 27) {
ToastUtil.show(this, R.string.error_network);
} else if (i == 32) {
ToastUtil.show(this, R.string.error_key);
} else {
ToastUtil.show(this, getString(R.string.error_other) + i);
}
}
//步行路徑規劃
@Override
public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {
}
//地圖移動事件處理
@Override
public void onCameraChange(CameraPosition cameraPosition) {
}
//地圖移動完成事件處理
@Override
public void onCameraChangeFinish(CameraPosition cameraPosition) {
}
/**
* 模擬語音導航路徑行駛
*/
@Override
public void onInitNaviFailure() {
Toast.makeText(this, "init navi Failed", Toast.LENGTH_SHORT).show();
}
@Override
public void onInitNaviSuccess() {
aMapNavi.calculateDriveRoute(mStartPoints, mEndPoints, null, PathPlanningStrategy.DRIVING_DEFAULT);
}
@Override
public void onStartNavi(int i) {
}
@Override
public void onTrafficStatusUpdate() {
}
@Override
public void onLocationChange(AMapNaviLocation aMapNaviLocation) {
}
@Override
public void onGetNavigationText(int i, String s) {
}
@Override
public void onEndEmulatorNavi() {
}
@Override
public void onArriveDestination() {
}
@Override
public void onCalculateRouteSuccess() {
// mRouteOverLay.removeFromMap();
AMapNaviPath naviPath = aMapNavi.getNaviPath();
aMapNavi.startNavi(1);
aMapNavi.startGPS();
if (naviPath == null) {
return;
}
// 獲取路徑規劃線路,顯示到地圖上
// mRouteOverLay.setAMapNaviPath(naviPath);
// mRouteOverLay.addToMap();
mRouteOverLay.zoomToSpan();
mRouteOverLay.setEmulateGPSLocationVisible();
}
@Override
public void onCalculateRouteFailure(int i) {
}
@Override
public void onReCalculateRouteForYaw() {
aMap.clear();
searchRouteResult(startPoint, endPoint);
aMapNavi.calculateDriveRoute(mStartPoints, mEndPoints, null, PathPlanningStrategy.DRIVING_DEFAULT);
}
@Override
public void onReCalculateRouteForTrafficJam() {
aMap.clear();
searchRouteResult(startPoint, endPoint);
aMapNavi.calculateDriveRoute(mStartPoints, mEndPoints, null, PathPlanningStrategy.DRIVING_DEFAULT);
}
@Override
public void onArrivedWayPoint(int i) {
}
@Override
public void onGpsOpenStatus(boolean b) {
b = true;
}
@Override
public void onNaviInfoUpdated(AMapNaviInfo aMapNaviInfo) {
}
@Override
public void onNaviInfoUpdate(NaviInfo naviInfo) {
Toast.makeText(this, "現在的速度是:" + sp, Toast.LENGTH_SHORT).show();
CarLatLngBean bean = new CarLatLngBean();
bean.setLatitude(naviInfo.getCoord().getLatitude());
bean.setLongitude(naviInfo.getCoord().getLongitude());
list.add(bean);
initRoadData(list);
if (list.size() > 2) {
moveLooper();
} else {
return;
}
}
@Override
public void OnUpdateTrafficFacility(TrafficFacilityInfo trafficFacilityInfo) {
}
@Override
public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo aMapNaviTrafficFacilityInfo) {
}
@Override
public void showCross(AMapNaviCross aMapNaviCross) {
}
@Override
public void hideCross() {
}
@Override
public void showLaneInfo(AMapLaneInfo[] aMapLaneInfos, byte[] bytes, byte[] bytes1) {
Toast.makeText(this, "導航計算失敗!" + aMapLaneInfos, Toast.LENGTH_SHORT).show();
}
@Override
public void hideLaneInfo() {
}
@Override
public void onCalculateMultipleRoutesSuccess(int[] ints) {
}
@Override
public void notifyParallelRoad(int i) {
}
public void initRoadData(ArrayList<CarLatLngBean> list) {
PolylineOptions polylineOptions = new PolylineOptions();
if (list.size() > 2) {
int counts = list.size();
for (int i = 0; i < counts; i++) {
polylineOptions.add(new LatLng(list.get(i).getLatitude(), list.get(i).getLongitude()));
}
polylineOptions.width(0);
polylineOptions.color(Color.RED);
mVirtureRoad = aMap.addPolyline(polylineOptions);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.setFlat(true);
markerOptions.anchor(0.5f, 0.5f);
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.taxi_bearing));
markerOptions.position(polylineOptions.getPoints().get(0));
if (mMoveMarker != null)
mMoveMarker.remove();
list.clear();
mMoveMarker = aMap.addMarker(markerOptions);
mMoveMarker.showInfoWindow();
mMoveMarker.setRotateAngle((float) getAngle(0));
} else {
return;
}
}
/**
* 根據點獲取圖標轉的角度
*/
private double getAngle(int startIndex) {
if ((startIndex + 1) >= mVirtureRoad.getPoints().size()) {
throw new RuntimeException("index out of bonds");
}
LatLng startPoint = mVirtureRoad.getPoints().get(startIndex);
LatLng endPoint = mVirtureRoad.getPoints().get(startIndex + 1);
return getAngle(startPoint, endPoint);
}
/**
* 根據兩點算取圖標轉的角度
*/
private double getAngle(LatLng fromPoint, LatLng toPoint) {
double slope = getSlope(fromPoint, toPoint);
if (slope == Double.MAX_VALUE) {
if (toPoint.latitude > fromPoint.latitude) {
return 0;
} else {
return 180;
}
}
float deltAngle = 0;
if ((toPoint.latitude - fromPoint.latitude) * slope < 0) {
deltAngle = 180;
}
double radio = Math.atan(slope);
double angle = 180 * (radio / Math.PI) + deltAngle - 90;
return angle;
}
/**
* 根據點和斜率算取截距
*/
private double getInterception(double slope, LatLng point) {
double interception = point.latitude - slope * point.longitude;
return interception;
}
/**
* 算取斜率
*/
private double getSlope(int startIndex) {
if ((startIndex + 1) >= mVirtureRoad.getPoints().size()) {
throw new RuntimeException("index out of bonds");
}
LatLng startPoint = mVirtureRoad.getPoints().get(startIndex);
LatLng endPoint = mVirtureRoad.getPoints().get(startIndex + 1);
return getSlope(startPoint, endPoint);
}
/**
* 算斜率
*/
private double getSlope(LatLng fromPoint, LatLng toPoint) {
if (toPoint.longitude == fromPoint.longitude) {
return Double.MAX_VALUE;
}
double slope = ((toPoint.latitude - fromPoint.latitude) / (toPoint.longitude - fromPoint.longitude));
return slope;
}
/**
* 計算x方向每次移動的距離
*/
private double getXMoveDistance(double slope) {
if (slope == Double.MAX_VALUE) {
return DISTANCE;
}
return Math.abs((DISTANCE * slope) / Math.sqrt(1 + slope * slope));
}
/**
* 進行移動邏輯
*/
public void moveLooper() {
new Thread() {
public void run() {
for (int i = 0; i < mVirtureRoad.getPoints().size() - 1; i++) {
LatLng startPoint = mVirtureRoad.getPoints().get(i);
LatLng endPoint = mVirtureRoad.getPoints().get(i + 1);
mMoveMarker.setPosition(startPoint);
mMoveMarker.setRotateAngle((float) getAngle(startPoint, endPoint));
double slope = getSlope(startPoint, endPoint);
//是不是正向的標示(向上設爲正向)
boolean isReverse = (startPoint.latitude > endPoint.latitude);
double intercept = getInterception(slope, startPoint);
double xMoveDistance = isReverse ? getXMoveDistance(slope) : -1 * getXMoveDistance(slope);
for (double j = startPoint.latitude; !((j > endPoint.latitude) ^ isReverse); j = j - xMoveDistance) {
LatLng latLng = null;
if (slope != Double.MAX_VALUE) {
latLng = new LatLng(j, (j - intercept) / slope);
} else {
latLng = new LatLng(j, startPoint.longitude);
}
mMoveMarker.setPosition(latLng);
try {
Thread.sleep(TIME_INTERVAL);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}.start();
}
上述的功能代碼我已經放到我的資源下載中去了http://download.csdn.net/detail/q394895302/9478728,demo用Android studio開發的。