一共有两个Activity ,第一个Activity显示地图,实现定位当前地址并输出在第一个页面的EditText里,第二个Activity是搜索页面,搜索框是EditText,ListView显示搜索结果,使用百度地图建议搜索功能。比如搜索一个万达广场,点击搜索结果后希望在第一个Activity的地图上显示当前定位地址和到万达广场的路线规划,就是起点和终点显示出来。
(这里需要起点自动获取,因为地图已经实现自动定位当前地址了,不要那种既要输入起点,又要输入终点,最后还得要点击一下确定,才会显示结果的那种无语的操作体验,整个软件是没有一个Bundle按钮的,只需要item)
现在的问题是点击第二个页面ListView里面的搜索结果万达广场,跳转到第一个页面之后没有任何反应。
谢谢各位大神哥哥姐姐~
第一个java,
package com.baidumap;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
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();
}
}
第二个java,
package com.baidumap;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.CityInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
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();
}
}