高德地图基础功能使用心得

个人感觉高德的sdk比百度的好用,而且出错概率也更小,如果用高德地图做一个简单的当前地点定位,不仅不需要设置mapView控件,直接集成在activity里即可。而且还可以按照固定的刷新频率获得经纬度,以及当前所在的街道和建筑物的名字,代码不长,本质上给LocationMangerProxy配置一个AmapLocationLister监听器即可,可以配置在任意一个activity或service中,百度地图换了新版之后旧版的类就没有了,真是太难用了

配置环境

首先去官网下载sdk和demo

高德地图基础功能使用心得_第1张图片

下载完后把左边开发包里的jar包和.so文件放到lib目录下,

把demo包里的AMap_Location_v1.4.0.jar也放进去,放完后是这样的

千万注意:AMap_3DMap_v2.6.0_20150914.jar要放在lib文件夹中,上图没有表示出来

最后把从官网申请的key写在manefest中

 <meta-data
            android:name="com.amap.api.v2.apikey"
            android:value="42af3812644d8c1774dba300630980a8"/>  


1、任意activity获取当前经纬度的方法

package com.example.qichebaojiata;

import android.app.Activity;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps.AMap;
import com.amap.api.maps.LocationSource;

import com.amap.api.maps.model.BitmapDescriptorFactory;

import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.SearchBound;

public class MapActivity extends Activity implements AMapLocationListener {//继承位置监听器,有一个最重要的方法,onLocationChanged(AMapLocation arg0)用于时时刷新当前位置
	 //声明变量
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	    
	    //初始化定位对象,LocationManagerProxy类是个位置管理类,给它设置一个回调监听器,指定定位设备,指定刷新频率等就可以用了
	    LocationManagerProxy mLocationManagerProxy =LocationManagerProxy .getInstance(this);//定位对象与监听器绑定
	    //注册定位监听
	    mLocationManagerProxy.requestLocationData(
	    		LocationProviderProxy.AMapNetwork,//定位设备,netWork是全部都用,
	    		1000,//刷新频率,单位ms
	    		15, //移动距离后刷新,仅对gps有效
	    		this//AMapLocationListener 回调监听器
	    		);  
	    
}
	

@Override
	/**
	 * 定位回调
	 */
	public void onLocationChanged(AMapLocation arg0) {
		// TODO Auto-generated method stub
		//检测错误码
		if(arg0!=null&&arg0.getAMapException().getErrorCode()==0){//等于0是成功了
System.out.println("城市:"+arg0.getCity()+"电话区号"+arg0.getCityCode());
			System.out.println("省:"+arg0.getProvince());
			System.out.println("国家:"+arg0.getCountry());
			System.out.println("经度"+arg0.getLatitude());
			System.out.println("纬度"+arg0.getLongitude());
			System.out.println("路是:"+arg0.getRoad());
			System.out.println("速度:"+arg0.getSpeed());
			System.out.println("楼层:"+arg0.getFloor());
			System.out.println("建筑物"+arg0.getPoiName());
		}else {
			System.out.println("定位失败");
		}
		
	}
	
}

附近位置搜索功能:

先让activity继承一个onPoiSearchListener

public class MapActivity extends Activity implements AMapLocationListener, OnPoiSearchListener 
在activity中写一个方法

public void search(){
		//Query类是一个搜索条件的封装类,用于封装页数和每页多少个
		PoiSearch.Query query = new PoiSearch.Query("车","汽车服务|汽车销售|汽车维修|摩托车服务|交通设施服务|道路附属设施","青岛市");
		// 第一个参数表示搜索字符串,
		//第二个参数表示POI搜索类型,二者选填其一,
		//POI搜索类型共分为以下20种:汽车服务|汽车销售|
		//汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|
		//住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|
		//金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
		//cityCode表示POI搜索区域的编码,是必须设置参数
		query.setPageSize(10);//设置每页返回多少条
		query.setPageNum(0);//设置车讯页码
		//PoiSearch类是一个搜索引擎,如果要返回搜索结果需要绑定一个OnPoiSearchListener类
		PoiSearch poiSearch = new PoiSearch(this, query);
		poiSearch.setOnPoiSearchListener(this);//设置本类为搜索监听类
		//设置一个地图点,LatLonPoint就是一个经纬度的封装类
		
		LatLonPoint point = new LatLonPoint(amapLocation.getLatitude(), amapLocation.getLongitude());
		//地点对象LatLonPoint如果想和引擎poiSearch设置进去,要用另一个封装类SearchBound
		//它封装了当前位置,搜索半径
		poiSearch.setBound(new SearchBound(point,2000,true));//第二个参数是搜索半径
		poiSearch.searchPOIAsyn();
	}

这个search()方法需要在获得了当前经纬度之后调用

AMapLocation amapLocation;
boolean searchFlag = false;
@Override
	/**
	 * 定位回调
	 */
	public void onLocationChanged(AMapLocation arg0) {
		// TODO Auto-generated method stub
		//检测错误码
		if(arg0!=null&&arg0.getAMapException().getErrorCode()==0){//等于0是成功了
			amapLocation = arg0;
			
			if(!searchFlag){
				search();
				searchFlag=true;
			}
			
		}else {
			System.out.println("定位失败");
		}
		
	}


写一个专门用来定位的服务也很简单

package com.situ.service;

import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;

public class GPSService extends Service implements AMapLocationListener {
	
	public static String PROVENCE = "山东";
	public static String CITY_NAME = "青岛";
	public static double LATITUDE = 0.0;
	public static double LONGITUDE = 0.0;
	public static String POI_NAME = "未知";
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		System.out.println("服务启动");
		System.out.println("服务启动");
		System.out.println("服务启动");
		System.out.println("服务启动");
		 //初始化定位对象,LocationManagerProxy类是个位置管理类,给它设置一个回调监听器,指定定位设备,指定刷新频率等就可以用了  
        LocationManagerProxy mLocationManagerProxy =LocationManagerProxy .getInstance(getApplicationContext());//定位对象与监听器绑定  
        //注册定位监听  
       
