android 百度地图 搜索跳转

一共有两个Activity ,第一个Activity显示地图,实现定位当前地址并输出在第一个页面的EditText里,第二个Activity是搜索页面,搜索框是EditText,ListView显示搜索结果,使用百度地图建议搜索功能。比如搜索一个万达广场,点击搜索结果后希望在第一个Activity的地图上显示当前定位地址和到万达广场的路线规划,就是起点和终点显示出来。
(这里需要起点自动获取,因为地图已经实现自动定位当前地址了,不要那种既要输入起点,又要输入终点,最后还得要点击一下确定,才会显示结果的那种无语的操作体验,整个软件是没有一个Bundle按钮的,只需要item)
现在的问题是点击第二个页面ListView里面的搜索结果万达广场,跳转到第一个页面之后没有任何反应。
谢谢各位大神哥哥姐姐~请帮我实现Intent ,使用的是startactivityforresult,数据传送和接收,在接收后的onActivityResult里面进行处理
第一个页面
public class MainActivity extends Activity {

private MapView mMapView = null;
private BaiduMap mBaidumap =null;
private PoiSearch mPoiSearch = null;
private EditText mTv = null;

private 

LocationClient mLocClient;
private MainActivity.MyLocationListener myListener = new MainActivity.MyLocationListener();
private int mCurrentDirection = 0;
private Double lastX = 0.0;
private MyLocationData locData;
private float mCurrentAccracy;
private double mCurrentLat = 0.0;
private double mCurrentLon = 0.0;
private String mCityName;
boolean isFirstLoc = true;
BitmapDescriptor mCurrentMarker;
private SensorManager mSensorManager;
private MyLocationConfiguration.LocationMode mCurrentMode;
private MainActivity.DirectionSensorListener DirectionListener = new MainActivity.DirectionSensorListener();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SDKInitializer.initialize(getApplicationContext());
    setContentView(R.layout.content_main);
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务
    mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
    //初始化地图
    mMapView = (MapView) findViewById(R.id.mapView);
    mTv = (EditText) findViewById(R.id.tiaozhuan);
    mTv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Bundle bundle = new Bundle();
            bundle.putString("userName", "zhangsan");
            bundle.putInt("userAge", 100);
            Intent intent = new Intent(MainActivity.this, Main2Activity.class);
            intent.putExtras(bundle);
            startActivityForResult(intent, 1);//
        }
    });

/*protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    switch (requestCode){
        case RESULT_OK:
            Bundle bundle=data.getExtras();
            String str=bundle.getString("backData");
            Toast.makeText(MainActivity.this, str,Toast.LENGTH_LONG).show();
            break;

        default:
            break;
    }*/
    mBaidumap = mMapView.getMap();
    mMapView.showScaleControl(false);
    mMapView.showZoomControls(false);
    UiSettings settings = mBaidumap.getUiSettings();
    settings.setOverlookingGesturesEnabled(false);//设置双指下拉时不启用3D地图
    settings.setRotateGesturesEnabled(false);//设置地图不可旋转
    //开启定位图层
    mBaidumap.setMyLocationEnabled(true);
    initLocation();
    //initPoiSearch();

    mPoiSearch = PoiSearch.newInstance();
    mPoiSearch.setOnGetPoiSearchResultListener(new OnGetPoiSearchResultListener() {
@Override
public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
    if (poiDetailResult == null
        || poiDetailResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
        Toast.makeText(MainActivity.this, "未找到结果", Toast.LENGTH_LONG)
        .show();
        return;
    }
    if (poiDetailResult.error == SearchResult.ERRORNO.NO_ERROR) {
    //搜索到POI
    mBaidumap.clear();
    mBaidumap.addOverlay(new MarkerOptions()
        .position(poiDetailResult.location)
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.alf))
        .title(poiDetailResult.getAddress()));
    //讲该POI设置为地图中心
    mBaidumap.setMapStatus(MapStatusUpdateFactory.newLatLng(poiDetailResult.location));
    Toast.makeText(MainActivity.this, "搜索中...", Toast.LENGTH_LONG).show();
        return;
    }
}
@Override
public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

}
@Override
public void onGetPoiResult(PoiResult poiResult) {

        }
    });
}

