现在代码都给你。第一,SearchResultActivity代码如下:package com.example.bus;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import java.util.ArrayList;
import java.util.List;
public class SearchResultActivity extends AppCompatActivity implements PoiSearch.OnPoiSearchListener {
private Button searchBtn, goToBtn;
private RecyclerView resultListView;
private List<PoiItem> poiList = new ArrayList<>();
private ResultAdapter adapter;
private PoiSearch poiSearch;
// 地图相关
private MapView mapView;
private AMap aMap;
private Marker selectedMarker;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1001;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("搜索地点");
}
initViews();
setupMap(savedInstanceState);
setupSearch();
// ✅ 在地图初始化完成后尝试开启蓝点(会自动请求权限)
enableMyLocationLayer();
}
private void initViews() {
searchBtn = findViewById(R.id.search_btn);
resultListView = findViewById(R.id.result_list);
goToBtn = findViewById(R.id.btn_go_to);
goToBtn.setEnabled(false);
}
private void setupMap(Bundle savedInstanceState) {
mapView = findViewById(R.id.map_view);
mapView.onCreate(savedInstanceState);
if (aMap == null) {
aMap = mapView.getMap();
UiSettings uiSettings = aMap.getUiSettings();
uiSettings.setZoomControlsEnabled(true);
uiSettings.setCompassEnabled(true);
uiSettings.setScrollGesturesEnabled(true);
// 设置地图点击事件:添加选中位置标记
aMap.setOnMapClickListener(latLng -> {
if (selectedMarker != null) {
selectedMarker.remove();
}
selectedMarker = aMap.addMarker(new MarkerOptions()
.position(latLng)
.title("选中位置"));
goToBtn.setEnabled(true);
});
// 默认视角为中国中心
aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(39.909186, 116.397411), 10f));
}
}
/**
* 开启地图蓝点(我的位置)
* 如果已有权限则直接启用,否则请求权限
*/
private void enableMyLocationLayer() {
if (aMap == null) return;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
try {
aMap.setMyLocationEnabled(true);
Toast.makeText(this, "已开启实时定位", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "无法开启定位图层", Toast.LENGTH_SHORT).show();
}
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (aMap != null) {
aMap.setMyLocationEnabled(true);
Toast.makeText(this, "已成功开启定位功能", Toast.LENGTH_SHORT).show();
}
} else {
boolean hasCoarse = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED;
if (hasCoarse) {
Toast.makeText(this, "建议开启精确位置以获得更准确定位", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "定位权限被拒绝,部分功能受限", Toast.LENGTH_LONG).show();
}
}
}
}
private void setupSearch() {
String keyword = getIntent().getStringExtra("keyword");
if (keyword != null && !keyword.isEmpty()) {
performSearch(keyword);
}
searchBtn.setOnClickListener(v -> {
String text = ((android.widget.EditText) findViewById(R.id.search_input)).getText().toString().trim();
if (!text.isEmpty()) {
performSearch(text);
} else {
Toast.makeText(this, "请输入关键词", Toast.LENGTH_SHORT).show();
}
});
goToBtn.setOnClickListener(v -> {
LatLonPoint targetPoint = null;
String title = "选中位置";
if (selectedMarker != null) {
LatLng pos = selectedMarker.getPosition();
targetPoint = new LatLonPoint(pos.latitude, pos.longitude);
title = selectedMarker.getTitle();
} else if (!poiList.isEmpty()) {
PoiItem item = poiList.get(0);
targetPoint = item.getLatLonPoint();
title = item.getTitle();
}
if (targetPoint == null) {
Toast.makeText(this, "暂无目标位置", Toast.LENGTH_SHORT).show();
return;
}
Intent intent = new Intent(this, RoutePlanActivity.class);
intent.putExtra(RoutePlanActivity.EXTRA_SOURCE, RoutePlanActivity.SOURCE_FROM_HOME_SEARCH);
intent.putExtra("target_lat", targetPoint.getLatitude());
intent.putExtra("target_lng", targetPoint.getLongitude());
intent.putExtra("target_title", title);
startActivity(intent);
});
}
private void performSearch(String keyword) {
PoiSearch.Query query = isLikelyBusStop(keyword) ?
new PoiSearch.Query(keyword, "15", "全国") :
new PoiSearch.Query(keyword, "", "全国");
query.setPageSize(20);
query.setPageNum(0);
try {
poiSearch = new PoiSearch(this, query);
poiSearch.setOnPoiSearchListener(this);
poiSearch.searchPOIAsyn();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "搜索启动失败", Toast.LENGTH_SHORT).show();
}
}
private boolean isLikelyBusStop(String keyword) {
return keyword.contains("公交") || keyword.contains("地铁") ||
keyword.contains("BRT") || keyword.endsWith("站") || keyword.endsWith("场");
}
@Override
public void onPoiSearched(PoiResult result, int rCode) {
if (rCode == 1000 && result != null && result.getPois() != null) {
poiList.clear();
poiList.addAll(result.getPois());
if (adapter == null) {
adapter = new ResultAdapter(poiList, item -> {
if (selectedMarker != null) selectedMarker.remove();
LatLng latLng = new LatLng(item.getLatLonPoint().getLatitude(), item.getLatLonPoint().getLongitude());
selectedMarker = aMap.addMarker(new MarkerOptions().position(latLng).title(item.getTitle()));
aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14f));
goToBtn.setEnabled(true);
});
resultListView.setLayoutManager(new LinearLayoutManager(this));
resultListView.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
goToBtn.setEnabled(!poiList.isEmpty());
} else {
String msg = rCode == 17 ? "高德Key校验失败" : "搜索失败: 错误码=" + rCode;
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
}
@Override
public void onPoiItemSearched(PoiItem item, int rCode) {
// 不处理详情查询
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
if (aMap != null) {
aMap.setMyLocationEnabled(false); // 关闭蓝点
}
if (poiSearch != null) {
poiSearch.setOnPoiSearchListener(null);
}
mapView = null;
aMap = null;
poiSearch = null;
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
第二,MapFragment代码如下:package com.example.bus.ui.map;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.amap.api.maps.MapView;
import com.amap.api.maps.AMap;
import com.amap.api.maps.model.LatLng;
//import com.example.bus.R;
//import com.example.bus.databinding.FragmentMapBinding;
import com.amap.api.services.core.AMapException;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.UiSettings;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.example.bus.R;
import com.example.bus.RoutePlanActivity;
import com.example.bus.databinding.FragmentMapBinding;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.LatLonPoint;
// MapView 已在 XML 中声明,无需额外 import(会自动识别)
public class MapFragment extends Fragment {
private FragmentMapBinding binding;
private MapView mapView; // 高德地图视图
private AMap aMap; // 地图控制器
private boolean isFirstLocationSet = false; // 防止反复跳转
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// 初始化 ViewModel 和 ViewBinding
binding = FragmentMapBinding.inflate(inflater, container, false);
View root = binding.getRoot();
//绑定 MapView
mapView = root.findViewById(R.id.map_view);
mapView.onCreate(savedInstanceState); // 必须调用生命周期方法
// 初始化地图
initMap();
if (binding.mapSearch != null) {
binding.mapSearch.setOnClickListener(v -> {
String keyword = binding.mapInput2.getText().toString().trim();
if (keyword.isEmpty()) {
Toast.makeText(requireContext(), "请输入终点", Toast.LENGTH_SHORT).show();
return;
}
PoiSearch.Query query = new PoiSearch.Query(keyword, "", "全国");
query.setPageSize(10);
query.setPageNum(0);
try {
PoiSearch search = new PoiSearch(requireContext(), query);
search.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
@Override
public void onPoiSearched(PoiResult result, int rCode) {
requireActivity().runOnUiThread(() -> {
if (rCode == 1000 && result != null && !result.getPois().isEmpty()) {
PoiItem item = result.getPois().get(0);
LatLonPoint point = item.getLatLonPoint();
// ✅ 使用地图当前中心作为起点
LatLng center = aMap.getCameraPosition().target;
Intent intent = new Intent(requireContext(), RoutePlanActivity.class);
intent.putExtra(RoutePlanActivity.EXTRA_SOURCE, RoutePlanActivity.SOURCE_FROM_MAP_DIRECT);
intent.putExtra("start_lat", center.latitude);
intent.putExtra("start_lng", center.longitude);
intent.putExtra("target_lat", point.getLatitude());
intent.putExtra("target_lng", point.getLongitude());
intent.putExtra("target_title", item.getTitle());
startActivity(intent);
} else {
handlePoiSearchError(rCode);
}
});
}
@Override
public void onPoiItemSearched(PoiItem item, int rCode) {}
});
search.searchPOIAsyn();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(requireContext(), "搜索失败:" + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
return root;
}
private void handlePoiSearchError(int rCode) {
String errorMsg;
switch (rCode) {
case 1101:
errorMsg = "网络连接异常";
break;
case 1102:
errorMsg = "网络响应超时";
break;
case 1103:
errorMsg = "解析异常";
break;
case 1104:
errorMsg = "请求参数非法";
break;
case 1200:
errorMsg = "API Key 不存在";
break;
case 1202:
errorMsg = "签名验证失败(SHA1/包名不匹配)";
break;
case 1206:
errorMsg = "API Key 权限不足(未开通 POI 搜索服务)";
break;
default:
errorMsg = "未知错误: " + rCode;
break;
}
Toast.makeText(requireContext(), "搜索失败: " + errorMsg, Toast.LENGTH_LONG).show();
}
/**
* 初始化地图
*/
private void initMap() {
if (aMap == null) {
aMap = mapView.getMap();
UiSettings uiSettings = aMap.getUiSettings();
uiSettings.setZoomControlsEnabled(true); // 显示缩放按钮
uiSettings.setCompassEnabled(true); // 显示指南针
uiSettings.setMyLocationButtonEnabled(false); // 我们自己控制定位行为
}
}
@Override
public void onResume() {
super.onResume(); //每次恢复可见时都检查权限状态
mapView.onResume();
// ✅ 直接开启定位图层(信任 MainActivity 的判断)
if (aMap != null) {
aMap.setMyLocationEnabled(true);
// 只第一次进入时移动相机
if (!isFirstLocationSet) {
LatLng defaultLoc = new LatLng(39.909186, 116.397411);
aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(defaultLoc, 12f));
isFirstLocationSet = true;
}
}
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (mapView != null) {
mapView.onDestroy();
}
binding = null;
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
第三:RoutePlanActivity代码如下:package com.example.bus;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.activity.OnBackPressedCallback;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusPath;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.BusStep;
import com.amap.api.services.route.RouteSearch;
import java.util.ArrayList;
import java.util.List;
public class RoutePlanActivity extends AppCompatActivity implements RouteSearch.OnRouteSearchListener, AMapLocationListener {
// 来源类型常量
public static final String EXTRA_SOURCE = "extra_source";
public static final int SOURCE_FROM_HOME_SEARCH = 1001;
public static final int SOURCE_FROM_MAP_DIRECT = 1002;
private MapView mapView;
private AMap aMap;
private RouteSearch routeSearch;
private RecyclerView recyclerSteps;
private TextView tvRouteInfo; // 持久显示路线信息
private boolean isSearching = false;
private int sourceType = -1;
// 定位相关
private AMapLocationClient locationClient;
private LatLonPoint currentLocation; // 存储定位到的“我的位置”
private LatLonPoint targetPoint; // 存储目标点(终点)
// 新增:防止重复发起搜索
private boolean hasStartedSearch = false; // 🔥 控制只发起一次搜索
// 新增:用于管理返回键行为
private OnBackPressedCallback onBackPressedCallback;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route_plan);
// 获取来源
sourceType = getIntent().getIntExtra(EXTRA_SOURCE, -1);
// 获取目标位置
double targetLat = getIntent().getDoubleExtra("target_lat", 0);
double targetLng = getIntent().getDoubleExtra("target_lng", 0);
if (targetLat == 0 || targetLng == 0) {
Toast.makeText(this, "目标位置无效", Toast.LENGTH_SHORT).show();
finish();
return;
}
targetPoint = new LatLonPoint(targetLat, targetLng);
// 初始化视图
mapView = findViewById(R.id.map_view);
recyclerSteps = findViewById(R.id.recycler_steps);
tvRouteInfo = findViewById(R.id.tv_route_info); // 显示路线信息(持续)
mapView.onCreate(savedInstanceState);
if (aMap == null) {
aMap = mapView.getMap();
}
try {
routeSearch = new RouteSearch(this);
routeSearch.setRouteSearchListener(this);
} catch (Exception e) {
Log.e("RoutePlan", "RouteSearch 初始化失败", e);
tvRouteInfo.setText("路线服务初始化失败");
finish();
return;
}
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("公交路线规划");
}
// 初始化定位
initLocation();
// 如果来自 MapFragment,直接发起搜索(不需要等定位)
if (sourceType == SOURCE_FROM_MAP_DIRECT) {
startRouteSearch(); // 🔥 提前发起搜索,不等待定位
}
// 🔥 替换 onBackPressed:注册 OnBackPressedCallback
onBackPressedCallback = new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
if (sourceType == SOURCE_FROM_MAP_DIRECT) {
Intent intent = new Intent(RoutePlanActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("open_tab", "map");
startActivity(intent);
finish();
} else {
setEnabled(false);
getOnBackPressedDispatcher().onBackPressed();
setEnabled(true);
}
}
};
getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback);
}
/**
* 初始化定位客户端
*/
private void initLocation() {
try {
locationClient = new AMapLocationClient(this);
AMapLocationClientOption option = new AMapLocationClientOption();
option.setOnceLocation(true);
option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
option.setMockEnable(false);
locationClient.setLocationOption(option);
locationClient.setLocationListener(this);
locationClient.startLocation();
tvRouteInfo.setText("正在获取您的位置...");
} catch (Exception e) {
Log.e("RoutePlan", "定位初始化失败", e);
tvRouteInfo.setText("定位服务启动失败");
finish();
}
}
/**
* 发起公交路线搜索(增加防重发机制)
*/
private void startRouteSearch() {
if (isSearching || hasStartedSearch) return;
hasStartedSearch = true; // ✅ 必须第一时间标记,防止定位回调干扰
LatLonPoint start = null;
if (sourceType == SOURCE_FROM_HOME_SEARCH) {
if (currentLocation == null) {
Log.e("RoutePlan", "📍 定位未完成,无法发起 HOME_SEARCH");
tvRouteInfo.setText("无法获取您的位置,请稍后重试");
finish();
return;
}
start = currentLocation;
Log.d("RoutePlan", "🏠 使用定位位置作为起点: " + start.getLatitude() + "," + start.getLongitude());
}
else if (sourceType == SOURCE_FROM_MAP_DIRECT) {
double startLat = getIntent().getDoubleExtra("start_lat", 0);
double startLng = getIntent().getDoubleExtra("start_lng", 0);
if (Math.abs(startLat) < 1e-6 || Math.abs(startLng) < 1e-6) {
Log.e("RoutePlan", "❌ MapDirect: 起点坐标无效 (" + startLat + ", " + startLng + ")");
tvRouteInfo.setText("起点坐标错误");
finish();
return;
}
start = new LatLonPoint(startLat, startLng);
Log.d("RoutePlan", "🗺️ 使用地图中心作为起点: " + start.getLatitude() + "," + start.getLongitude());
} else {
tvRouteInfo.setText("未知操作来源");
Log.e("RoutePlan", "❌ 未知来源: " + sourceType);
finish();
return;
}
// 构建查询
RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(start, targetPoint);
RouteSearch.BusRouteQuery query = new RouteSearch.BusRouteQuery(fromAndTo, RouteSearch.BUS_DEFAULT, "全国", 0);
isSearching = true;
tvRouteInfo.setText("正在规划路线...");
routeSearch.calculateBusRouteAsyn(query);
}
@Override
public void onLocationChanged(AMapLocation loc) {
if (loc != null && loc.getErrorCode() == 0) {
currentLocation = new LatLonPoint(loc.getLatitude(), loc.getLongitude());
Log.d("RoutePlan", "✅ 定位成功: " + loc.getLatitude() + "," + loc.getLongitude());
// 只有来自 SearchResultActivity 才在此处开始搜索
if (sourceType == SOURCE_FROM_HOME_SEARCH && !hasStartedSearch) {
startRouteSearch();
}
// 🔥 其他情况(如 MapDirect)已经搜过或不需要定位数据,无需处理
} else {
Log.e("RoutePlan", "❌ 定位失败: " + (loc != null ? loc.getErrorInfo() : "null"));
tvRouteInfo.setText("定位失败,请检查权限");
Toast.makeText(this, "无法获取位置", Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void onBusRouteSearched(BusRouteResult result, int rCode) {
isSearching = false;
if (rCode != 1000 || result == null || result.getPaths().isEmpty()) {
tvRouteInfo.setText("未找到公交路线");
return;
}
BusPath bestPath = result.getPaths().get(0); // 默认最优路线
drawRouteOnMap(bestPath);
StepAdapter adapter = new StepAdapter(bestPath.getSteps());
recyclerSteps.setLayoutManager(new LinearLayoutManager(this));
recyclerSteps.setAdapter(adapter);
// ✅ 手动计算总时间和换乘次数
long totalDuration = 0;
int busRideCount = 0;
for (BusStep step : bestPath.getSteps()) {
// 公交段
if (step.getBusLine() != null && step.getBusLine().getDuration() > 0) {
totalDuration += step.getBusLine().getDuration();
busRideCount++;
}
// 步行段
else if (step.getWalk() != null) {
totalDuration += step.getWalk().getDuration();
}
}
int transferNum = Math.max(0, busRideCount - 1);
// 显示路线概要信息
String info = String.format("⏱️ %d分钟 | 💰 ¥%.2f | 🚌 %d次换乘",
totalDuration / 60,
bestPath.getCost(),
transferNum);
tvRouteInfo.setText(info);
}
/**
* 绘制路线
*/
private void drawRouteOnMap(BusPath path) {
aMap.clear();
List<LatLng> allPoints = new ArrayList<>();
for (BusStep step : path.getSteps()) {
// 公交段
if (step.getBusLine() != null && step.getBusLine().getPolyline() != null) {
for (LatLonPoint point : step.getBusLine().getPolyline()) {
allPoints.add(new LatLng(point.getLatitude(), point.getLongitude()));
}
}
// 步行段
else if (step.getWalk() != null && step.getWalk().getPolyline() != null) {
for (LatLonPoint point : step.getWalk().getPolyline()) {
allPoints.add(new LatLng(point.getLatitude(), point.getLongitude()));
}
}
// 出入口 fallback
else {
if (step.getEntrance() != null && step.getEntrance().getLatLonPoint() != null) {
LatLonPoint p = step.getEntrance().getLatLonPoint();
allPoints.add(new LatLng(p.getLatitude(), p.getLongitude()));
}
if (step.getExit() != null && step.getExit().getLatLonPoint() != null) {
LatLonPoint p = step.getExit().getLatLonPoint();
allPoints.add(new LatLng(p.getLatitude(), p.getLongitude()));
}
}
}
if (!allPoints.isEmpty()) {
PolylineOptions options = new PolylineOptions()
.addAll(allPoints)
.color(0xFF4A90E2)
.width(12f);
aMap.addPolyline(options);
// 聚焦整条路线
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng point : allPoints) {
builder.include(point);
}
aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 100));
} else {
tvRouteInfo.setText("路线数据为空");
}
}
@Override
public boolean onSupportNavigateUp() {
getOnBackPressedDispatcher().onBackPressed();
return true;
}
// 以下回调不处理
@Override
public void onDriveRouteSearched(com.amap.api.services.route.DriveRouteResult r, int c) {}
@Override
public void onWalkRouteSearched(com.amap.api.services.route.WalkRouteResult r, int c) {}
@Override
public void onRideRouteSearched(com.amap.api.services.route.RideRouteResult r, int c) {}
// 生命周期方法
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
if (routeSearch != null) {
routeSearch.setRouteSearchListener(null);
}
if (locationClient != null) {
locationClient.onDestroy();
}
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
现在,刚刚描述的那一切问题都没有解决。第一,我希望的是,如果从SearchResultActivity中进入的RoutePlanActivity,我需要用自己实际的位置作为起点,而不是最近的公交站作为起点。如果我不在公交站/地铁站,需要步行前往,这部分步行路线不能省略。第二,如果从MapFragment进入RoutePlanActivity,则不应该从我的位置开始规划路线,而是从MapFragment中输入的起点位置开始规划路线
最新发布