        mLocationManagerProxy.requestLocationData(  
                LocationProviderProxy.AMapNetwork,//定位设备,netWork是全部都用,  
                2000,//刷新频率,单位ms  
                15, //移动距离后刷新,仅对gps有效  
                this//AMapLocationListener 回调监听器  
                );    
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override  
    /** 
     * 定位回调 
     */  
    public void onLocationChanged(AMapLocation arg0) {  
        // TODO Auto-generated method stub  
        //检测错误码  
        if(arg0!=null&&arg0.getAMapException().getErrorCode()==0){//等于0是成功了  
        	System.out.println("城市:"+arg0.getCity()+"电话区号"+arg0.getCityCode());  
            this.PROVENCE = arg0.getProvince();
            this.CITY_NAME = arg0.getCity();
            this.POI_NAME = arg0.getPoiName();
            this.LATITUDE = arg0.getLatitude();
            this.LONGITUDE = arg0.getLongitude();
        }else {  
            System.out.println("定位失败");  
        }  
          
    }  
	

}

我就喜欢把AmapLocationListener放在一个service里,实现监听器的分离,那么在activity里的map对象想获得当前定位的蓝色指针,就要外接listener,这样activity就不需要继承

AmapLocationListener接口了,可以实现资源利用的优化

package com.situ.schoolsale;

import java.util.ArrayList;  
import java.util.List;  
  




import android.app.Activity;  
import android.content.Intent;
import android.graphics.Color;  
import android.location.Location;  
import android.os.Bundle;  
  




import com.amap.api.location.AMapLocation;  
import com.amap.api.location.AMapLocationListener;  
import com.amap.api.location.LocationManagerProxy;  
import com.amap.api.location.LocationProviderProxy;  
import com.amap.api.maps.AMap;  
import com.amap.api.maps.LocationSource;  
import com.amap.api.maps.MapView;  
import com.amap.api.maps.model.BitmapDescriptor;  
import com.amap.api.maps.model.BitmapDescriptorFactory;  
import com.amap.api.maps.model.LatLng;  
import com.amap.api.maps.model.Marker;  
import com.amap.api.maps.model.MarkerOptions;  
import com.amap.api.maps.model.MyLocationStyle;  
import com.situ.service.GPSService;
  
public class MapActivity extends Activity implements  LocationSource{//地图加载完成的监听器  
     //声明变量  
    private MapView mapView;  
    private AMap aMap;  
    LocationManagerProxy mAMapLocationManager ;  
    OnLocationChangedListener mListener;  
    private Marker marker;// 定位雷达小图标  
      
      
    List<LatLng> list = new ArrayList<LatLng>();//用于存储轨迹的单点  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_map); 
        if(GPSService.isRunning==false){
        	startService(new Intent(this,GPSService.class));//开启GPS服务
        }
        //在onCreat方法中给aMap对象赋值  
        //显示地图用的三句话  
        mapView = (MapView) findViewById(R.id.map);  
        mapView.onCreate(savedInstanceState);// 必须要写  
        aMap = mapView.getMap();  
        setUpMap();  
        new Thread(){
        	public void run() {
        		while(true){
        			try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
        			System.out.println("正在定位");
        		 if (mListener != null &&GPSService.location!=null) { //外接AMapLocationListener的AmapLocation(在onLocationChanged方法中的参数)
                     mListener.onLocationChanged(GPSService.location);// 显示系统小蓝点  
                     marker.setPosition(new LatLng(GPSService.LATITUDE, GPSService.LONGITUDE));// 定位雷达小图标  
                     float bearing = aMap.getCameraPosition().bearing;  
                     aMap.setMyLocationRotateAngle(bearing);// 设置小蓝点旋转角度  
                 }  
        		}
        	};
        }.start();
    }  
        /** 
         * 设置一些amap的属性 
         */  
        private void setUpMap() {  
            ArrayList<BitmapDescriptor> giflist = new ArrayList<BitmapDescriptor>();  
            giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point1));//蓝色圆点  
            giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point2));  
            giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point3));  
            giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point4));  
            giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point5));  
            giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point6));  
            marker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)  
                    .icons(giflist).period(50));  
            // 自定义系统定位小蓝点  
            MyLocationStyle myLocationStyle = new MyLocationStyle();  
            myLocationStyle.myLocationIcon(BitmapDescriptorFactory  
                    .fromResource(R.drawable.location_marker));// 设置蓝色箭头  
            myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色  
            myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色  
            // myLocationStyle.anchor(int,int)//设置小蓝点的锚点  
            myLocationStyle.strokeWidth(0.1f);// 设置圆形的边框粗细  
            aMap.setMyLocationStyle(myLocationStyle);  
            aMap.setMyLocationRotateAngle(90);//这个参数好像没什么用  
            aMap.setLocationSource(this);// 设置定位监听  
            aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示  
            aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位,false表示隐藏定位层并不可触发定位,默认是false  
            //设置定位的类型为定位模式 ,可以由定位、跟随或地图根据面向方向旋转几种   
            aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_ROTATE);//整个地图根据手机旋转,指针始终向前  
