你提醒我了,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;
// 来自 SearchResultActivity:使用定位结果作为起点
if (sourceType == SOURCE_FROM_HOME_SEARCH) {
if (currentLocation == null) {
tvRouteInfo.setText("无法获取您的位置,请稍后重试");
finish();
return;
}
start = currentLocation;
}
// 来自 MapFragment:使用传入的起点坐标
else if (sourceType == SOURCE_FROM_MAP_DIRECT) {
double startLat = getIntent().getDoubleExtra("start_lat", 0);
double startLng = getIntent().getDoubleExtra("start_lng", 0);
if (startLat == 0 || startLng == 0) {
tvRouteInfo.setText("请输入有效的起点");
finish();
return;
}
start = new LatLonPoint(startLat, startLng);
} else {
tvRouteInfo.setText("未知操作来源");
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);
}
}
如果MapFragment有问题,请你进行最小量的修改,跟刚刚一样保证原有功能框架不变,以免造成过多的报错