private void initLocation() {
    mLocClient = new LocationClient(this);
    mLocClient.registerLocationListener(myListener);
    LocationClientOption option = new LocationClientOption();
    option.setOpenGps(true);//打开GPS
    option.setCoorType("bd09ll");//设置坐标类型
    option.setIsNeedAddress(true);//是否需要地址信息
    option.setScanSpan(1000);
    LocationPermission();
    mLocClient.setLocOption(option);
}

private void LocationPermission() {
    int checkPermission = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION);
    if (checkPermission != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
        Log.d("未获得定位权限", "弹出提示");
        return;
    }
}

public class DirectionSensorListener implements SensorEventListener {

    @Override
    public void onSensorChanged(SensorEvent event) {
        double x = event.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            mCurrentDirection = (int) x;
            //设置定位数据
            locData = new MyLocationData.Builder()
                    .accuracy(mCurrentAccracy)//精度
                    .direction(mCurrentDirection) //此处设置开发者获取到的方向信息,顺时针0-360
                    .latitude(mCurrentLat)//经度
                    .longitude(mCurrentLon)//纬度
                    .build();
            mBaidumap.setMyLocationData(locData);
        }
        lastX = x;
    }
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
}
public class MyLocationListener implements BDLocationListener {

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        //map view销毁后不在处理新接受的位置
        if (bdLocation == null || mMapView == null) {
            return;
        }
        mCurrentLat = bdLocation.getLatitude();
        mCurrentLon = bdLocation.getLongitude();
        mCurrentAccracy = bdLocation.getRadius();
        mCityName = bdLocation.getCity();
        //设置定位数据
        locData = new MyLocationData.Builder()
                .accuracy(bdLocation.getRadius())//精度
                .direction(mCurrentDirection) //此处设置开发者获取到的方向信息,顺时针0-360
                .latitude(bdLocation.getLatitude())//经度
                .longitude(bdLocation.getLongitude())//纬度
                .build();
        mBaidumap.setMyLocationData(locData);
        //第一次定位时,将地图位置移动到当前位置
        if (isFirstLoc) {
            isFirstLoc = false;
            LatLng ll = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(ll).zoom(18.0f);
            mBaidumap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            mCurrentMarker = null;
            mBaidumap
                    .setMyLocationConfiguration(new MyLocationConfiguration(
                            mCurrentMode, true, null));
        }
    }
}
@Override
protected void onStart() {
    //为系统的方向传感器注册监听器
    mSensorManager.registerListener(DirectionListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION)
            , SensorManager.SENSOR_DELAY_UI);
    //启动监听
    mLocClient.start();
    super.onStart();
}

@Override
protected void onPause() {
    mMapView.onPause();
    super.onPause();
}

@Override
protected void onResume() {
    mMapView.onResume();
    super.onResume();
}

@Override
protected void onStop() {
    //取消传感器监听
    mSensorManager.unregisterListener(DirectionListener);
    super.onStop();
}

@Override
protected void onDestroy() {
    //退出时销毁定位
    mLocClient.stop();
    //关闭定位图层
    mBaidumap.setMyLocationEnabled(false);
    mMapView.onDestroy();
    //mMapView = null;
   // mPoiSearch.destroy();
    //mSuggestionSearch.destroy();
    super.onDestroy();
}

}
第二个页面
public class Main2Activity extends Activity implements OnGetSuggestionResultListener {

private EditText et_address;
private Adapter_list_Address adapter_list_Address;
private ListView myListView;
private List<String> list = new ArrayList<>();
private List<String> lists = new ArrayList<>();


//地图相关
/**
 * 百度地图控件
 */
MapView mMapView = null;
/**
 * 百度地图实例
 */
BaiduMap mBaidumap = null;


//定位相关
/**
 * 定位客户端
 */
LocationClient mLocClient;
/**
 * 定位模式
 */
private LocationMode mCurrentMode;
/**
 * 定位图标
 */
BitmapDescriptor mCurrentMarker;
/**
 * 传感器管理器
 */
private SensorManager mSensorManager;
/**
 * 当前方向
 */
private int mCurrentDirection = 0;
/**
 * 当前经度
 */
private double mCurrentLat = 0.0;
/**
 * 当前纬度
 */
private double mCurrentLon = 0.0;
/**
 * 当前经度
 */
private float mCurrentAccracy;
/**
 * 是否首次定位
 */
boolean isFirstLoc = true;
/**
 * 定位数据
 */
private MyLocationData locData;
/**
 * 定位监听
 */
private MyLocationListener myListener = new MyLocationListener();
/**
 * 方向监听
 */
private DirectionSensorListener DirectionListener = new DirectionSensorListener();
/**
 * 上一次的方向
 */
private Double lastX = 0.0;
/**
 * 定位所在城市
 */
private String mCityName;
//poi搜索相关
/**
 * Poi检索实例
 */
private PoiSearch mPoiSearch = null;
private SuggestionSearch mSuggestionSearch = null;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SDKInitializer.initialize(getApplicationContext());
    setContentView(R.layout.activity_main2);
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务
    mCurrentMode = LocationMode.NORMAL;
    //初始化地图
    mMapView = (MapView) findViewById(R.id.mapView2);
    mBaidumap = mMapView.getMap();
    mMapView.showScaleControl(false);
    mMapView.showZoomControls(false);
    UiSettings settings = mBaidumap.getUiSettings();
    settings.setOverlookingGesturesEnabled(false);//设置双指下拉时不启用3D地图
    settings.setRotateGesturesEnabled(false);//设置地图不可旋转
    //开启定位图层
    mBaidumap.setMyLocationEnabled(true);
    initLocation();
    initPoiSearch();
    initData();

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        public void run() {
            ShowKeyboard(et_address);
        }
    }, 500);
}