//          aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);//指针始终向手机前方,人走动的也不动  
//          aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);//指针始终指向北方,相当于指北针  
        }  
  
           
          
        /** 
         * 方法必须重写 
         */  
        @Override  
        protected void onResume() {  
            super.onResume();  
            mapView.onResume();  
        }  
  
        /** 
         * 方法必须重写 
         */  
        @Override  
        protected void onPause() {  
            super.onPause();  
            mapView.onPause();  
            deactivate();  
        }  
  
        /** 
         * 方法必须重写 
         */  
        @Override  
        protected void onSaveInstanceState(Bundle outState) {  
            super.onSaveInstanceState(outState);  
            mapView.onSaveInstanceState(outState);  
        }  
  
        /** 
         * 方法必须重写 
         */  
        @Override  
        protected void onDestroy() {  
            super.onDestroy();  
            mapView.onDestroy();  
        }  
  
        
  
       
  
        /** 
         * 激活定位 
         */  
        @Override  
        public void activate(OnLocationChangedListener listener) {  
            mListener = listener;  
            if (mAMapLocationManager == null) {  
                mAMapLocationManager = LocationManagerProxy.getInstance(this);  
                /* 
                 * mAMapLocManager.setGpsEnable(false); 
                 * 1.0.2版本新增方法,设置true表示混合定位中包含gps定位,false表示纯网络定位,默认是true Location 
                 * API定位采用GPS和网络混合定位方式 
                 * ,第一个参数是定位provider,第二个参数时间最短是2000毫秒,第三个参数距离间隔单位是米,第四个参数是定位监听者 
                 */  
               
                mAMapLocationManager.requestLocationData(  
                        LocationProviderProxy.AMapNetwork, 2000, 10, GPSService.listener); //外接一个AmapListener 
            }  
        }  
  
        /** 
         * 停止定位 
         */  
        @Override  
        public void deactivate() {  
            mListener = null;  
            if (mAMapLocationManager != null) {  
                mAMapLocationManager.removeUpdates(GPSService.listener);  //外接一个AMapLocationListener
                mAMapLocationManager.destroy();; 
            }  
            mAMapLocationManager = null;  
        }  
  
          
      
      
}  




定位成功的回调函数

/**
     * 搜索成功的回调函数
     * @param arg0
     * @param arg1
     */
    @Override
    public void onPoiSearched(PoiResult arg0, int arg1) {
        // TODO Auto-generated method stub
        if(arg1==0){//搜索成功
            List<PoiItem> list = arg0.getPois();
            //PoiItem类是封装查询结果的类
            for (PoiItem poiItem : list) {
                System.out.println("搜索结果区名:"+poiItem.getAdName());//返回:城阳区
                System.out.println("结果大概位置:"+poiItem.getSnippet());//返回:是建筑物的话返回如春阳路346附近、春阳路167-2号,如果是公交车站的话返回:117路;613路;903路;905路环线;915路环线,
                System.out.println("搜索结果title:"+poiItem.getTitle());// 搜索结果title:金鑫源汽车租赁
                System.out.println("目标经纬度是"+poiItem.getLatLonPoint().getLatitude()+","+poiItem.getLatLonPoint().getLongitude());
            }
//用标记显示出搜索的结果
            PoiOverlay poiOverlay = new PoiOverlay(aMap, poiItems);
            poiOverlay.removeFromMap();
            poiOverlay.addToMap();//把标记添加到地图上
            poiOverlay.zoomToSpan();//让地图转移到搜索后的位置
 }
    }

3、绘制步行轨迹,这是一个很好玩的功能,可以记录行程,用于跑步计步什么的,一般可以用在service

package com.example.qichebaojiata;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.OnMapLoadedListener;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.PolylineOptions;

public class MapActivity extends Activity implements AMapLocationListener ,OnMapLoadedListener{//地图加载完成的监听器
	 //声明变量
    private MapView mapView;
    private AMap aMap;
    LocationManagerProxy mAMapLocationManager ;
    
	List<LatLng> list = new ArrayList<LatLng>();//用于存储轨迹的list
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_map);
	    //在onCreat方法中给aMap对象赋值
	    //显示地图用的三句话
	    mapView = (MapView) findViewById(R.id.map);
	    mapView.onCreate(savedInstanceState);// 必须要写
	    //给mapView绑定加载监听器
            aMap = mapView.getMap();
	    aMap.setOnMapLoadedListener(this);
            // AMap类自动处理以下操作
               1.连接到高德地图服务
               2.下载地图数据
               3.在设备屏幕上显示地图
               4.显示各种控件,如缩放按钮控件
               5.支持各种手势,如平移和缩放手势
            //初始化定位对象
	    LocationManagerProxy mLocationManagerProxy =LocationManagerProxy .getInstance(this);//定位对象与监听器绑定
	    //注册定位监听
	    mLocationManagerProxy.requestLocationData(
	    		LocationProviderProxy.AMapNetwork,//定位设备,netWork是全部都用
	    		1000,//刷新频率,单位ms
	    		15, //移动距离后刷新,仅对gps有效
	    		this//AMapLocationListener 回调监听器
	    		);
	    
	    
	}
	
	
	
	AMapLocation amapLocation;
	boolean searchFlag = false;
	@Override
	/**
	 * 定位回调
	 */
	public void onLocationChanged(AMapLocation arg0) {
		// TODO Auto-generated method stub
		//检测错误码
		if(arg0!=null&&arg0.getAMapException().getErrorCode()==0){//等于0是成功了
			amapLocation = arg0;
			//latLng对象是一个经纬度的封装类,有点像LatLonPoint类
			LatLng latLng = new LatLng(arg0.getLatitude(), arg0.getLongitude());
			System.out.println("当前经纬度"+latLng);
			//把当前经纬度放到list里去,准备绘制轨迹
			list.add(latLng);
			//添加轨迹线
			if(mapLoaded==true){//如果mapView已经加载完成,否则容易报错
				System.out.println("正在绘制轨迹");
				mapView.getMap().addPolyline(new PolylineOptions().addAll(list));
			}
			if(!searchFlag){
				searchFlag=true;
			}
			
		}else {
			System.out.println("定位失败");
		}
		
	}

	boolean mapLoaded=false;
	/**
	 * 地图加载完毕后调用
	 */
	@Override
	public void onMapLoaded() {
		// TODO Auto-generated method stub
		mapLoaded = true;
	}
		
	
}


下面到了最激动人心的时刻了,用mapView显示一个小蓝色箭头,指示出用户当前的位置和方向:

下面给出高德官方的例程,测试过感觉还行

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.OnMapLoadedListener;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.PolylineOptions;

