关闭

android通过高德地图仿微信发送地址移动地图自动搜索附近店铺及地址(架包和配置参考高德地图官网)

标签: 仿微信发送地址移动地图自动搜索附近店铺及
563人阅读 评论(0) 收藏 举报
package com.example.daniel.carwashmerchant.modules.enter_approved.controllers;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
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.example.daniel.carwashmerchant.R;
import com.example.daniel.carwashmerchant.modules.common.controllers.CWBaseActivity;
import com.example.daniel.carwashmerchant.modules.common.views.NavigationBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import common.android.lib.ui.base.CustBaseAdapter;

/**
 * Created by daniel on 2016/8/12.
 */
public class AddressActivity extends CWBaseActivity implements AMap.OnCameraChangeListener,
        PoiSearch.OnPoiSearchListener, AMapLocationListener, AdapterView.OnItemClickListener {

    private MapView mapView;
    private ListView listView;
    private List<Map<String, String>> list;
    private AddressAdapter adapter;
    private final int ADDRESS = 2001;
    private AMap aMap;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private LocationSource.OnLocationChangedListener mListener;
    private LatLng locationLatLng;
    private Marker marker;// 有跳动效果的marker对象
    private LatLonPoint latLonPoint;
    private boolean fri;
    private int currentPage = 0;// 当前页面,从0开始计数
    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;// POI搜索
    private List<PoiItem> poiItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address);
        NavigationBar navigationBar = (NavigationBar) findViewById(R.id.navigationBar);
        navigationBar.setTitle(getResources().getString(R.string.my_position));
        ((ImageView) navigationBar.getBackBackButton()).setImageResource(R.mipmap.commonality_back_icon);
        listView = (ListView) findViewById(R.id.poi_listView);
        listView.setOnItemClickListener(this);
        list = new ArrayList<>();
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);
        adapter = new AddressAdapter(this, list);
        listView.setAdapter(adapter);
        init();
    }

    // 初始化AMap对象
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
            // 对amap添加移动地图事件监听器
            aMap.setOnCameraChangeListener(this);
            //设置定位监听
            aMap.setLocationSource(locationSource);
            // 设置默认定位按钮是否显示
            aMap.getUiSettings().setMyLocationButtonEnabled(true);
            // 设置为true表示显示定位层并可触发定位,false表示隐藏定位层并不可触发定位,默认是false
            aMap.setMyLocationEnabled(true);
        }
    }

    private void addMarker(LatLng latLng) {
        if (!fri) {
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker());
            markerOptions.draggable(true);
            markerOptions.title(getResources().getString(R.string.my_position));
            marker = aMap.addMarker(markerOptions);
            fri = true;
        }

    }

    /**
     * 定位成功后回调函数
     *
     * @param amapLocation
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null && amapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                float bearing = aMap.getCameraPosition().bearing;
                aMap.setMyLocationRotateAngle(bearing);// 设置小蓝点旋转角度
                Double geoLat = amapLocation.getLatitude();//获取纬度
                Double geoLng = amapLocation.getLongitude();//获取经度
                locationLatLng = new LatLng(geoLat, geoLng);
                addMarker(locationLatLng);
                //获得小点
                if (latLonPoint == null) {
                    latLonPoint = new LatLonPoint(geoLat, geoLng);
                } else {
                    latLonPoint.setLatitude(geoLat);
                    latLonPoint.setLongitude(geoLng);
                }
                //设置地图显示的位置
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(locationLatLng, 30));
                //将地图移动到定位点
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(geoLat, geoLng)));
                //点击定位按钮 能够将地图的中心移动到定位点
                mListener.onLocationChanged(amapLocation);
                locationSource.deactivate();
                StringBuffer buffer = new StringBuffer();
                buffer.append(amapLocation.getProvince() + "" + amapLocation.getCity() + ""
                        + amapLocation.getDistrict() + "" + amapLocation.getStreet() + ""
                        + amapLocation.getStreetNum());
                showToastMessage(buffer.toString());
                doSearchQuery();
            } else {
                //显示错误信息ErrCode是错误码,errInfo是错误信息
                String err = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                showToastMessage(err);
            }
        }
    }

    LocationSource locationSource = new LocationSource() {

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

        @Override
        public void activate(OnLocationChangedListener listener) {
            mListener = listener;
            if (mlocationClient == null) {
                mlocationClient = new AMapLocationClient(AddressActivity.this);
                //初始化定位参数
                mLocationOption = new AMapLocationClientOption();
                //设置定位监听
                mlocationClient.setLocationListener(AddressActivity.this);
                //设置定位模式为高精度模式,Battery_Saving为低功耗模式,Device_Sensors是仅设备模式
                mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
                //设置是否返回地址信息(默认返回地址信息)
                mLocationOption.setNeedAddress(true);
                //设置是否只定位一次,默认为false
                mLocationOption.setOnceLocation(false);
                //设置是否强制刷新WIFI,默认为强制刷新
                mLocationOption.setWifiActiveScan(true);
                //设置是否允许模拟位置,默认为false,不允许模拟位置
                mLocationOption.setMockEnable(false);
                //设置定位间隔,单位毫秒,默认为2000ms
                mLocationOption.setInterval(2000);
                //设置定位参数
                mlocationClient.setLocationOption(mLocationOption);
                //启动定位
                mlocationClient.startLocation();
            }
        }
    };

    /**
     * 移动地图调用
     *
     * @param position
     */
    @Override
    public void onCameraChange(CameraPosition position) {
        if (position != null) {
            LatLng target = position.target;
            marker.setPosition(target);
        }
    }

    /**
     * 移动完成定位
     *
     * @param position
     */
    @Override
    public void onCameraChangeFinish(CameraPosition position) {
        if (marker != null) {
            //目标位置的屏幕中心点经纬度坐标
            LatLng target = position.target;
            latLonPoint = new LatLonPoint(target.latitude, target.longitude);
            doSearchQuery();
        }
    }

    /**
     * 执行搜索
     */
    public void doSearchQuery() {
        currentPage = 0;
        // 第一个参数表示搜索字符串,第二个参数表示poi搜索类型,第三个参数表示poi搜索区域(空字符串代表全国)
        query = new PoiSearch.Query("", "", "西安市");
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页

        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        //设置移动点附近搜索范围
        if (latLonPoint != null) {
            PoiSearch.SearchBound searchBound = new PoiSearch.SearchBound(latLonPoint, 2000);
            poiSearch.setBound(searchBound);
        }
        poiSearch.searchPOIAsyn();
    }

    /**
     * 搜索完成回调
     *
     * @param result
     * @param rCode
     */
    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        if (rCode == 1000) {
            if (result != null && result.getQuery() != null) {
                // 取得搜索到的poiitems有多少页
                poiItems = result.getPois();// 取得第一页的poiitem数
                list.clear();
                for (PoiItem poiItem : poiItems) {
                    //附近店铺名称
                    String adName = poiItem.getTitle();
                    //附近店铺详细地址
                    String snippet = poiItem.getSnippet();
                    //获取纬度
                    double latitude = poiItem.getLatLonPoint().getLatitude();
                    //获取经度
                    double longitude = poiItem.getLatLonPoint().getLongitude();
                    Log.i("", "-------维度---------" + latitude + "-------经度-------" + longitude);
                    Map<String, String> map = new HashMap<>();
                    map.put("name", adName);
                    map.put("address", snippet);
                    map.put("latitude", latitude + "");
                    map.put("longitude", longitude + "");
                    list.add(map);

                }
                adapter.notifyDataSetChanged();
            } else {
                showToastMessage("未找到附近相关地址");
            }
        } else {
            showToastMessage("获取附近地址失败,请稍后重试");
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent();
        //选择的地址
        intent.putExtra("checkedAddress", list.get(position).get("address"));
        //选择地址的维度
        intent.putExtra("latitude", list.get(position).get("latitude").toString());
        //选择地址的经度
        intent.putExtra("longitude", list.get(position).get("longitude").toString());
        setResult(ADDRESS, intent);
        finish();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        locationSource.deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }


    class AddressAdapter extends CustBaseAdapter {

        private Context mContext;
        private List<Map<String, String>> list;

        public AddressAdapter(Context mContext, List<Map<String, String>> list) {
            this.mContext = mContext;
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            if (view == null) {
                view = LayoutInflater.from(mContext).inflate(R.layout.activity_address_poi_list_item, parent, false);
            }
            TextView name = get(view, R.id.poi_name);
            TextView address = get(view, R.id.poi_address);
            name.setText(list.get(position).get("name"));
            address.setText(list.get(position).get("address"));
            return view;
        }
    }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:3628次
    • 积分:106
    • 等级:
    • 排名:千里之外
    • 原创:7篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类