但请你注意一点,这个是搜索提示框,他还拥有一个补全信息的功能,是含有猜测的功能所在的,他需要预测用户需要搜索的信息,目前代码中确实含有这样的功能,只不过我希望他能够跟搜索结果的逻辑保持一致而已。所以不同于搜索结果,这里每输入一个字都要进行实时更新而且响应要快
而目前我的代码还没有做更改,这也是我的疏忽,刚刚没跟你说明白这些东西。目前各部分代码如下:
1、RealTimePoiSuggestHelper代码如下:package com.example.bus;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.NonNull;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
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 com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class RealTimePoiSuggestHelper implements OnPoiSearchListener {
private final Context context;
private final Handler mainHandler = new Handler(Looper.getMainLooper());
private PoiSearch poiSearch;
private SuggestionCallback callback;
private String currentCity = "";
private double lat = 0, lng = 0;
private boolean useLocationBias = false;
private boolean useDistanceSort = false; // 是否按距离排序建议
public interface SuggestionCallback {
void onSuggestionsReady(String[] suggestions);
}
public RealTimePoiSuggestHelper(Context context) {
this.context = context;
}
public void setCurrentCity(String city) {
this.currentCity = city;
}
public void setLocationBias(double lat, double lng) {
this.lat = lat;
this.lng = lng;
this.useLocationBias = true;
}
public void setUseDistanceSort(boolean use) {
this.useDistanceSort = use;
}
public void setCallback(SuggestionCallback callback) {
this.callback = callback;
}
public void requestSuggestions(String keyword) {
if (keyword.isEmpty() || callback == null) return;
// 使用 CityManager 解析是否有显式城市
CityManager.ParsedQuery parsed = CityManager.parse(keyword);
String actualKeyword = parsed.keyword.isEmpty() ? keyword : parsed.keyword;
String city = !parsed.targetCity.isEmpty() ? parsed.targetCity : currentCity; // 显式城市 > 当前城市
PoiSearch.Query query = new PoiSearch.Query(actualKeyword, "", city);
query.setPageSize(20);
query.requireSubPois(false);
if (useLocationBias) {
LatLonPoint lp = new LatLonPoint(lat, lng);
query.setLocation(lp);
}
try {
poiSearch = new PoiSearch(context, query);
poiSearch.setOnPoiSearchListener(this);
poiSearch.searchPOIAsyn();
} catch (Exception e) {
e.printStackTrace();
notifyEmpty();
}
}
@Override
public void onPoiSearched(PoiResult result, int rCode) {
if (rCode == 1000 && result != null && result.getPois() != null) {
List<PoiItem> pois = result.getPois();
List<String> names;
if (useDistanceSort && useLocationBias) {
// ✅ 正确做法:将 LatLonPoint 转为 LatLng 再计算距离
LatLng me = new LatLng(lat, lng);
names = pois.stream()
.sorted((a, b) -> {
LatLng pointA = toLatLng(a.getLatLonPoint());
LatLng pointB = toLatLng(b.getLatLonPoint());
double distA = AMapUtils.calculateLineDistance(pointA, me);
double distB = AMapUtils.calculateLineDistance(pointB, me);
return Double.compare(distA, distB);
})
.map(PoiItem::getTitle)
.collect(Collectors.toList());
} else {
names = new ArrayList<>();
for (PoiItem item : pois) {
names.add(item.getTitle());
}
}
String[] arr = names.toArray(new String[0]);
notifySuccess(arr);
} else {
notifyEmpty();
}
}
@Override
public void onPoiItemSearched(com.amap.api.services.core.PoiItem item, int rCode) {
// 忽略
}
// ✅ 新增工具方法:将 LatLonPoint 转换为 LatLng
private LatLng toLatLng(LatLonPoint point) {
if (point == null) return null;
return new LatLng(point.getLatitude(), point.getLongitude());
}
private void notifySuccess(@NonNull String[] suggestions) {
mainHandler.post(() -> callback.onSuggestionsReady(suggestions));
}
private void notifyEmpty() {
mainHandler.post(() -> callback.onSuggestionsReady(new String[0]));
}
}
2、MapFragment代码如下:package com.example.bus.ui.map;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.constraintlayout.widget.ConstraintSet;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
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.maps.model.MyLocationStyle;
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 com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.example.bus.CityManager;
import com.example.bus.R;
import com.example.bus.RealTimePoiSuggestHelper;
import com.example.bus.RoutePlanActivity;
import com.example.bus.ResultAdapter;
import com.example.bus.databinding.FragmentMapBinding;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MapFragment extends Fragment implements PoiSearch.OnPoiSearchListener, GeocodeSearch.OnGeocodeSearchListener {
private FragmentMapBinding binding;
private MapView mapView;
private AMap aMap;
private RealTimePoiSuggestHelper activeSuggestHelper;
// 数据
private List<PoiItem> poiList = new ArrayList<>();
private ResultAdapter adapter;
// 当前阶段:1=选择起点, 2=选择终点
private int selectionStage = 0;
// 缓存已选 POI
private PoiItem selectedStartPoi = null;
private PoiItem selectedEndPoi = null;
private Marker startMarker = null;
private Marker endMarker = null;
// 缓存关键词
private String lastStartKeyword = "";
private String lastEndKeyword = "";
// ✅ 当前城市
private String currentCity = "";
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1001;
// ✅ 标记是否已居中我的位置
private boolean userHasInteracted = false;
// ✅ 反地理编码(仅用于“我的位置”)
private GeocodeSearch geocodeSearch;
// 【关键新增】保存定位得到的“我的位置”
private double myCurrentLat = 0;
private double myCurrentLng = 0;
private boolean isLocationReady = false; // 定位是否完成
// 🔽 新增缓存字段
private List<PoiItem> nationalResults = new ArrayList<>(); // 全国结果
private List<PoiItem> localResults = new ArrayList<>(); // 本市结果
private List<PoiItem> nearbyResults = new ArrayList<>(); // 附近结果
private boolean isNearbyLoaded = false; // 是否已加载 nearby 数据
private boolean isInNearbyMode = false; // 是否处于附近模式
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binding = FragmentMapBinding.inflate(inflater, container, false);
View root = binding.getRoot();
mapView = binding.mapView;
mapView.onCreate(savedInstanceState);
initViews();
setupMap(savedInstanceState);
setupSearchSuggestion();
return root;
}
private void initViews() {
adapter = new ResultAdapter(poiList, this::onPoiItemSelected);
binding.resultList.setLayoutManager(new LinearLayoutManager(requireContext()));
binding.resultList.setAdapter(adapter);
binding.mapSearch.setOnClickListener(v -> performSearch());
binding.btnSwitchTarget.setOnClickListener(v -> {
if (selectionStage == 1) {
showEndpointSelection(binding.mapInput2.getText().toString().trim());
} else if (selectionStage == 2) {
showStartpointSelection(binding.mapInput1.getText().toString().trim());
}
});
binding.btnGoTo.setOnClickListener(v -> {
if (selectedStartPoi != null && selectedEndPoi != null) {
Intent intent = new Intent(requireContext(), RoutePlanActivity.class);
intent.putExtra(RoutePlanActivity.EXTRA_SOURCE, RoutePlanActivity.SOURCE_FROM_MAP_DIRECT);
intent.putExtra("start_lat", selectedStartPoi.getLatLonPoint().getLatitude());
intent.putExtra("start_lng", selectedStartPoi.getLatLonPoint().getLongitude());
intent.putExtra("target_lat", selectedEndPoi.getLatLonPoint().getLatitude());
intent.putExtra("target_lng", selectedEndPoi.getLatLonPoint().getLongitude());
intent.putExtra("target_title", selectedEndPoi.getTitle());
startActivity(intent);
} else {
Toast.makeText(requireContext(), "请完成起点和终点的选择", Toast.LENGTH_SHORT).show();
}
});
binding.btnToggleMode.setOnClickListener(v -> {
if (isInNearbyMode) {
exitNearbyMode();
} else {
enterNearbyMode();
}
});
}
private void performSearch() {
String startKeyword = binding.mapInput1.getText().toString().trim();
String endKeyword = binding.mapInput2.getText().toString().trim();
if (startKeyword.isEmpty()) {
Toast.makeText(requireContext(), "请输入起点", Toast.LENGTH_SHORT).show();
return;
}
if (endKeyword.isEmpty()) {
Toast.makeText(requireContext(), "请输入终点", Toast.LENGTH_SHORT).show();
return;
}
if (startKeyword.equals(lastStartKeyword) &&
endKeyword.equals(lastEndKeyword) &&
selectedStartPoi != null &&
selectedEndPoi != null) {
binding.btnGoTo.performClick();
return;
}
binding.containerResultList.setVisibility(View.VISIBLE);
binding.buttonGroup.setVisibility(View.VISIBLE);
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(binding.getRoot());
constraintSet.connect(
R.id.map_view, ConstraintSet.BOTTOM,
R.id.container_result_list, ConstraintSet.TOP,
0
);
constraintSet.applyTo(binding.getRoot());
userHasInteracted = true;
View currentFocus = requireActivity().getCurrentFocus();
if (currentFocus != null) {
currentFocus.clearFocus();
InputMethodManager imm = (InputMethodManager) requireContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(currentFocus.getWindowToken(), 0);
}
if (!startKeyword.equals(lastStartKeyword)) {
lastStartKeyword = startKeyword;
lastEndKeyword = endKeyword;
showStartpointSelection(startKeyword);
} else if (!endKeyword.equals(lastEndKeyword)) {
lastEndKeyword = endKeyword;
showEndpointSelection(endKeyword);
} else if (selectedStartPoi == null) {
showStartpointSelection(startKeyword);
} else {
showEndpointSelection(endKeyword);
}
}
private void showStartpointSelection(String keyword) {
selectionStage = 1;
binding.btnSwitchTarget.setText("前往选择终点");
binding.btnGoTo.setEnabled(false);
binding.btnToggleMode.setText("📍 附近");
binding.emptyView.setText("🔍 搜索起点中...");
binding.emptyView.setVisibility(View.VISIBLE);
binding.resultList.setVisibility(View.GONE);
doSearch(keyword);
}
private void showEndpointSelection(String keyword) {
selectionStage = 2;
binding.btnSwitchTarget.setText("回到选择起点");
binding.btnGoTo.setEnabled(false);
binding.btnToggleMode.setText("📍 附近");
binding.emptyView.setText("🔍 搜索终点中...");
binding.emptyView.setVisibility(View.VISIBLE);
binding.resultList.setVisibility(View.GONE);
doSearch(keyword);
}
private void doSearch(String keyword) {
if (keyword.isEmpty()) return;
nationalResults.clear();
localResults.clear();
nearbyResults.clear(); // ✅ 清除历史 nearby
isNearbyLoaded = false;
isInNearbyMode = false;
binding.btnToggleMode.setText("📍 附近");
CityManager.ParsedQuery parsed = CityManager.parse(keyword);
String searchKeyword = parsed.keyword.isEmpty() ? keyword : parsed.keyword;
String explicitCity = parsed.targetCity;
if (!explicitCity.isEmpty()) {
PoiSearch.Query query = new PoiSearch.Query(searchKeyword, "", explicitCity);
query.setPageSize(20);
try {
PoiSearch search = new PoiSearch(requireContext(), query);
search.setOnPoiSearchListener(this);
search.searchPOIAsyn();
} catch (Exception e) {
Toast.makeText(requireContext(), "搜索失败", Toast.LENGTH_SHORT).show();
}
} else {
binding.emptyView.setText("🔍 搜索中...");
binding.emptyView.setVisibility(View.VISIBLE);
binding.resultList.setVisibility(View.GONE);
PoiSearch.Query nationalQuery = new PoiSearch.Query(searchKeyword, "", "");
nationalQuery.setPageSize(20);
try {
PoiSearch nationalSearch = new PoiSearch(requireContext(), nationalQuery);
nationalSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
@Override
public void onPoiSearched(PoiResult result, int rCode) {
if (rCode == 1000 && result != null && result.getPois() != null) {
nationalResults.clear();
nationalResults.addAll(result.getPois());
}
requestLocalSearch(searchKeyword);
}
@Override
public void onPoiItemSearched(PoiItem item, int rCode) {}
});
nationalSearch.searchPOIAsyn();
} catch (Exception e) {
e.printStackTrace();
requestLocalSearch(searchKeyword);
}
}
}
private void requestLocalSearch(String keyword) {
if (currentCity.isEmpty()) {
showCombinedResults();
return;
}
PoiSearch.Query localQuery = new PoiSearch.Query(keyword, "", currentCity);
localQuery.setPageSize(20);
try {
PoiSearch localSearch = new PoiSearch(requireContext(), localQuery);
localSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
@Override
public void onPoiSearched(PoiResult result, int rCode) {
if (rCode == 1000 && result != null && result.getPois() != null) {
localResults.clear();
localResults.addAll(result.getPois());
}
showCombinedResults();
}
@Override
public void onPoiItemSearched(PoiItem item, int rCode) {}
});
localSearch.searchPOIAsyn();
} catch (Exception e) {
e.printStackTrace();
showCombinedResults();
}
}
private void showCombinedResults() {
List<PoiItem> combined = new ArrayList<>();
Set<String> seen = new HashSet<>();
adapter.clearExtraText();
for (PoiItem item : localResults) {
if (seen.add(item.getPoiId())) {
combined.add(item);
String city = getDisplayCity(item);
adapter.setExtraText(item, " | " + city);
}
}
for (PoiItem item : nationalResults) {
if (seen.add(item.getPoiId())) {
combined.add(item);
String city = getDisplayCity(item);
adapter.setExtraText(item, " | " + city);
}
}
updateResultList(combined);
}
private String getDisplayCity(PoiItem item) {
if (item == null) return "未知城市";
String city = item.getCityName();
if (city != null && !city.isEmpty() && !city.equals("[]")) {
return city;
}
String adName = item.getAdName();
if (adName != null && !adName.isEmpty() && !adName.equals("[]")) {
return adName;
}
String province = item.getProvinceName();
if (province != null && !province.isEmpty()) {
return province;
}
return "未知城市";
}
private void enterNearbyMode() {
if (!isLocationReady) {
Toast.makeText(requireContext(), "正在获取位置...", Toast.LENGTH_SHORT).show();
return;
}
String keyword = getCurrentKeyword();
CityManager.ParsedQuery parsed = CityManager.parse(keyword);
String explicitCity = parsed.targetCity;
String searchKeyword = parsed.keyword.isEmpty() ? keyword : parsed.keyword;
if (!explicitCity.isEmpty() && !isSameCity(explicitCity, currentCity)) {
nearbyResults.clear();
localResults.clear();
nationalResults.clear();
poiList.clear();
adapter.notifyDataSetChanged();
binding.emptyView.setText("📍 所选城市非当前所在城市\n无法搜索附近");
binding.emptyView.setVisibility(View.VISIBLE);
binding.resultList.setVisibility(View.GONE);
isInNearbyMode = false;
return;
}
if (!isNearbyLoaded) {
startNearbySearch(searchKeyword);
} else {
showNearbyResults();
}
isInNearbyMode = true;
binding.btnToggleMode.setText("🌐 全范围");
}
private boolean isSameCity(String city1, String city2) {
if (city1 == null || city2 == null) return false;
String c1 = city1.endsWith("市") ? city1.substring(0, city1.length() - 1) : city1;
String c2 = city2.endsWith("市") ? city2.substring(0, city2.length() - 1) : city2;
return c1.equals(c2);
}
private void exitNearbyMode() {
showCombinedResults();
isInNearbyMode = false;
binding.btnToggleMode.setText("📍 附近");
}
// ✅【重点增强】增加内部防护
private void startNearbySearch(String keyword) {
String rawKeyword = getCurrentKeyword();
CityManager.ParsedQuery parsed = CityManager.parse(rawKeyword);
String explicitCity = parsed.targetCity;
if (!explicitCity.isEmpty() && !isSameCity(explicitCity, currentCity)) {
Log.w("MapFragment", "拒绝发起跨城 nearby 搜索: " + explicitCity);
binding.emptyView.setText("📍 所选城市非当前所在城市\n无法搜索附近");
binding.emptyView.setVisibility(View.VISIBLE);
binding.resultList.setVisibility(View.GONE);
return;
}
LatLonPoint center = new LatLonPoint(myCurrentLat, myCurrentLng);
PoiSearch.Query query = new PoiSearch.Query(keyword, "", "");
query.setPageSize(20);
try {
PoiSearch nearbySearch = new PoiSearch(requireContext(), query);
nearbySearch.setBound(new PoiSearch.SearchBound(center, 3000));
nearbySearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
@Override
public void onPoiSearched(PoiResult res, int code) {
if (code == 1000 && res != null && res.getPois() != null && !res.getPois().isEmpty()) {
nearbyResults.clear();
nearbyResults.addAll(sortByDistance(res.getPois(), myCurrentLat, myCurrentLng));
isNearbyLoaded = true;
showNearbyResults();
} else {
binding.emptyView.setText("⚠️ 附近未找到地点");
binding.emptyView.setVisibility(View.VISIBLE);
binding.resultList.setVisibility(View.GONE);
}
}
@Override
public void onPoiItemSearched(PoiItem item, int rCode) {}
});
nearbySearch.searchPOIAsyn();
} catch (Exception e) {
e.printStackTrace();
binding.emptyView.setText("⚠️ 附近搜索失败");
binding.emptyView.setVisibility(View.VISIBLE);
binding.resultList.setVisibility(View.GONE);
}
}
private void showNearbyResults() {
List<PoiItem> list = new ArrayList<>(nearbyResults);
adapter.clearExtraText();
LatLng me = new LatLng(myCurrentLat, myCurrentLng);
for (PoiItem item : nearbyResults) {
double dist = AMapUtils.calculateLineDistance(toLatLng(item.getLatLonPoint()), me);
String distText = dist < 1000 ?
((int) dist) + "m" :
String.format("%.1fkm", dist / 1000);
adapter.setExtraText(item, " | " + distText);
}
updateResultList(list);
}
private void onPoiItemSelected(PoiItem item) {
LatLng latLng = new LatLng(item.getLatLonPoint().getLatitude(), item.getLatLonPoint().getLongitude());
if (selectionStage == 1) {
if (startMarker != null) startMarker.remove();
startMarker = aMap.addMarker(new MarkerOptions()
.position(latLng)
.title("起点:" + item.getTitle())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
selectedStartPoi = item;
aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14f));
updateGoToButtonState();
} else if (selectionStage == 2) {
if (endMarker != null) endMarker.remove();
endMarker = aMap.addMarker(new MarkerOptions()
.position(latLng)
.title("终点:" + item.getTitle())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
selectedEndPoi = item;
aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14f));
updateGoToButtonState();
}
userHasInteracted = true;
}
private void updateGoToButtonState() {
binding.btnGoTo.setEnabled(selectedStartPoi != null && selectedEndPoi != null);
}
@Override
public void onPoiSearched(PoiResult result, int rCode) {
String keyword = getCurrentKeyword();
CityManager.ParsedQuery parsed = CityManager.parse(keyword);
if (parsed.targetCity.isEmpty()) return;
if (rCode == 1000 && result != null && result.getPois() != null && !result.getPois().isEmpty()) {
updateResultList(result.getPois());
} else {
handleSearchError(rCode);
binding.emptyView.setText("⚠️ 未找到相关地点");
binding.emptyView.setVisibility(View.VISIBLE);
binding.resultList.setVisibility(View.GONE);
}
}
private String getCurrentKeyword() {
return selectionStage == 1 ?
binding.mapInput1.getText().toString().trim() :
binding.mapInput2.getText().toString().trim();
}
private void updateResultList(List<PoiItem> list) {
poiList.clear();
poiList.addAll(list);
adapter.notifyDataSetChanged();
binding.resultList.scrollToPosition(0);
binding.emptyView.setVisibility(list.isEmpty() ? View.VISIBLE : View.GONE);
binding.resultList.setVisibility(list.isEmpty() ? View.GONE : View.VISIBLE);
if (!list.isEmpty()) {
adapter.setSelected(0);
onPoiItemSelected(list.get(0));
}
}
@Override
public void onPoiItemSearched(PoiItem item, int rCode) {}
private LatLng toLatLng(LatLonPoint point) {
if (point == null) return null;
return new LatLng(point.getLatitude(), point.getLongitude());
}
private List<PoiItem> sortByDistance(List<PoiItem> list, double lat, double lng) {
LatLng me = new LatLng(lat, lng);
return list.stream()
.sorted((a, b) -> {
double da = AMapUtils.calculateLineDistance(toLatLng(a.getLatLonPoint()), me);
double db = AMapUtils.calculateLineDistance(toLatLng(b.getLatLonPoint()), me);
return Double.compare(da, db);
})
.collect(java.util.stream.Collectors.toList());
}
private void setupMap(Bundle savedInstanceState) {
mapView.onCreate(savedInstanceState);
aMap = mapView.getMap();
if (aMap != null) {
initMapSettings();
} else {
new Handler(Looper.getMainLooper()).post(() -> {
aMap = mapView.getMap();
if (aMap != null) {
initMapSettings();
} else {
waitAMapReady();
}
});
}
try {
geocodeSearch = new GeocodeSearch(requireContext());
geocodeSearch.setOnGeocodeSearchListener(this);
} catch (Exception e) {
e.printStackTrace();
}
}
private void waitAMapReady() {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
int retry = 0;
@Override
public void run() {
if (mapView == null) return;
aMap = mapView.getMap();
if (aMap != null) {
initMapSettings();
} else if (retry++ < 30) {
new Handler(Looper.getMainLooper()).postDelayed(this, 100);
}
}
}, 100);
}
private void initMapSettings() {
UiSettings uiSettings = aMap.getUiSettings();
uiSettings.setZoomControlsEnabled(true);
uiSettings.setCompassEnabled(true);
uiSettings.setScrollGesturesEnabled(true);
uiSettings.setMyLocationButtonEnabled(true);
new Handler(Looper.getMainLooper()).post(() ->
aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(39.909186, 116.397411), 10f))
);
enableMyLocationLayer();
}
private void enableMyLocationLayer() {
if (aMap == null) return;
if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
MyLocationStyle myLocationStyle = new MyLocationStyle();
myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
aMap.setMyLocationStyle(myLocationStyle);
aMap.setMyLocationEnabled(true);
AMap.OnMyLocationChangeListener listener = location -> {
if (location != null && !userHasInteracted) {
LatLng curLatlng = new LatLng(location.getLatitude(), location.getLongitude());
if (activeSuggestHelper != null) {
activeSuggestHelper.setLocationBias(location.getLatitude(), location.getLongitude());
}
myCurrentLat = location.getLatitude();
myCurrentLng = location.getLongitude();
isLocationReady = true;
aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(curLatlng, 16f));
userHasInteracted = true;
LatLonPoint point = new LatLonPoint(myCurrentLat, myCurrentLng);
RegeocodeQuery query = new RegeocodeQuery(point, 200, GeocodeSearch.AMAP);
try {
geocodeSearch.getFromLocationAsyn(query);
} catch (Exception e) {
e.printStackTrace();
}
aMap.setOnMyLocationChangeListener(null);
}
};
aMap.setOnMyLocationChangeListener(listener);
} else {
ActivityCompat.requestPermissions(requireActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (aMap != null) {
MyLocationStyle myLocationStyle = new MyLocationStyle();
myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
aMap.setMyLocationStyle(myLocationStyle);
aMap.setMyLocationEnabled(true);
AMap.OnMyLocationChangeListener listener = location -> {
if (location != null && !userHasInteracted) {
LatLng curLatlng = new LatLng(location.getLatitude(), location.getLongitude());
if (activeSuggestHelper != null) {
activeSuggestHelper.setLocationBias(location.getLatitude(), location.getLongitude());
}
myCurrentLat = location.getLatitude();
myCurrentLng = location.getLongitude();
isLocationReady = true;
aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(curLatlng, 16f));
userHasInteracted = true;
LatLonPoint point = new LatLonPoint(myCurrentLat, myCurrentLng);
RegeocodeQuery query = new RegeocodeQuery(point, 200, GeocodeSearch.AMAP);
try {
geocodeSearch.getFromLocationAsyn(query);
} catch (Exception e) {
e.printStackTrace();
}
aMap.setOnMyLocationChangeListener(null);
}
};
aMap.setOnMyLocationChangeListener(listener);
}
}
}
}
@Override
public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
if (result == null || result.getRegeocodeQuery() == null) return;
LatLonPoint point = result.getRegeocodeQuery().getPoint();
if (rCode == 1000 && result.getRegeocodeAddress() != null) {
String city = result.getRegeocodeAddress().getCity();
String updatedCity = (city != null && !city.isEmpty()) ? city : result.getRegeocodeAddress().getProvince();
if (Math.abs(point.getLatitude() - myCurrentLat) < 0.0001 &&
Math.abs(point.getLongitude() - myCurrentLng) < 0.0001) {
currentCity = updatedCity;
if (activeSuggestHelper != null) {
activeSuggestHelper.setCurrentCity(currentCity);
}
Log.d("MapFragment", "🎯 currentCity 已更新为: " + currentCity);
}
} else {
Log.e("MapFragment", "❌ 反编译失败: rCode=" + rCode);
}
}
@Override
public void onGeocodeSearched(com.amap.api.services.geocoder.GeocodeResult geocodeResult, int i) {}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
if (!userHasInteracted) {
enableMyLocationLayer();
}
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onDestroyView() {
super.onDestroyView();
mapView.onDestroy();
geocodeSearch = null;
binding = null;
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
private void setupSearchSuggestion() {
RealTimePoiSuggestHelper suggestHelper = new RealTimePoiSuggestHelper(requireContext());
suggestHelper.setCurrentCity(currentCity);
activeSuggestHelper = suggestHelper;
suggestHelper.setCallback(suggestions -> {
if (suggestions.length > 0) {
ArrayAdapter<String> adapter = new ArrayAdapter<>(
requireContext(),
android.R.layout.simple_dropdown_item_1line,
suggestions
);
new Handler(Looper.getMainLooper()).post(() -> {
binding.mapInput1.setAdapter(adapter);
binding.mapInput2.setAdapter(adapter);
if (requireActivity().getCurrentFocus() == binding.mapInput1) {
binding.mapInput1.showDropDown();
} else if (requireActivity().getCurrentFocus() == binding.mapInput2) {
binding.mapInput2.showDropDown();
}
});
}
});
if (isLocationReady) {
suggestHelper.setLocationBias(myCurrentLat, myCurrentLng);
}
Handler handler = new Handler(Looper.getMainLooper());
Runnable[] pending1 = {null}, pending2 = {null};
binding.mapInput1.addTextChangedListener(new SimpleTextWatcher(s -> {
if (pending1[0] != null) handler.removeCallbacks(pending1[0]);
if (s.length() == 0) {
binding.mapInput1.setAdapter(null);
return;
}
pending1[0] = () -> suggestHelper.requestSuggestions(s.toString());
handler.postDelayed(pending1[0], 300);
}));
binding.mapInput2.addTextChangedListener(new SimpleTextWatcher(s -> {
if (pending2[0] != null) handler.removeCallbacks(pending2[0]);
if (s.length() == 0) {
binding.mapInput2.setAdapter(null);
return;
}
pending2[0] = () -> suggestHelper.requestSuggestions(s.toString());
handler.postDelayed(pending2[0], 300);
}));
binding.mapInput1.setOnEditorActionListener((v, actionId, event) -> {
if ((actionId & EditorInfo.IME_MASK_ACTION) == EditorInfo.IME_ACTION_SEARCH) {
performSearch();
return true;
}
return false;
});
binding.mapInput2.setOnEditorActionListener((v, actionId, event) -> {
if ((actionId & EditorInfo.IME_MASK_ACTION) == EditorInfo.IME_ACTION_SEARCH) {
performSearch();
return true;
}
return false;
});
}
private void handleSearchError(int rCode) {
String msg;
switch (rCode) {
case 12: msg = "API Key 错误"; break;
case 27: msg = "网络连接失败"; break;
case 30: msg = "SHA1 或包名错误"; break;
case 33: msg = "请求频繁"; break;
default: msg = "搜索失败: " + rCode; break;
}
Toast.makeText(requireContext(), msg, Toast.LENGTH_SHORT).show();
}
private static class SimpleTextWatcher implements android.text.TextWatcher {
private final java.util.function.Consumer<CharSequence> onTextChanged;
public SimpleTextWatcher(java.util.function.Consumer<CharSequence> onTextChanged) {
this.onTextChanged = onTextChanged;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void afterTextChanged(Editable s) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
onTextChanged.accept(s);
}
}
}
3、SearchResultActivity代码如下:package com.example.bus;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
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.maps.model.MyLocationStyle;
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 com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class SearchResultActivity extends AppCompatActivity implements PoiSearch.OnPoiSearchListener, GeocodeSearch.OnGeocodeSearchListener {
private Button searchBtn, goToBtn, btnToggleMode;
private RecyclerView resultListView;
private List<PoiItem> poiList = new ArrayList<>();
private ResultAdapter adapter;
// 地图相关
private MapView mapView;
private AMap aMap;
private Marker selectedMarker;
// 输入提示
private GeocodeSearch geocodeSearch;
// 当前城市
private String currentCity = "";
// 是否已与地图交互
private boolean userHasInteracted = false;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1001;
// 空状态提示视图
private TextView emptyView;
// 【关键新增】保存定位得到的“我的位置”
private double myCurrentLat = 0;
private double myCurrentLng = 0;
private boolean isLocationReady = false;
// 缓存关键词
private String pendingKeyword = null;
// ✅ 实时建议助手
private RealTimePoiSuggestHelper suggestHelper;
// 🔽 新增缓存字段
private List<PoiItem> nationalResults = new ArrayList<>();
private List<PoiItem> localResults = new ArrayList<>();
private List<PoiItem> nearbyResults = new ArrayList<>();
private boolean isNearbyLoaded = false;
private boolean isInNearbyMode = false;
// ✅ 将搜索输入框提升为成员变量
private android.widget.AutoCompleteTextView searchInput;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
initViews();
setupMap(savedInstanceState);
try {
geocodeSearch = new GeocodeSearch(this);
geocodeSearch.setOnGeocodeSearchListener(this);
} catch (Exception e) {
e.printStackTrace();
}
pendingKeyword = getIntent().getStringExtra("keyword");
// 初始化 suggestHelper
suggestHelper = new RealTimePoiSuggestHelper(this);
suggestHelper.setCurrentCity(currentCity);
suggestHelper.setCallback(suggestions -> {
if (suggestions.length > 0) {
ArrayAdapter<String> adapter = new ArrayAdapter<>(
this,
android.R.layout.simple_dropdown_item_1line,
suggestions
);
new Handler(Looper.getMainLooper()).post(() -> {
searchInput.setAdapter(adapter);
if (getCurrentFocus() == searchInput) {
searchInput.showDropDown();
}
});
}
});
}
private void initViews() {
searchBtn = findViewById(R.id.search_btn);
resultListView = findViewById(R.id.result_list);
goToBtn = findViewById(R.id.btn_go_to);
btnToggleMode = findViewById(R.id.btn_toggle_mode);
emptyView = findViewById(R.id.empty_view);
searchInput = findViewById(R.id.search_input);
goToBtn.setEnabled(false);
adapter = new ResultAdapter(poiList, this::onPoiItemSelected);
resultListView.setLayoutManager(new LinearLayoutManager(this));
resultListView.setAdapter(adapter);
resultListView.setVisibility(View.GONE);
emptyView.setVisibility(View.GONE);
goToBtn.setOnClickListener(v -> {
if (selectedMarker == null) {
Toast.makeText(this, "请先选择一个位置", Toast.LENGTH_SHORT).show();
return;
}
LatLng targetPos = selectedMarker.getPosition();
if (!isLocationReady) {
Toast.makeText(this, "正在获取您的位置,请稍后再试", Toast.LENGTH_SHORT).show();
return;
}
Intent intent = new Intent(SearchResultActivity.this, RoutePlanActivity.class);
intent.putExtra("start_lat", myCurrentLat);
intent.putExtra("start_lng", myCurrentLng);
intent.putExtra("target_lat", targetPos.latitude);
intent.putExtra("target_lng", targetPos.longitude);
intent.putExtra(RoutePlanActivity.EXTRA_SOURCE, RoutePlanActivity.SOURCE_FROM_SEARCH_RESULT);
startActivity(intent);
finish();
});
btnToggleMode.setOnClickListener(v -> {
if (isInNearbyMode) {
exitNearbyMode();
} else {
enterNearbyMode();
}
});
}
private void setupMap(Bundle savedInstanceState) {
mapView = findViewById(R.id.map_view);
mapView.onCreate(savedInstanceState);
aMap = mapView.getMap();
if (aMap != null) {
initMapSettings();
} else {
new Handler(Looper.getMainLooper()).post(() -> {
aMap = mapView.getMap();
if (aMap != null) {
initMapSettings();
} else {
waitAMapReady();
}
});
}
}
private void waitAMapReady() {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
int retry = 0;
@Override
public void run() {
if (mapView == null) return;
aMap = mapView.getMap();
if (aMap != null) {
initMapSettings();
} else if (retry++ < 30) {
new Handler(Looper.getMainLooper()).postDelayed(this, 100);
}
}
}, 100);
}
private void initMapSettings() {
UiSettings uiSettings = aMap.getUiSettings();
uiSettings.setZoomControlsEnabled(true);
uiSettings.setCompassEnabled(true);
uiSettings.setScrollGesturesEnabled(true);
uiSettings.setMyLocationButtonEnabled(true);
new Handler(Looper.getMainLooper()).post(() ->
aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(35.8617, 104.1954), 4f))
);
enableMyLocationLayer();
}
private void enableMyLocationLayer() {
if (aMap == null) return;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
MyLocationStyle myLocationStyle = new MyLocationStyle();
myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
aMap.setMyLocationStyle(myLocationStyle);
aMap.setMyLocationEnabled(true);
AMap.OnMyLocationChangeListener listener = location -> {
if (location != null && !userHasInteracted) {
LatLng curLatlng = new LatLng(location.getLatitude(), location.getLongitude());
myCurrentLat = location.getLatitude();
myCurrentLng = location.getLongitude();
isLocationReady = true;
suggestHelper.setLocationBias(myCurrentLat, myCurrentLng);
aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(curLatlng, 16f), 500, null);
userHasInteracted = true;
LatLonPoint point = new LatLonPoint(myCurrentLat, myCurrentLng);
RegeocodeQuery query = new RegeocodeQuery(point, 200, GeocodeSearch.AMAP);
try {
geocodeSearch.getFromLocationAsyn(query);
} catch (Exception e) {
e.printStackTrace();
}
new Handler(Looper.getMainLooper()).postDelayed(() -> {
if (pendingKeyword != null && !pendingKeyword.isEmpty()) {
performSearchWithKeyword(pendingKeyword);
}
}, 800);
aMap.setOnMyLocationChangeListener(null);
}
};
aMap.setOnMyLocationChangeListener(listener);
} 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) {
enableMyLocationLayer();
}
}
}
private void setupSearchSuggestion() {
Handler handler = new Handler(Looper.getMainLooper());
Runnable[] pendingRunnable = {null};
searchInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (pendingRunnable[0] != null) {
handler.removeCallbacks(pendingRunnable[0]);
}
if (s.length() == 0) {
searchInput.setAdapter(null);
return;
}
pendingRunnable[0] = () -> suggestHelper.requestSuggestions(s.toString());
handler.postDelayed(pendingRunnable[0], 300);
}
@Override
public void afterTextChanged(Editable s) {}
});
searchInput.setOnEditorActionListener((v, actionId, event) -> {
if ((actionId & EditorInfo.IME_MASK_ACTION) == EditorInfo.IME_ACTION_SEARCH) {
searchBtn.performClick();
return true;
}
return false;
});
searchBtn.setOnClickListener(v -> {
String keyword = searchInput.getText().toString().trim();
if (!keyword.isEmpty()) {
performSearch(keyword);
} else {
Toast.makeText(this, "请输入关键词", Toast.LENGTH_SHORT).show();
}
});
}
private void performSearchWithKeyword(String keyword) {
searchInput.setText(keyword);
searchInput.clearFocus();
searchBtn.performClick();
}
private void performSearch(String keyword) {
if (keyword.isEmpty()) return;
// ✅【新增】重置所有状态(含 nearby)
nationalResults.clear();
localResults.clear();
nearbyResults.clear(); // 清除历史 nearby 结果
isNearbyLoaded = false;
isInNearbyMode = false;
btnToggleMode.setText("📍 附近");
emptyView.setText("🔍 搜索中...");
emptyView.setVisibility(View.VISIBLE);
resultListView.setVisibility(View.GONE);
CityManager.ParsedQuery parsed = CityManager.parse(keyword);
String searchKeyword = parsed.keyword.isEmpty() ? keyword : parsed.keyword;
String explicitCity = parsed.targetCity;
if (!explicitCity.isEmpty()) {
PoiSearch.Query query = new PoiSearch.Query(searchKeyword, "", explicitCity);
query.setPageSize(20);
try {
PoiSearch search = new PoiSearch(this, query);
search.setOnPoiSearchListener(this);
search.searchPOIAsyn();
} catch (Exception e) {
Toast.makeText(this, "搜索失败", Toast.LENGTH_SHORT).show();
}
} else {
nationalResults.clear();
localResults.clear();
PoiSearch.Query nationalQuery = new PoiSearch.Query(searchKeyword, "", "");
nationalQuery.setPageSize(20);
try {
PoiSearch nationalSearch = new PoiSearch(this, nationalQuery);
nationalSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
@Override
public void onPoiSearched(PoiResult result, int rCode) {
if (rCode == 1000 && result != null && result.getPois() != null) {
nationalResults.clear();
nationalResults.addAll(result.getPois());
}
requestLocalSearch(searchKeyword);
}
@Override
public void onPoiItemSearched(PoiItem item, int rCode) {}
});
nationalSearch.searchPOIAsyn();
} catch (Exception e) {
e.printStackTrace();
requestLocalSearch(searchKeyword);
}
}
}
private void requestLocalSearch(String keyword) {
if (currentCity.isEmpty()) {
showCombinedResults();
return;
}
PoiSearch.Query localQuery = new PoiSearch.Query(keyword, "", currentCity);
localQuery.setPageSize(20);
try {
PoiSearch localSearch = new PoiSearch(this, localQuery);
localSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
@Override
public void onPoiSearched(PoiResult result, int rCode) {
if (rCode == 1000 && result != null && result.getPois() != null) {
localResults.clear();
localResults.addAll(result.getPois());
}
showCombinedResults();
}
@Override
public void onPoiItemSearched(PoiItem item, int rCode) {}
});
localSearch.searchPOIAsyn();
} catch (Exception e) {
e.printStackTrace();
showCombinedResults();
}
}
private void showCombinedResults() {
List<PoiItem> combined = new ArrayList<>();
Set<String> seen = new HashSet<>();
adapter.clearExtraText();
for (PoiItem item : localResults) {
if (seen.add(item.getPoiId())) {
combined.add(item);
String city = getDisplayCity(item);
adapter.setExtraText(item, " | " + city);
}
}
for (PoiItem item : nationalResults) {
if (seen.add(item.getPoiId())) {
combined.add(item);
String city = getDisplayCity(item);
adapter.setExtraText(item, " | " + city);
}
}
updateResultList(combined);
}
private String getDisplayCity(PoiItem item) {
if (item == null) return "未知城市";
String city = item.getCityName();
if (city != null && !city.isEmpty() && !city.equals("[]")) {
return city;
}
String adName = item.getAdName();
if (adName != null && !adName.isEmpty() && !adName.equals("[]")) {
return adName;
}
String province = item.getProvinceName();
if (province != null && !province.isEmpty()) {
return province;
}
return "未知城市";
}
private void enterNearbyMode() {
if (!isLocationReady) {
Toast.makeText(this, "正在获取位置...", Toast.LENGTH_SHORT).show();
return;
}
String keyword = searchInput.getText().toString().trim();
CityManager.ParsedQuery parsed = CityManager.parse(keyword);
String explicitCity = parsed.targetCity;
String searchKeyword = parsed.keyword.isEmpty() ? keyword : parsed.keyword;
// 🔴【关键】如果指定城市非当前城市,则禁止 nearby
if (!explicitCity.isEmpty() && !isSameCity(explicitCity, currentCity)) {
nearbyResults.clear();
localResults.clear();
nationalResults.clear();
poiList.clear();
adapter.notifyDataSetChanged();
emptyView.setText("📍 所选城市非当前所在城市\n无法搜索附近");
emptyView.setVisibility(View.VISIBLE);
resultListView.setVisibility(View.GONE);
isInNearbyMode = false;
return;
}
// 只有同城才允许加载 nearby
if (!isNearbyLoaded) {
startNearbySearch(searchKeyword);
} else {
showNearbyResults();
}
isInNearbyMode = true;
btnToggleMode.setText("🌐 全范围");
}
private boolean isSameCity(String city1, String city2) {
if (city1 == null || city2 == null) return false;
String c1 = city1.endsWith("市") ? city1.substring(0, city1.length() - 1) : city1;
String c2 = city2.endsWith("市") ? city2.substring(0, city2.length() - 1) : city2;
return c1.equals(c2);
}
private void exitNearbyMode() {
showCombinedResults();
isInNearbyMode = false;
btnToggleMode.setText("📍 附近");
}
// ✅【重点增强】增加内部防护
private void startNearbySearch(String keyword) {
String rawKeyword = searchInput.getText().toString().trim();
CityManager.ParsedQuery parsed = CityManager.parse(rawKeyword);
String explicitCity = parsed.targetCity;
// 🔒 再次检查是否跨城(防御性编程)
if (!explicitCity.isEmpty() && !isSameCity(explicitCity, currentCity)) {
Log.w("SearchResult", "拒绝发起跨城 nearby 搜索: " + explicitCity);
emptyView.setText("📍 所选城市非当前所在城市\n无法搜索附近");
emptyView.setVisibility(View.VISIBLE);
resultListView.setVisibility(View.GONE);
return;
}
LatLonPoint center = new LatLonPoint(myCurrentLat, myCurrentLng);
PoiSearch.Query query = new PoiSearch.Query(keyword, "", "");
query.setPageSize(20);
try {
PoiSearch nearbySearch = new PoiSearch(this, query);
nearbySearch.setBound(new PoiSearch.SearchBound(center, 3000));
nearbySearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
@Override
public void onPoiSearched(PoiResult res, int code) {
if (code == 1000 && res != null && res.getPois() != null && !res.getPois().isEmpty()) {
nearbyResults.clear();
nearbyResults.addAll(sortByDistance(res.getPois(), myCurrentLat, myCurrentLng));
isNearbyLoaded = true;
showNearbyResults();
} else {
emptyView.setText("⚠️ 附近未找到地点");
emptyView.setVisibility(View.VISIBLE);
resultListView.setVisibility(View.GONE);
}
}
@Override
public void onPoiItemSearched(PoiItem item, int rCode) {}
});
nearbySearch.searchPOIAsyn();
} catch (Exception e) {
e.printStackTrace();
emptyView.setText("⚠️ 附近搜索失败");
emptyView.setVisibility(View.VISIBLE);
resultListView.setVisibility(View.GONE);
}
}
private void showNearbyResults() {
List<PoiItem> list = new ArrayList<>(nearbyResults);
adapter.clearExtraText();
LatLng me = new LatLng(myCurrentLat, myCurrentLng);
for (PoiItem item : nearbyResults) {
double dist = com.amap.api.maps.AMapUtils.calculateLineDistance(toLatLng(item.getLatLonPoint()), me);
String distText = dist < 1000 ?
((int) dist) + "m" :
String.format("%.1fkm", dist / 1000);
adapter.setExtraText(item, " | " + distText);
}
updateResultList(list);
}
private void onPoiItemSelected(PoiItem item) {
LatLng latLng = new LatLng(item.getLatLonPoint().getLatitude(), item.getLatLonPoint().getLongitude());
if (selectedMarker != null) {
selectedMarker.remove();
selectedMarker = null;
}
selectedMarker = aMap.addMarker(new MarkerOptions()
.position(latLng)
.title("终点:" + item.getTitle())
.icon(com.amap.api.maps.model.BitmapDescriptorFactory.defaultMarker(
com.amap.api.maps.model.BitmapDescriptorFactory.HUE_RED)));
aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14f));
goToBtn.setEnabled(true);
}
private LatLng toLatLng(LatLonPoint point) {
if (point == null) return null;
return new LatLng(point.getLatitude(), point.getLongitude());
}
private List<PoiItem> sortByDistance(List<PoiItem> list, double lat, double lng) {
LatLng me = new LatLng(lat, lng);
return list.stream()
.sorted((a, b) -> {
double da = com.amap.api.maps.AMapUtils.calculateLineDistance(toLatLng(a.getLatLonPoint()), me);
double db = com.amap.api.maps.AMapUtils.calculateLineDistance(toLatLng(b.getLatLonPoint()), me);
return Double.compare(da, db);
})
.collect(java.util.stream.Collectors.toList());
}
@Override
public void onPoiSearched(PoiResult result, int rCode) {
String keyword = searchInput.getText().toString().trim();
CityManager.ParsedQuery parsed = CityManager.parse(keyword);
if (parsed.targetCity.isEmpty()) return;
if (rCode == 1000 && result != null && result.getPois() != null && !result.getPois().isEmpty()) {
updateResultList(result.getPois());
} else {
emptyView.setText("⚠️ 未找到相关地点");
emptyView.setVisibility(View.VISIBLE);
resultListView.setVisibility(View.GONE);
}
}
private void updateResultList(List<PoiItem> list) {
poiList.clear();
poiList.addAll(list);
adapter.notifyDataSetChanged();
resultListView.scrollToPosition(0);
emptyView.setVisibility(list.isEmpty() ? View.VISIBLE : View.GONE);
resultListView.setVisibility(list.isEmpty() ? View.GONE : View.VISIBLE);
if (!list.isEmpty()) {
adapter.setSelected(0);
onPoiItemSelected(list.get(0));
}
}
@Override
public void onPoiItemSearched(PoiItem item, int rCode) {}
@Override
public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
if (result == null || result.getRegeocodeQuery() == null) return;
LatLonPoint point = result.getRegeocodeQuery().getPoint();
if (rCode == 1000 && result.getRegeocodeAddress() != null) {
String city = result.getRegeocodeAddress().getCity();
String updatedCity = (city != null && !city.isEmpty()) ? city : result.getRegeocodeAddress().getProvince();
if (Math.abs(point.getLatitude() - myCurrentLat) < 0.0001 &&
Math.abs(point.getLongitude() - myCurrentLng) < 0.0001) {
currentCity = updatedCity;
if (suggestHelper != null) {
suggestHelper.setCurrentCity(currentCity);
}
Log.d("SearchResultActivity", "🎯 currentCity 已更新为: " + currentCity);
}
} else {
Log.e("SearchResultActivity", "❌ 反编译失败: rCode=" + rCode);
}
}
@Override
public void onGeocodeSearched(com.amap.api.services.geocoder.GeocodeResult geocodeResult, int i) {}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
setupSearchSuggestion();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
geocodeSearch = null;
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
请你按照我的要求对我的代码进行最小量的修改,为我提供修改好的完整代码,所有文件都从import开始提供
最新发布