public class MapActivity extends Activity implements AMapLocationListener , LocationSource{//地图加载完成的监听器
	 //声明变量
    private MapView mapView;
    private AMap aMap;
    LocationManagerProxy mAMapLocationManager ;
    OnLocationChangedListener mListener;
    private Marker marker;// 定位雷达小图标
    
    
	List<LatLng> list = new ArrayList<LatLng>();//用于存储轨迹的单点
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_map);
	    //在onCreat方法中给aMap对象赋值
	    //显示地图用的三句话
	    mapView = (MapView) findViewById(R.id.map);
	    mapView.onCreate(savedInstanceState);// 必须要写
	    aMap = mapView.getMap();
	    setUpMap();
	}
	    /**
		 * 设置一些amap的属性
		 */
		private void setUpMap() {
			ArrayList<BitmapDescriptor> giflist = new ArrayList<BitmapDescriptor>();
			giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point1));//蓝色圆点
			giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point2));
			giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point3));
			giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point4));
			giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point5));
			giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point6));
			marker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
					.icons(giflist).period(50));
			// 自定义系统定位小蓝点
			MyLocationStyle myLocationStyle = new MyLocationStyle();
			myLocationStyle.myLocationIcon(BitmapDescriptorFactory
					.fromResource(R.drawable.location_marker));// 设置蓝色箭头
			myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
			myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
			// myLocationStyle.anchor(int,int)//设置小蓝点的锚点
			myLocationStyle.strokeWidth(0.1f);// 设置圆形的边框粗细
			aMap.setMyLocationStyle(myLocationStyle);
			aMap.setMyLocationRotateAngle(90);//这个参数好像没什么用
			aMap.setLocationSource(this);// 设置定位监听
			aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
			aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位,false表示隐藏定位层并不可触发定位,默认是false
			//设置定位的类型为定位模式 ,可以由定位、跟随或地图根据面向方向旋转几种 
			aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_ROTATE);//整个地图根据手机旋转,指针始终向前
//			aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);//指针始终向手机前方,人走动的也不动
//			aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);//指针始终指向北方,相当于指北针
		}

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

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

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

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

		/**
		 * 此方法已经废弃
		 */
		@Override
		public void onLocationChanged(Location location) {
		}

		@Override
		public void onProviderDisabled(String provider) {
		}

		@Override
		public void onProviderEnabled(String provider) {
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}

		/**
		 * 定位成功后回调函数
		 */
		@Override
		public void onLocationChanged(AMapLocation aLocation) {
			if (mListener != null && aLocation != null) {
				mListener.onLocationChanged(aLocation);// 显示系统小蓝点
				marker.setPosition(new LatLng(aLocation.getLatitude(), aLocation
						.getLongitude()));// 定位雷达小图标
				float bearing = aMap.getCameraPosition().bearing;
				aMap.setMyLocationRotateAngle(bearing);// 设置小蓝点旋转角度
			}
		}

		/**
		 * 激活定位
		 */
		@Override
		public void activate(OnLocationChangedListener listener) {
			mListener = listener;
			if (mAMapLocationManager == null) {
				mAMapLocationManager = LocationManagerProxy.getInstance(this);
				/*
				 * mAMapLocManager.setGpsEnable(false);
				 * 1.0.2版本新增方法,设置true表示混合定位中包含gps定位,false表示纯网络定位,默认是true Location
				 * API定位采用GPS和网络混合定位方式
				 * ,第一个参数是定位provider,第二个参数时间最短是2000毫秒,第三个参数距离间隔单位是米,第四个参数是定位监听者
				 */
				mAMapLocationManager.requestLocationData(
						LocationProviderProxy.AMapNetwork, 2000, 10, this);
			}
		}

		/**
		 * 停止定位
		 */
		@Override
		public void deactivate() {
			mListener = null;
			if (mAMapLocationManager != null) {
				mAMapLocationManager.removeUpdates(this);
				mAMapLocationManager.destroy();;
			}
			mAMapLocationManager = null;
		}

		
	
	
}


那么现在让蓝色指针和路径轨迹同时出现一下,只需要把上面的onLocationChanged(AmapLocation)添加一点东西就可以了

/**
         * 定位成功后回调函数
         */
        @Override
        public void onLocationChanged(AMapLocation aLocation) {
            if (mListener != null && aLocation != null) {
                mListener.onLocationChanged(aLocation);// 显示系统小蓝点
                marker.setPosition(new LatLng(aLocation.getLatitude(), aLocation
                        .getLongitude()));// 定位雷达小图标
                float bearing = aMap.getCameraPosition().bearing;
                System.out.println("当前转角"+bearing);
                aMap.setMyLocationRotateAngle(bearing);// 设置小蓝点旋转角度
                
                    //latLng对象是一个经纬度的封装类,有点像LatLonPoint类
                    LatLng latLng = new LatLng(aLocation.getLatitude(), aLocation.getLongitude());
                    System.out.println("当前经纬度"+latLng);
                    //把当前经纬度放到list里去,准备绘制轨迹
                    list.add(latLng);
                    //添加轨迹线
                        System.out.println("正在绘制轨迹");
                        mapView.getMap().addPolyline(new PolylineOptions().addAll(list));
                    
                }else {
                    System.out.println("定位失败");
                }
            
        }

4、下面是最实用的一个功能,根据指定的经纬度在地图上加一个或多个标记,或者画一条连接本地到标记的虚线,或者根据指定位置画一个规定半径的透明的圆来标明区域


import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.OnMapLoadedListener;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.PolylineOptions;

public class MapActivity extends Activity implements AMapLocationListener , LocationSource{//地图加载完成的监听器
	 //声明变量
    private MapView mapView;
    private AMap aMap;
    LocationManagerProxy mAMapLocationManager ;
    OnLocationChangedListener mListener;
    private Marker marker;// 定位雷达小图标
    MarkerOptions markerOptions = new MarkerOptions();//MarkerOptions这个类作用大,position属性:在地图上标记位置的经纬度值,titile属性:当用户点击标记,在信息窗口上显示的字符串
    //snippet附加文本,显示在标题的下方
    //draggable 如果您允许用于可以自由移动标记
    //visible设置false则标记不可见
    //icon设置Marker的图标
    //anchor图标摆放在地图上的基准点
    //perspective设置true,标记有近大远小的效果
    //可以通过Marker.setRotateAngle()方法设置旋转角度
    