private void initData() {
    et_address = (EditText) findViewById(R.id.et_address);
    myListView = (ListView) findViewById(R.id.lv_address);
    mPoiSearch = PoiSearch.newInstance();
    mPoiSearch.setOnGetPoiSearchResultListener(new OnGetPoiSearchResultListener() {
@Override
public void onGetPoiResult(PoiResult poiResult) {
    if (poiResult == null || poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
    Toast.makeText(Main2Activity.this, "未找到结果", Toast.LENGTH_LONG).show();
    return;
}
    if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {

}
    if (poiResult.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {
    //当输入关键字在本市没有找到,但是在其他城市找到时,返回包含该关键字信息的城市列表
    String strInfo = "在";
    for (CityInfo cityInfo : poiResult.getSuggestCityList()) {
            strInfo += cityInfo.city;
            strInfo += ",";
        }
            strInfo += "找到结果";
            Toast.makeText(Main2Activity.this, strInfo, Toast.LENGTH_LONG).show();
        }
    }

@Override
public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
    if (poiDetailResult == null
        || poiDetailResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
        Toast.makeText(Main2Activity.this, "未找到结果", Toast.LENGTH_LONG)
            .show();
            return;
        }
    if (poiDetailResult.error == SearchResult.ERRORNO.NO_ERROR) {
    //搜索到POI
    mBaidumap.clear();
    mBaidumap.addOverlay(new MarkerOptions()
            .position(poiDetailResult.location)
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.alf))
            .title(poiDetailResult.getAddress()));
        //讲该POI设置为地图中心
        mBaidumap.setMapStatus(MapStatusUpdateFactory.newLatLng(poiDetailResult.location));
        Toast.makeText(Main2Activity.this, "搜索中...", Toast.LENGTH_LONG).show();
            return;
        }
    }
@Override
public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }
});

    //初始化建议搜索模块,注册建议搜索事件监听
    mSuggestionSearch = SuggestionSearch.newInstance();
    mSuggestionSearch.setOnGetSuggestionResultListener(this);
    et_address.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable arg0) {
    if (adapter_list_Address != null) {
        adapter_list_Address.notifyDataSetChanged();
    }
    mSuggestionSearch
        .requestSuggestion((new SuggestionSearchOption())
        .keyword(et_address.getText().toString()).city("北京"));
    }
@Override
public void beforeTextChanged(CharSequence arg0, int arg1,
                              int arg2, int arg3) {
    if (adapter_list_Address != null) {
        adapter_list_Address.notifyDataSetChanged();
    }
    mSuggestionSearch
        .requestSuggestion((new SuggestionSearchOption())
        .keyword(et_address.getText().toString()).city("北京"));
    }
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
                          int arg3) {
    if (cs.length() < 0) {
        return;
    }
/**
* 使用建议搜索服务获取建议列表,结果在onSuggestionResult()中更新
*/
if (adapter_list_Address != null) {
          adapter_list_Address.notifyDataSetChanged();
}
    mSuggestionSearch
    .requestSuggestion((new SuggestionSearchOption())
    .keyword(et_address.getText().toString()).city("北京"));
}
});

}

