在Fragment中显示地图

在Fragment中显示地图

在onCreateView()方法中通过LayoutInflater来加载布局(相当于Activity中的OnCreat())

public class BlankFragment extends Fragment implements AMap.OnMapClickListener, LocationSource, AMapLocationListener{
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_SHOW_TEXT = "text";

    private String mContentText;
    MapView mapView=null;
    //初始化地图控制器对象
    AMap aMap;
    private double mylatitude;
    private double mylongitude;
    LatLng mylatlng=null;
    LatLng poilatlng=null;

    //定位需要的数据
    LocationSource.OnLocationChangedListener mListener;
    AMapLocationClient mlocationClient;
    AMapLocationClientOption mLocationOption;
    //定位蓝点
    MyLocationStyle myLocationStyle;

    //标识,用于判断是否只显示一次定位信息和用户重新定位
    private boolean isFirstLoc = true;
    private GeocodeSearch geocodeSearch;
    //逆地理编码查询
    private RegeocodeQuery regeocodeQuery = null;

    private GeocodeQuery geocodeQuery = null;
    PoiSearch poiSearch;
    //Marker
    Marker marker=null;
    Marker []markers=null;

    //布局、控件
    LinearLayout bottom_layout=null;
    LinearLayout collect_button=null;
    LinearLayout my_position_=null;
    ImageView my_position=null;
    TextView poi_name;
    TextView poi_distance;
    TextView poi_snippet;
    TextView poi_type;
    View rootView=null;
    ImageView collect_image=null;
    Button route_button=null;

    //标志
    boolean iscollect=false;

    public BlankFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @return A new instance of fragment BlankFragment.
     */
    public static BlankFragment newInstance(String param1) {
        BlankFragment fragment = new BlankFragment();
        //BlankFragment fragment=new BlankFragment();

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        if (getArguments() != null) {
//            mContentText = getArguments().getString(ARG_SHOW_TEXT);
//        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             final Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView = inflater.inflate(R.layout.activity_main, container, false);

        mapView = (MapView) rootView.findViewById(R.id.map);
        //mapView.setVisibility(View.INVISIBLE);
        if (aMap == null) {
            aMap = mapView.getMap();
//            LatLng latLng = new LatLng(45.71701,126.64256);//构造一个位置
//            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
        }

        //设置地图的放缩级别
        //设置显示定位按钮 并且可以点击
        UiSettings settings = aMap.getUiSettings();

        aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
        // 设置定位监听
        aMap.setLocationSource(this);

        // 是否显示定位按钮
        settings.setMyLocationButtonEnabled(false);
        //是否显示缩放按钮
        settings.setZoomControlsEnabled(false);

        // 设置为true表示显示定位层并可触发定位,false表示隐藏定位层并不可触发定位,默认是false
        aMap.setMyLocationEnabled(true);
        // 设置定位的类型为定位模式,有定位、跟随或地图根据面向方向旋转几种
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);


        //设置地图点击监听
        aMap.setOnMapClickListener(this);
        //设置地理编码监听
//        geocodeSearch = new GeocodeSearch(this);
//        geocodeSearch.setOnGeocodeSearchListener(this);


        //蓝点初始化
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点,定位点依照设备方向旋转,并且会跟随设备移动。(1秒1次定位)如果不设置myLocationType,默认也会执行此种模式。
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.my_position_blue_point));
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔,只在连续定位模式下生效,单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.strokeColor(Color.TRANSPARENT);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细

        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        //aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示,非必需设置。
        //aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点,false表示隐藏定位蓝点并不进行定位,默认是false。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点,定位点依照设备方向旋转,并且会跟随设备移动。(1秒1次定位)默认执行此种模式。


        myLocationStyle.showMyLocation(true);

        final MarkerOptions markerOptions = new MarkerOptions();


        //地图poi点击
        aMap.setOnPOIClickListener(new AMap.OnPOIClickListener() {
            @Override
            public void onPOIClick(Poi poi) {

                //poiId
                poi.getPoiId();
                //poi名称
                poi.getName();
                System.out.println("poi:"+poi.getName());
                //poi经纬度
                poi.getCoordinate();
                poilatlng=poi.getCoordinate();

                doSerarchPOI(poi.getPoiId());
                bottom_layout=getActivity().findViewById(R.id.bottom_info);
                bottom_layout.setVisibility(View.VISIBLE);
                bottom_layout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        System.out.println("kjsjafnd");
                    }
                });
//                LatLng latLng = new LatLng(26.061328,119.291608);
                if(marker!=null){
                    marker.remove();
                }
                View markerView = LayoutInflater.from(getContext()).inflate(R.layout.marker_style,mapView,false);
                markerOptions.position(poi.getCoordinate())  //经纬度
//                        .title("Title") //标题
//                        .snippet("Snippet") //内容
                        .visible(true)  //是否显示
                        .draggable(false)   //是否拖拽
                        .anchor(0.5f,1.0f)  //锚点 默认0.5f,1.0f
                        .alpha(1.0f)    //透明度
                        //自定义图标