	List<LatLng> list = new ArrayList<LatLng>();//用于存储轨迹的单点
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_map);
	    //在onCreat方法中给aMap对象赋值
	    //显示地图用的三句话
	    mapView = (MapView) findViewById(R.id.map);
	    mapView.onCreate(savedInstanceState);// 必须要写
	    aMap = mapView.getMap();
	    setUpMap();
	    markerOptions.position(new LatLng(36.306307,120.396338));//设置标记的位置
	    markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.audi));//设置标记的图片
	    //给地图添加标记
	    Marker marker = aMap.addMarker(markerOptions);//如果这几句添加for循环,可以添加多个标志
	    //设置标记的旋转角度,很好玩的功能
	    marker.setRotateAngle(30);
	    
	    //正如markerOptions可以再地图上画标记,polylineOptions可以在地图上画一条线
	    PolylineOptions polylineOptions = new PolylineOptions();
	    polylineOptions.add(new LatLng(36.306307,120.396338),new LatLng(37.306307,120.396338));//可以画多个点组成的折线
	    polylineOptions.color(0xffaabbcc);//设置线的颜色
	    polylineOptions.width(10);//设置线宽
	    polylineOptions.setDottedLine(true);//设置为虚线
	    aMap.addPolyline(polylineOptions);
	    
	    //画个圆
	    CircleOptions circleOptions = new CircleOptions();
	    circleOptions.center(new LatLng(36.306307, 120.396338));//设置圆心
	    circleOptions.radius(1000);//设置半径1000m
	    circleOptions.fillColor(0xaabbccdd);//设置颜色,可以在此设置透明度
	    aMap.addCircle(circleOptions);
	    //还可以设置边框的颜色和宽度
	}
	    
        //下面的用于定位的显示和上面例程的一样
		
	
	
}

4、规划路径功能

有三种方式,步行,驾车,公交,每个方式都有自己的查询类和回调函数,要分类使用,下面以步行为例

首先activity要继承一个监听器来回调

public class MapActivity extends Activity implements OnRouteSearchListener
具体的搜索函数,在oncreate中调用

/**
		 * 开始搜索步行路径
		 * @param startPoint
		 * @param endPoint
		 */
		public void searchRouteResult(LatLonPoint startPoint, LatLonPoint endPoint) {
			final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
					startPoint, endPoint);//FromAndTo对象用于封装出发地和目的地的经纬度
				WalkRouteQuery query = new WalkRouteQuery(fromAndTo, RouteSearch.WalkDefault);// 第一个参数表示路径规划的起点和终点,第二个参数表示驾车模式,第三个参数表示途经点,第四个参数表示避让区域,第五个参数表示避让道路
				routeSearch.calculateWalkRouteAsyn(query);// 异步路径规划驾车模式查询
		}
复写回调函数

/**
		 * 步行路线结果回调
		 */
		@Override
		public void onWalkRouteSearched(WalkRouteResult result, int rCode) {
			if (rCode == 0) {
				if (result != null && result.getPaths() != null
						&& result.getPaths().size() > 0) {
					WalkPath walkPath = result.getPaths().get(0);
//					aMap.clear();// 清理地图上的所有覆盖物,如果不需要请不要开启
					WalkRouteOverlay walkRouteOverlay = new WalkRouteOverlay(this,
							aMap, walkPath, result.getStartPos(),
							result.getTargetPos());
					walkRouteOverlay.addToMap();
					walkRouteOverlay.zoomToSpan();
				} else {
					System.out.println("没找到步行结果");
				}
			} else if (rCode == 27) {
				System.out.println("失败");
			} else if (rCode == 32) {
				System.out.println("失败");
			} else {
				System.out.println("失败");
			}
		}

如果是驾驶路径,方法几乎一样

/**
	 * 开始搜索路径规划方案
	 */
	public void searchRouteResult(LatLonPoint startPoint, LatLonPoint endPoint) {
		showProgressDialog();
		final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
		
		
			DriveRouteQuery query = new DriveRouteQuery(fromAndTo, RouteSearch.DrivingDefault,
					null, null, "");// 第一个参数表示路径规划的起点和终点,第二个参数表示驾车模式,第三个参数表示途经点,第四个参数表示避让区域,第五个参数表示避让道路
			routeSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询
		
	}

回调

/**
	 * 驾车结果回调
	 */
	@Override
	public void onDriveRouteSearched(DriveRouteResult result, int rCode) {
		dissmissProgressDialog();
		if (rCode == 0) {
			if (result != null && result.getPaths() != null
					&& result.getPaths().size() > 0) {
				driveRouteResult = result;
				DrivePath drivePath = driveRouteResult.getPaths().get(0);
				aMap.clear();// 清理地图上的所有覆盖物
				DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(
						this, aMap, drivePath, driveRouteResult.getStartPos(),
						driveRouteResult.getTargetPos());
				drivingRouteOverlay.removeFromMap();
				drivingRouteOverlay.addToMap();
				drivingRouteOverlay.zoomToSpan();
			} else {
<pre name="code" class="java">
					System.out.println("没找到驾车结果");
				}
			} else if (rCode == 27) {
				System.out.println("失败");
			} else if (rCode == 32) {
				System.out.println("失败");
			} else {
				System.out.println("失败");
			}
		}

 公交结果请参考官网给的demo,在下面贴出来 
 
package com.amap.map3d.demo.route;

import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.InfoWindowAdapter;
import com.amap.api.maps.AMap.OnInfoWindowClickListener;
import com.amap.api.maps.AMap.OnMapClickListener;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.MapView;
import com.amap.api.maps.MapsInitializer;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.overlay.BusRouteOverlay;
import com.amap.api.maps.overlay.DrivingRouteOverlay;
import com.amap.api.maps.overlay.WalkRouteOverlay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiItemDetail;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.amap.api.services.route.BusPath;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.RouteSearch.BusRouteQuery;
import com.amap.api.services.route.RouteSearch.DriveRouteQuery;
import com.amap.api.services.route.RouteSearch.OnRouteSearchListener;
import com.amap.api.services.route.RouteSearch.WalkRouteQuery;
import com.amap.api.services.route.WalkPath;
import com.amap.api.services.route.WalkRouteResult;
import com.amap.map3d.demo.route.RouteSearchPoiDialog.OnListItemClick;
import com.amap.map3d.demo.util.AMapUtil;
import com.amap.map3d.demo.util.OffLineMapUtils;
import com.amap.map3d.demo.util.ToastUtil;
import com.amap.map3d.demo.R;