@Override
public void onGetSuggestionResult(final SuggestionResult msg) {
    // TODO Auto-generated method stub
    if (msg == null || msg.getAllSuggestions() == null) {
        Toast.makeText(Main2Activity.this, "未检索到当前地址", Toast.LENGTH_SHORT).show();
        return;
    }

    if (list != null) {
        list.clear();
    }
    if (lists != null) {
        lists.clear();
    }

    for (SuggestionResult.SuggestionInfo info : msg.getAllSuggestions()) {
        Log.e("info.ccity", "info.city" + info.city + "info.district" + info.district + "info.key" + info.key);
        list.add(info.key);
        lists.add(info.city + info.district + info.key);
        adapter_list_Address = new Adapter_list_Address(Main2Activity.this, list, lists);
        myListView.setAdapter(adapter_list_Address);
        myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                SuggestionResult.SuggestionInfo info = msg.getAllSuggestions().get(position);
                mPoiSearch.searchPoiDetail(new PoiDetailSearchOption().poiUid(info.uid));

                Intent intentAddress = new Intent();
                intentAddress.putExtra("backData",et_address.getText().toString());
                setResult(RESULT_OK,intentAddress);
                finish();
            }
        });
        adapter_list_Address.notifyDataSetChanged();
    }
}

public static void ShowKeyboard(View v) {
    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(v, InputMethodManager.SHOW_FORCED);
}

public static void HideKeyboard(View v) {
    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm.isActive()) {
        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
    }
}

/**
 * 初始化定位相关
 */
private void initLocation() {
    mLocClient = new LocationClient(this);
    mLocClient.registerLocationListener(myListener);
    LocationClientOption option = new LocationClientOption();
    option.setOpenGps(true);//打开GPS
    option.setCoorType("bd09ll");//设置坐标类型
    option.setIsNeedAddress(true);//是否需要地址信息
    option.setScanSpan(1000);
    LocationPermission();
    mLocClient.setLocOption(option);
}

/**
 * poi搜索相关
 */
private void initPoiSearch() {
    //初始化搜索模块,注册搜索事件监听
    mPoiSearch = PoiSearch.newInstance();
    //mPoiSearch.setOnGetPoiSearchResultListener(this);
}

/**
 * 获取GPS定位权限(Android6.0 以上需要动态获取权限)
 */
private void LocationPermission() {
    int checkPermission = ContextCompat.checkSelfPermission(Main2Activity.this, Manifest.permission.ACCESS_COARSE_LOCATION);
    if (checkPermission != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(Main2Activity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
        Log.d("未获得定位权限", "弹出提示");
        return;
    }
}

/**
 * 方向监听
 */
public class DirectionSensorListener implements SensorEventListener {

    @Override
    public void onSensorChanged(SensorEvent event) {
        double x = event.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            mCurrentDirection = (int) x;
            //设置定位数据
            locData = new MyLocationData.Builder()
                    .accuracy(mCurrentAccracy)//精度
                    .direction(mCurrentDirection) //此处设置开发者获取到的方向信息,顺时针0-360
                    .latitude(mCurrentLat)//经度
                    .longitude(mCurrentLon)//纬度
                    .build();
            mBaidumap.setMyLocationData(locData);
        }
        lastX = x;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
}

/**
 * 定位监听
 */
public class MyLocationListener implements BDLocationListener {

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        //map view销毁后不在处理新接受的位置
        if (bdLocation == null || mMapView == null) {
            return;
        }
        mCurrentLat = bdLocation.getLatitude();
        mCurrentLon = bdLocation.getLongitude();
        mCurrentAccracy = bdLocation.getRadius();
        mCityName = bdLocation.getCity();
        //设置定位数据
        locData = new MyLocationData.Builder()
                .accuracy(bdLocation.getRadius())//精度
                .direction(mCurrentDirection) //此处设置开发者获取到的方向信息,顺时针0-360
                .latitude(bdLocation.getLatitude())//经度
                .longitude(bdLocation.getLongitude())//纬度
                .build();
        mBaidumap.setMyLocationData(locData);
        //第一次定位时,将地图位置移动到当前位置
        if (isFirstLoc) {
            isFirstLoc = false;
            LatLng ll = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(ll).zoom(18.0f);
            mBaidumap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            mCurrentMarker = null;
            mBaidumap
                    .setMyLocationConfiguration(new MyLocationConfiguration(
                            mCurrentMode, true, null));
        }
    }
}

