仿Uber滑动选择地图

来源:互联网 发布:近视眼手术知乎 编辑:程序博客网 时间:2024/06/05 06:18

//布局:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:fitsSystemWindows="true"    android:orientation="vertical" >    <include layout="@layout/three_widget_titlelayout" />    <FrameLayout        android:layout_width="match_parent"        android:layout_height="0dip"        android:layout_weight="1" >        <com.baidu.mapapi.map.MapView            android:id="@+id/bmapView"            android:layout_width="match_parent"            android:layout_height="fill_parent"            android:clickable="true" />        <ImageView            android:layout_width="40dip"            android:layout_height="40dip"            android:layout_gravity="center"            android:scaleType="centerCrop"            android:src="@drawable/icon_gcoding" />        <TextView            android:id="@+id/addressview"            android:layout_width="match_parent"            android:layout_height="50dip"            android:layout_gravity="bottom"            android:background="#e0000000"            android:alpha="0.4"            android:paddingRight="10dip"            android:paddingLeft="10dip"            android:gravity="center_vertical"            android:textColor="#ffffff"            android:textSize="16sp" />    </FrameLayout></LinearLayout>

//核心代码

/** * 百度地图 * @author 肖建斌 * */public class MapActivity extends BaseActivity implements OnGetGeoCoderResultListener{private final static String TAG = MapActivity.class.getName();@ViewInject(id = R.id.actionbar_home,click = "backClick")ImageView backImageView;@ViewInject(id = R.id.actionbar_title)TextView titleView;@ViewInject(id = R.id.actionbar_action,click = "sureClick")TextView sureView;@ViewInject(id = R.id.addressview)TextView addressView;MapView mMapView = null;BaiduMap mBaiduMap;GeoCoder mSearch = null; // 搜索模块,也可去掉地图模块独立使用// 定位相关public MyLocationListenner myListener = new MyLocationListenner();LocationClient mLocClient;private LocationMode mCurrentMode;BitmapDescriptor mCurrentMarker;boolean isFirstLoc = true;// 是否首次定位boolean isFistStuatus = true;//状态private String curentAddress = null;private String moveAddress = null;//纬度,经度private double mlat;private double mlong;//坐标private double x;private double y;//mBaiduMap.setOnMarkerClickListener marker的点击事件@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_mapview);FinalActivity.initInjectedView(this);init();}private void init(){titleView.setText("百度地图");sureView.setText("确定");mMapView = (MapView) findViewById(R.id.bmapView);mMapView.showZoomControls(false);// 隐藏放大缩小控件mMapView.setEnabled(true);mBaiduMap = mMapView.getMap();mBaiduMap.setOnMapStatusChangeListener(onMapStatusChangeListener);mSearch = GeoCoder.newInstance();mSearch.setOnGetGeoCodeResultListener(this);mCurrentMode = LocationMode.NORMAL;//mCurrentMarker = BitmapDescriptorFactory//.fromResource(R.drawable.current_addres_point_icon);mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(mCurrentMode,true, null));// 开启定位图层mBaiduMap.setMyLocationEnabled(true);// 定位初始化mLocClient = new LocationClient(this);mLocClient.registerLocationListener(myListener);LocationClientOption option = new LocationClientOption();option.setOpenGps(true);// 打开gpsoption.setCoorType("bd09ll"); // 设置坐标类型option.setScanSpan(1000);mLocClient.setLocOption(option);mLocClient.start();}OnMapStatusChangeListener onMapStatusChangeListener = new OnMapStatusChangeListener() {@Overridepublic void onMapStatusChangeStart(MapStatus arg0) {}//状态结束@Overridepublic void onMapStatusChangeFinish(MapStatus arg0) {//获取百度地图的中心点LatLng latLng = arg0.target;double longitude = latLng.longitude;//经度double latitude = latLng.latitude;//维度LatLng ptCenter = new LatLng(latitude, longitude);mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(ptCenter));}@Overridepublic void onMapStatusChange(MapStatus arg0) {}};//确定public void sureClick(View view){baidu2Gps(mlong+"", mlat+"");}//结束Activitypublic void backClick(View view){finish();}@Overridepublic void onGetGeoCodeResult(GeoCodeResult arg0) {}//编码转成实际地址@Overridepublic void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {showToast("亲,没找到该地址");return;}mBaiduMap.setMyLocationConfigeration(null);mBaiduMap.clear();//mBaiduMap.addOverlay(new MarkerOptions().position(result.getLocation())//.icon(BitmapDescriptorFactory//.fromResource(R.drawable.current_addres_point_icon)));//mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(result//.getLocation()));LatLng latLng = result.getLocation();mlat = latLng.latitude;//纬度mlong = latLng.longitude;//经度if (!TextUtils.isEmpty(result.getAddress())) {//Toast.makeText(MapActivity.this, result.getAddress(),100).show();moveAddress = result.getAddress();addressView.setText("地址:"+moveAddress);}else {addressView.setText("地址:没有找到该地方名称");}}Marker marker = null;/** * 定位SDK监听函数 */public class MyLocationListenner implements BDLocationListener {@Overridepublic void onReceiveLocation(BDLocation location) {// map view 销毁后不在处理新接收的位置if (location == null || mMapView == null)return;MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())// 此处设置开发者获取到的方向信息,顺时针0-360.direction(0).latitude(location.getLatitude()).longitude(location.getLongitude()).build();mBaiduMap.setMyLocationData(locData);if (isFirstLoc) {isFirstLoc = false;LatLng ll = new LatLng(location.getLatitude(),location.getLongitude());mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(ll));//新加//BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.current_addres_point_icon);//准备 marker option 添加 marker 使用//MarkerOptions markerOptions = new MarkerOptions().icon(bitmap).position(ll);//获取添加的 marker ,可以触发点击事件获取位置//marker = (Marker) mBaiduMap.addOverlay(markerOptions);MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);mBaiduMap.animateMapStatus(u);}}public void onReceivePoi(BDLocation poiLocation) {}}/** * 步骤1: * @param bx * @param by */public void baidu2Gps(final String bx,final String by){showDialog("请稍后...");//http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x=116.397428&y=39.90923&callback=BMap.Convertor.cbk_7594 //参考传参数方法String url = "http://api.map.baidu.com/ag/coord/convert";//固定不变AjaxParams params = new AjaxParams();params.put("from", "0");params.put("to", "4");params.put("x", bx);params.put("y", by);Callback callback = new Callback(tag,this) {@Overridepublic void onSuccess(String t) {try {JsonParser parser = new JsonParser();    JsonObject root = parser.parse(t).getAsJsonObject();    String base64x = root.get("x").getAsString();    String base64y = root.get("y").getAsString();            double x1 = Double.parseDouble(bx);    double y1 = Double.parseDouble(by);        //Log.i(TAG +"=======x1===============", x1+"");    //Log.i(TAG +"=======y1===============", y1+"");        String tempx = new String(Base64Util.decode(base64x));    String tempy = new String(Base64Util.decode(base64y));        //Log.i(TAG +"=======tempx==============", tempx+"");    //Log.i(TAG +"=======tempy===============", tempy+"");        double x2 = Double.parseDouble(tempx);    double y2 = Double.parseDouble(tempy);        //Log.i(TAG +"=======x2===============", x2+"");    //Log.i(TAG +"=======y2===============", y2+"");        x = 2 * x1 - x2;    y = 2 * y1 - y2;        //Log.i(TAG +"=======x===============", x+"");    //Log.i(TAG +"=======y===============", y+"");        getGps(x+"", y+"");} catch (Exception e) {e.printStackTrace();Log.i(TAG + "baidu2Gps 坐标转换异常", "baidu map");dimissDialog();}}@Overridepublic void onFailure(Throwable t, int errorNo, String strMsg) {super.onFailure(t, errorNo, strMsg);dimissDialog();}};FinalHttp finalHttp = new FinalHttp();finalHttp.get(url, params, callback);}/** *  * 获得百度坐标对应的gps坐标 *  * 步骤2: */public void getGps(String bx,String by){String url = "http://api.map.baidu.com/ag/coord/convert";AjaxParams params = new AjaxParams();params.put("from", "0");params.put("to", "4");params.put("x", bx);params.put("y", by);Callback callback = new Callback(tag,this) {@Overridepublic void onSuccess(String t) {dimissDialog();try {JsonParser parser = new JsonParser();    JsonObject root = parser.parse(t).getAsJsonObject();        //获得真正的gps坐标    String tempx  = root.get("x").getAsString();    String tempy = root.get("y").getAsString();        String resultx = new String(Base64Util.decode(tempx));    String resulty = new String(Base64Util.decode(tempy));        MapSendAddressEvent mapSendAddressEvent = new MapSendAddressEvent();mapSendAddressEvent.address = moveAddress;mapSendAddressEvent.latitude = resulty + "";mapSendAddressEvent.longitude = resultx + "";EventBus.getDefault().post(mapSendAddressEvent);finish();    //Log.i(TAG+"============最后结果===========resultx", resultx+"");    //Log.i(TAG +"===============最后结果========resulty", resulty+"");    } catch (Exception e) {e.printStackTrace();Log.i(TAG + "getGps坐标转换异常", "baidu map");}}@Overridepublic void onFailure(Throwable t, int errorNo, String strMsg) {super.onFailure(t, errorNo, strMsg);dimissDialog();}};FinalHttp finalHttp = new FinalHttp();finalHttp.get(url, params, callback);}@Overridepublic void onResume() {super.onResume();mMapView.onResume();}@Overridepublic void onPause() {super.onPause();mMapView.onPause();}@Overridepublic void onDestroy() {super.onDestroy();mMapView.onDestroy();mSearch.destroy();}}


0 0
原创粉丝点击