/**
 * AMapV2地图中简单介绍route搜索
 */
public class RouteActivity extends Activity implements OnMarkerClickListener,
		OnMapClickListener, OnInfoWindowClickListener, InfoWindowAdapter,
		OnPoiSearchListener, OnRouteSearchListener, OnClickListener {
	private AMap aMap;
	private MapView mapView;
	private Button drivingButton;
	private Button busButton;
	private Button walkButton;

	private ImageButton startImageButton;
	private ImageButton endImageButton;
	private ImageButton routeSearchImagebtn;

	private EditText startTextView;
	private EditText endTextView;
	private ProgressDialog progDialog = null;// 搜索时进度条
	private int busMode = RouteSearch.BusDefault;// 公交默认模式
	private int drivingMode = RouteSearch.DrivingDefault;// 驾车默认模式
	private int walkMode = RouteSearch.WalkDefault;// 步行默认模式
	private BusRouteResult busRouteResult;// 公交模式查询结果
	private DriveRouteResult driveRouteResult;// 驾车模式查询结果
	private WalkRouteResult walkRouteResult;// 步行模式查询结果
	private int routeType = 1;// 1代表公交模式,2代表驾车模式,3代表步行模式
	private String strStart;
	private String strEnd;
	private LatLonPoint startPoint = null;
	private LatLonPoint endPoint = null;
	private PoiSearch.Query startSearchQuery;
	private PoiSearch.Query endSearchQuery;

	private boolean isClickStart = false;
	private boolean isClickTarget = false;
	private Marker startMk, targetMk;
	private RouteSearch routeSearch;
	public ArrayAdapter<String> aAdapter;

	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.route_activity);
        /*
         * 设置离线地图存储目录,在下载离线地图或初始化地图设置;
         * 使用过程中可自行设置, 若自行设置了离线地图存储的路径,
         * 则需要在离线地图下载和使用地图页面都进行路径设置
         * */
	    //Demo中为了其他界面可以使用下载的离线地图,使用默认位置存储,屏蔽了自定义设置
        MapsInitializer.sdcardDir =OffLineMapUtils.getSdCacheDir(this);
		mapView = (MapView) findViewById(R.id.map);
		mapView.onCreate(bundle);// 此方法必须重写
		init();
	}

	/**
	 * 初始化AMap对象
	 */
	private void init() {
		if (aMap == null) {
			aMap = mapView.getMap();
			registerListener();
		}
		routeSearch = new RouteSearch(this);
		routeSearch.setRouteSearchListener(this);
		startTextView = (EditText) findViewById(R.id.autotextview_roadsearch_start);
		endTextView = (EditText) findViewById(R.id.autotextview_roadsearch_goals);
		busButton = (Button) findViewById(R.id.imagebtn_roadsearch_tab_transit);
		busButton.setOnClickListener(this);
		drivingButton = (Button) findViewById(R.id.imagebtn_roadsearch_tab_driving);
		drivingButton.setOnClickListener(this);
		walkButton = (Button) findViewById(R.id.imagebtn_roadsearch_tab_walk);
		walkButton.setOnClickListener(this);
		startImageButton = (ImageButton) findViewById(R.id.imagebtn_roadsearch_startoption);
		startImageButton.setOnClickListener(this);
		endImageButton = (ImageButton) findViewById(R.id.imagebtn_roadsearch_endoption);
		endImageButton.setOnClickListener(this);
		routeSearchImagebtn = (ImageButton) findViewById(R.id.imagebtn_roadsearch_search);
		routeSearchImagebtn.setOnClickListener(this);
	}

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

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

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

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

	/**
	 * 选择公交模式
	 */
	private void busRoute() {
		routeType = 1;// 标识为公交模式
		busMode = RouteSearch.BusDefault;
		drivingButton.setBackgroundResource(R.drawable.mode_driving_off);
		busButton.setBackgroundResource(R.drawable.mode_transit_on);
		walkButton.setBackgroundResource(R.drawable.mode_walk_off);

	}

	/**
	 * 选择驾车模式
	 */
	private void drivingRoute() {
		routeType = 2;// 标识为驾车模式
		drivingButton.setBackgroundResource(R.drawable.mode_driving_on);
		busButton.setBackgroundResource(R.drawable.mode_transit_off);
		walkButton.setBackgroundResource(R.drawable.mode_walk_off);
	}

	/**
	 * 选择步行模式
	 */
	private void walkRoute() {
		routeType = 3;// 标识为步行模式
		walkMode = RouteSearch.WalkMultipath;
		drivingButton.setBackgroundResource(R.drawable.mode_driving_off);
		busButton.setBackgroundResource(R.drawable.mode_transit_off);
		walkButton.setBackgroundResource(R.drawable.mode_walk_on);
	}

	/**
	 * 在地图上选取起点
	 */
	private void startImagePoint() {
		ToastUtil.show(RouteActivity.this, "在地图上点击您的起点");
		isClickStart = true;
		isClickTarget = false;
		registerListener();
	}

	/**
	 * 在地图上选取终点
	 */
	private void endImagePoint() {
		ToastUtil.show(RouteActivity.this, "在地图上点击您的终点");
		isClickTarget = true;
		isClickStart = false;
		registerListener();
	}

	/**
	 * 点击搜索按钮开始Route搜索
	 */
	public void searchRoute() {
		strStart = startTextView.getText().toString().trim();
		strEnd = endTextView.getText().toString().trim();
		if (strStart == null || strStart.length() == 0) {
			ToastUtil.show(RouteActivity.this, "请选择起点");
			return;
		}
		if (strEnd == null || strEnd.length() == 0) {
			ToastUtil.show(RouteActivity.this, "请选择终点");
			return;
		}
		if (strStart.equals(strEnd)) {
			ToastUtil.show(RouteActivity.this, "起点与终点距离很近,您可以步行前往");
			return;
		}

		startSearchResult();// 开始搜终点
	}

	@Override
	public void onInfoWindowClick(Marker marker) {
		isClickStart = false;
		isClickTarget = false;
		if (marker.equals(startMk)) {
			startTextView.setText("地图上的起点");
			startPoint = AMapUtil.convertToLatLonPoint(startMk.getPosition());
			startMk.hideInfoWindow();
			startMk.remove();
		} else if (marker.equals(targetMk)) {
			endTextView.setText("地图上的终点");
			endPoint = AMapUtil.convertToLatLonPoint(targetMk.getPosition());
			targetMk.hideInfoWindow();
			targetMk.remove();
		}
	}

	@Override
	public boolean onMarkerClick(Marker marker) {
		if (marker.isInfoWindowShown()) {
			marker.hideInfoWindow();
		} else {
			marker.showInfoWindow();
		}
		return false;
	}

	@Override
	public void onMapClick(LatLng latng) {
		if (isClickStart) {
			startMk = aMap.addMarker(new MarkerOptions()
					.anchor(0.5f, 1)
					.icon(BitmapDescriptorFactory
							.fromResource(R.drawable.point)).position(latng)
					.title("点击选择为起点"));
			startMk.showInfoWindow();
		} else if (isClickTarget) {
			targetMk = aMap.addMarker(new MarkerOptions()
					.anchor(0.5f, 1)
					.icon(BitmapDescriptorFactory
							.fromResource(R.drawable.point)).position(latng)
					.title("点击选择为目的地"));
			targetMk.showInfoWindow();
		}
	}

	@Override
	public View getInfoContents(Marker marker) {
		return null;
	}

	@Override
	public View getInfoWindow(Marker marker) {
		return null;
	}

	/**
	 * 注册监听
	 */
	private void registerListener() {
		aMap.setOnMapClickListener(RouteActivity.this);
		aMap.setOnMarkerClickListener(RouteActivity.this);
		aMap.setOnInfoWindowClickListener(RouteActivity.this);
		aMap.setInfoWindowAdapter(RouteActivity.this);
	}

	/**
	 * 显示进度框
	 */
	private void showProgressDialog() {
		if (progDialog == null)
			progDialog = new ProgressDialog(this);
		progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progDialog.setIndeterminate(false);
		progDialog.setCancelable(true);
		progDialog.setMessage("正在搜索");
		progDialog.show();
	}

	/**
	 * 隐藏进度框
	 */
	private void dissmissProgressDialog() {
		if (progDialog != null) {
			progDialog.dismiss();
		}
	}

	/**
	 * 查询路径规划起点
	 */
	public void startSearchResult() {
		strStart = startTextView.getText().toString().trim();
		if (startPoint != null && strStart.equals("地图上的起点")) {
			endSearchResult();
		} else {
			showProgressDialog();
			startSearchQuery = new PoiSearch.Query(strStart, "", "010"); // 第一个参数表示查询关键字,第二参数表示poi搜索类型,第三个参数表示城市区号或者城市名
			startSearchQuery.setPageNum(0);// 设置查询第几页,第一页从0开始
			startSearchQuery.setPageSize(20);// 设置每页返回多少条数据
			PoiSearch poiSearch = new PoiSearch(RouteActivity.this,
					startSearchQuery);
			poiSearch.setOnPoiSearchListener(this);
			poiSearch.searchPOIAsyn();// 异步poi查询
		}
	}

	/**
	 * 查询路径规划终点
	 */
	public void endSearchResult() {
		strEnd = endTextView.getText().toString().trim();
		if (endPoint != null && strEnd.equals("地图上的终点")) {
			searchRouteResult(startPoint, endPoint);
		} else {
			showProgressDialog();
			endSearchQuery = new PoiSearch.Query(strEnd, "", "010"); // 第一个参数表示查询关键字,第二参数表示poi搜索类型,第三个参数表示城市区号或者城市名
			endSearchQuery.setPageNum(0);// 设置查询第几页,第一页从0开始
			endSearchQuery.setPageSize(20);// 设置每页返回多少条数据

			PoiSearch poiSearch = new PoiSearch(RouteActivity.this,
					endSearchQuery);
			poiSearch.setOnPoiSearchListener(this);
			poiSearch.searchPOIAsyn(); // 异步poi查询
		}
	}

	/**
	 * 开始搜索路径规划方案
	 */
	public void searchRouteResult(LatLonPoint startPoint, LatLonPoint endPoint) {
		showProgressDialog();
		final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
				startPoint, endPoint);
		if (routeType == 1) {// 公交路径规划
			BusRouteQuery query = new BusRouteQuery(fromAndTo, busMode, "北京", 0);// 第一个参数表示路径规划的起点和终点,第二个参数表示公交查询模式,第三个参数表示公交查询城市区号,第四个参数表示是否计算夜班车,0表示不计算
			routeSearch.calculateBusRouteAsyn(query);// 异步路径规划公交模式查询
		} else if (routeType == 2) {// 驾车路径规划
			DriveRouteQuery query = new DriveRouteQuery(fromAndTo, drivingMode,
					null, null, "");// 第一个参数表示路径规划的起点和终点,第二个参数表示驾车模式,第三个参数表示途经点,第四个参数表示避让区域,第五个参数表示避让道路
			routeSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询
		} else if (routeType == 3) {// 步行路径规划
			WalkRouteQuery query = new WalkRouteQuery(fromAndTo, walkMode);
			routeSearch.calculateWalkRouteAsyn(query);// 异步路径规划步行模式查询
		}
	}

	@Override
	public void onPoiItemDetailSearched(PoiItemDetail arg0, int arg1) {

	}

	/**
	 * POI搜索结果回调
	 */
	@Override
	public void onPoiSearched(PoiResult result, int rCode) {
		dissmissProgressDialog();
		if (rCode == 0) {// 返回成功
			if (result != null && result.getQuery() != null
					&& result.getPois() != null && result.getPois().size() > 0) {// 搜索poi的结果
				if (result.getQuery().equals(startSearchQuery)) {
					List<PoiItem> poiItems = result.getPois();// 取得poiitem数据
					RouteSearchPoiDialog dialog = new RouteSearchPoiDialog(
							RouteActivity.this, poiItems);
					dialog.setTitle("您要找的起点是:");
					dialog.show();
					dialog.setOnListClickListener(new OnListItemClick() {
						@Override
						public void onListItemClick(
								RouteSearchPoiDialog dialog,
								PoiItem startpoiItem) {
							startPoint = startpoiItem.getLatLonPoint();
							strStart = startpoiItem.getTitle();
							startTextView.setText(strStart);
							endSearchResult();// 开始搜终点
						}

					});
				} else if (result.getQuery().equals(endSearchQuery)) {
					List<PoiItem> poiItems = result.getPois();// 取得poiitem数据
					RouteSearchPoiDialog dialog = new RouteSearchPoiDialog(
							RouteActivity.this, poiItems);
					dialog.setTitle("您要找的终点是:");
					dialog.show();
					dialog.setOnListClickListener(new OnListItemClick() {
						@Override
						public void onListItemClick(
								RouteSearchPoiDialog dialog, PoiItem endpoiItem) {
							endPoint = endpoiItem.getLatLonPoint();
							strEnd = endpoiItem.getTitle();
							endTextView.setText(strEnd);
							searchRouteResult(startPoint, endPoint);// 进行路径规划搜索
						}

					});
				}
			} else {
				ToastUtil.show(RouteActivity.this, R.string.no_result);
			}
		} else if (rCode == 27) {
			ToastUtil.show(RouteActivity.this, R.string.error_network);
		} else if (rCode == 32) {
			ToastUtil.show(RouteActivity.this, R.string.error_key);
		} else {
			ToastUtil.show(RouteActivity.this, getString(R.string.error_other)
					+ rCode);
		}
	}

	/**
	 * 公交路线查询回调
	 */
	@Override
	public void onBusRouteSearched(BusRouteResult result, int rCode) {
		dissmissProgressDialog();
		if (rCode == 0) {
			if (result != null && result.getPaths() != null
					&& result.getPaths().size() > 0) {
				busRouteResult = result;
				BusPath busPath = busRouteResult.getPaths().get(0);
				aMap.clear();// 清理地图上的所有覆盖物
				BusRouteOverlay routeOverlay = new BusRouteOverlay(this, aMap,
						busPath, busRouteResult.getStartPos(),
						busRouteResult.getTargetPos());
				routeOverlay.removeFromMap();
				routeOverlay.addToMap();
				routeOverlay.zoomToSpan();
			} else {
				ToastUtil.show(RouteActivity.this, R.string.no_result);
			}
		} else if (rCode == 27) {
			ToastUtil.show(RouteActivity.this, R.string.error_network);
		} else if (rCode == 32) {
			ToastUtil.show(RouteActivity.this, R.string.error_key);
		} else {
			ToastUtil.show(RouteActivity.this, getString(R.string.error_other)
					+ rCode);
		}
	}

	/**
	 * 驾车结果回调
	 */
	@Override
	public void onDriveRouteSearched(DriveRouteResult result, int rCode) {
		dissmissProgressDialog();
		if (rCode == 0) {
			if (result != null && result.getPaths() != null
					&& result.getPaths().size() > 0) {
				driveRouteResult = result;
				DrivePath drivePath = driveRouteResult.getPaths().get(0);
				aMap.clear();// 清理地图上的所有覆盖物
				DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(
						this, aMap, drivePath, driveRouteResult.getStartPos(),
						driveRouteResult.getTargetPos());
				drivingRouteOverlay.removeFromMap();
				drivingRouteOverlay.addToMap();
				drivingRouteOverlay.zoomToSpan();
			} else {
				ToastUtil.show(RouteActivity.this, R.string.no_result);
			}
		} else if (rCode == 27) {
			ToastUtil.show(RouteActivity.this, R.string.error_network);
		} else if (rCode == 32) {
			ToastUtil.show(RouteActivity.this, R.string.error_key);
		} else {
			ToastUtil.show(RouteActivity.this, getString(R.string.error_other)
					+ rCode);
		}
	}

	/**
	 * 步行路线结果回调
	 */
	@Override
	public void onWalkRouteSearched(WalkRouteResult result, int rCode) {
		dissmissProgressDialog();
		if (rCode == 0) {
			if (result != null && result.getPaths() != null
					&& result.getPaths().size() > 0) {
				walkRouteResult = result;
				WalkPath walkPath = walkRouteResult.getPaths().get(0);
				aMap.clear();// 清理地图上的所有覆盖物
				WalkRouteOverlay walkRouteOverlay = new WalkRouteOverlay(this,
						aMap, walkPath, walkRouteResult.getStartPos(),
						walkRouteResult.getTargetPos());
				walkRouteOverlay.removeFromMap();
				walkRouteOverlay.addToMap();
				walkRouteOverlay.zoomToSpan();
			} else {
				ToastUtil.show(RouteActivity.this, R.string.no_result);
			}
		} else if (rCode == 27) {
			ToastUtil.show(RouteActivity.this, R.string.error_network);
		} else if (rCode == 32) {
			ToastUtil.show(RouteActivity.this, R.string.error_key);
		} else {
			ToastUtil.show(RouteActivity.this, getString(R.string.error_other)
					+ rCode);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.imagebtn_roadsearch_startoption:
			startImagePoint();
			break;
		case R.id.imagebtn_roadsearch_endoption:
			endImagePoint();
			break;
		case R.id.imagebtn_roadsearch_tab_transit:
			busRoute();
			break;
		case R.id.imagebtn_roadsearch_tab_driving:
			drivingRoute();
			break;
		case R.id.imagebtn_roadsearch_tab_walk:
			walkRoute();
			break;
		case R.id.imagebtn_roadsearch_search:
			searchRoute();
			break;
		default:
			break;
		}
	}
}


你可能感兴趣的:(android,地图)