//                        .icon(BitmapDescriptorFactory.fromResource(R.mipmap.marker));
                        .icon(BitmapDescriptorFactory.fromView(markerView));
                marker=aMap.addMarker(markerOptions);
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(poi.getCoordinate()));
            }
        });

        aMap.setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
                //从location对象中获取经纬度信息,地址描述信息,建议拿到位置之后调用逆地理编码接口获取
                mapView.setVisibility(View.VISIBLE);
                mapView.onCreate(savedInstanceState);// 此方法必须重写


            }
        });

        
        //点击收藏
        /**
         *在这初始化iscollect
         */
        collect_button=rootView.findViewById(R.id.collect_button);
        collect_image=rootView.findViewById(R.id.collect_image);
        //collect_button的点击事件
        change_collect_image();

        return rootView;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理
        mapView.onDestroy();
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume (),实现地图生命周期管理
        mapView.onResume();
    }
    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause (),实现地图生命周期管理
        mapView.onPause();
    }
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState),实现地图生命周期管理
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                //mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                if (isFirstLoc) {
                    //设置缩放级别
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
                    //将地图移动到定位点
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
                    //点击定位按钮 能够将地图的中心移动到定位点
                    mListener.onLocationChanged(aMapLocation);
                    //添加图钉
                    //aMap.addMarker(getMarkerOptions(amapLocation));
                    //获取定位信息
                    mylatitude=aMapLocation.getLatitude();
                    mylongitude=aMapLocation.getLongitude();
                    mylatlng=new LatLng(mylatitude,mylongitude);
                    StringBuffer buffer = new StringBuffer();
                    buffer.append(aMapLocation.getCountry() + "" + aMapLocation.getProvince() + "" + aMapLocation.getCity() + "" + aMapLocation.getProvince() + "" + aMapLocation.getDistrict() + "" + aMapLocation.getStreet() + "" + aMapLocation.getStreetNum());
                    //Toast.makeText(getApplicationContext(), buffer.toString(), Toast.LENGTH_LONG).show();
                    isFirstLoc = false;
                }

            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
                Log.e("定位AmapErr", errText);
            }
        }

    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            //初始化定位
            mlocationClient = new AMapLocationClient(getContext());
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            mlocationClient.setLocationListener(this);
            //mLocationOption.setOnceLocation(true);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求,为了减少电量消耗或网络流量消耗,
            // 注意设置合适的定位时间的间隔(最小间隔支持为2000ms),并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后,在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下,定位无论成功与否,都无需调用stopLocation()方法移除请求,定位sdk内部会移除
            mlocationClient.startLocation();//启动定位

        }

    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;

    }


    @Override
    public void onMapClick(LatLng latLng) {
        marker.remove();
        bottom_layout.setVisibility(View.INVISIBLE);
        poi_name.setText("");
        poi_distance.setText("");
        poi_snippet.setText("");
        poi_type.setText("");
    }
    //开启POI兴趣点搜索
    protected  void doSerarchPOI(String ID) {

        //开始搜索POI兴趣点
        Log.e("Amap", "button onclick");
        //开始POI搜索
        // 1 创建一个搜索的条件对象 query
//                PoiSearch.Query query = new PoiSearch.Query(dstAddr, "", _city);
        // 2 创建一个POISearch句柄和query关联
//                PoiSearch poiSearch = new PoiSearch(getContext(), query);
        poiSearch = new PoiSearch(getContext(), null);
        poiSearch.searchPOIIdAsyn(ID);// 异步搜索
        // 3 给search绑定一个回调函数
        poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult poiResult, int i) {
                //处理得到的POI兴趣点集合 poiResult
            }
            //处理单个的数据
            @Override
            public void onPoiItemSearched(PoiItem poiItem, int i) {
                System.out.println(poiItem.getTitle()+"hhh"+poiItem.getSnippet()+"jjj"+poiItem.getTypeDes());
                poi_name = getActivity().findViewById(R.id.poi_name);
                poi_name.setText(poiItem.getTitle());
                poi_distance = getActivity().findViewById(R.id.poi_distance);
                poi_distance.setText(Tools.mi_change_kil((int)Tools.distance(poiItem.getLatLonPoint().getLatitude(),poiItem.getLatLonPoint().getLongitude(),mylatitude,mylongitude)));
                poi_snippet = getActivity().findViewById(R.id.poi_snippet);
                poi_snippet.setText(poiItem.getSnippet());
                poi_type = getActivity().findViewById(R.id.poi_type);
                poi_type.setText(poiItem.getTypeDes());
            }
        });
        // 4 启动搜索
        poiSearch.searchPOIAsyn();
    }

    /**
     * 点击收藏改变图片
     */

    public void change_collect_image(){
        collect_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iscollect=!iscollect;
                if(iscollect){
                    collect_image.setImageDrawable(getResources().getDrawable(R.drawable.collect_selector));
                }
                else {
                    collect_image.setImageDrawable(getResources().getDrawable(R.drawable.collect));
                }
            }
        });

    }

}

效果图:

在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值