@Override
protected void onStart() {
    //为系统的方向传感器注册监听器
    mSensorManager.registerListener(DirectionListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION)
            , SensorManager.SENSOR_DELAY_UI);
    //启动监听
    mLocClient.start();
    super.onStart();
}

@Override
protected void onPause() {
    mMapView.onPause();
    super.onPause();
}

@Override
protected void onResume() {
    mMapView.onResume();
    super.onResume();
}

@Override
protected void onStop() {
    //取消传感器监听
    mSensorManager.unregisterListener(DirectionListener);
    super.onStop();
}

@Override
protected void onDestroy() {
    //退出时销毁定位
    mLocClient.stop();
    //关闭定位图层
    mBaidumap.setMyLocationEnabled(false);
    mMapView.onDestroy();
    mMapView = null;
    mPoiSearch.destroy();
    mSuggestionSearch.destroy();
    super.onDestroy();
}

}

2个回答

你看上个提问里面我的回答了吗,又开一个一样的。。

qq_41202319
qq_41202319 回复一条特立独行的咸鱼: 大哥帮帮忙,我加你QQ,你教我简单的改一下 能在第一个页面显示搜索结果就行。。
接近 3 年之前 回复
qdlgjsj345
一条特立独行的咸鱼 回复qq_41202319: 之能用手机qq,太麻烦了
接近 3 年之前 回复
qq_41202319
qq_41202319 我的Intent代码不会写,不知道怎么传送和接收,还有接收后的处理。。。
接近 3 年之前 回复
qq_41202319
qq_41202319 看到了,哥哥,按照你的要求改了,但是我实在太菜了,还望帮帮忙呀,可以加你QQ吗?这20C币送给哥哥,帮我解决一下这个问题吧~
接近 3 年之前 回复

把onActivityResult里面swtich(requestCode)中的requestCode改成resultCode就可以了,
requestCode是你startActivityForResult发过的请求码,不是返回过来的结果码,
你这里requestCode写的1,返回过来的resultCode是result_ok(-1),所以会没跑那段代码

 Intent intentAddress = new Intent();
 intentAddress.putExtra("backData",et_address.getText().toString());
 setResult(RESULT_OK,intentAddress);
 finish();

传值应该没问题

qq_41202319
qq_41202319 回复一条特立独行的咸鱼: 好的
接近 3 年之前 回复
qdlgjsj345
一条特立独行的咸鱼 回复qq_41202319: 你发站内私信吧,你代码贴太多了,刷新之后还要往下翻半天
接近 3 年之前 回复
qq_41202319
qq_41202319 回复一条特立独行的咸鱼: 现在只要把onActivityResult这段代码放出来再运行就闪退了,把它隐了就正常。。。但是地图不显示搜索结果
接近 3 年之前 回复
qdlgjsj345
一条特立独行的咸鱼 回复qq_41202319: 应该可以正确传值过去吧
接近 3 年之前 回复
qq_41202319
qq_41202319 startActivityForResult(intent, (-1));这样写对吗?
接近 3 年之前 回复
qq_41202319
qq_41202319 上面这个有问题吗?
接近 3 年之前 回复
qq_41202319
qq_41202319 public void onClick(View view) { Bundle bundle = new Bundle(); bundle.putString("userName", "zhangsan"); bundle.putInt("userAge", 100); Intent intent = new Intent(MainActivity.this, Main2Activity.class); intent.putExtras(bundle); startActivityForResult(intent, 1);// }
接近 3 年之前 回复
qq_41202319
qq_41202319 回复qq_41202319: case RESULT_OK: Bundle bundle=data.getExtras(); String str=bundle.getString("backData"); Toast.makeText(MainActivity.this, str,Toast.LENGTH_LONG).show(); break;
接近 3 年之前 回复
qq_41202319
qq_41202319 result_ok(-1)这个要写到哪里呀。。swtich(requestCode)中的requestCode改成resultCode后运行还是闪退。。
接近 3 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问