美文网首页
android studio高德地图基础应用+定位规划路线

android studio高德地图基础应用+定位规划路线

作者: 常友 | 来源:发表于2016-11-07 18:26 被阅读0次

    1.申请Key

        首先注册成为高德开发平台用户,http://lbs.amap.com/,进入控制台,点击右上角创建应用按钮,应用程序创建以后,点击该应用展开,应用对应右侧添加Key值,进入如下界面

    添加新Key

    Key名称:为你的应用起一个名字。

    服务平台默认选择android sdk。

    发布版sha1获取命令:在studio中Terminal下输入命令keytool -list -v -keystore **.keystore,之后输入keystore的密码,**为你的keystore名称;

    测试版sha1获取命令:keytool -list -v -keystore debug.keystore,密码略过;

    package:一定要是你要使用高德的项目中的package,否则高德会找不到项目。

    2.基础使用(附代码)

           基础使用只需要2DMap包,定位需要使用Location包,而搜索及路线规划需用到Service包,共三包请先准备好。

            @Override

           protected voidonCreate(Bundle savedInstanceState) {

                    super.onCreate(savedInstanceState);

                    setContentView(R.layout.activity_order_detail);

                    model.mapView = (MapView)findViewById(R.id.mapView);

                    model.mapView.onCreate(savedInstanceState);  //创建Map对象

           }

          @Override

           protected voidonDestroy() {

                   model.mapView.onDestroy();

                  super.onDestroy();

           }

           @Override

            protected voidonResume() {

                       //在activity执行onResume时执行mMapView.onResume (),实现地图生命周期管理

                      model.mapView.onResume();

                      super.onResume();

            }

            @Override

            protected voidonPause() {

                    //在activity执行onPause时执行mMapView.onPause (),实现地图生命周期管理

                   model.mapView.onPause();

                   super.onPause();

             }

             @Override

              protected voidonSaveInstanceState(Bundle outState) {

                      //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState),实现地图生命周期管理

                    model.mapView.onSaveInstanceState(outState);

                    super.onSaveInstanceState(outState);

               }

    一定要在使用MapView的Activity中进行MapView生命周期管理,否则会出现地图无法显示,内存溢出等问题。

    3.定位

              //初始化定位

             mLocationClient=newAMapLocationClient(ac);

              //设置定位回调监听

              mLocationClient.setLocationListener(this);

                //初始化定位参数

                  mLocationOption=newAMapLocationClientOption();

                  //设置定位模式为高精度模式,Battery_Saving为低功耗模式,Device_Sensors是仅设备模式

                 mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);

                //设置是否返回地址信息(默认返回地址信息)

                 mLocationOption.setNeedAddress(true);

                //设置是否只定位一次,默认为false

                  mLocationOption.setOnceLocation(true);

               //设置是否强制刷新WIFI,默认为强制刷新

             mLocationOption.setWifiActiveScan(true);

                //设置是否允许模拟位置,默认为false,不允许模拟位置

              mLocationOption.setMockEnable(false);

             //设置定位间隔,单位毫秒,默认为2000ms

               mLocationOption.setInterval(2000);

              //给定位客户端对象设置定位参数

              mLocationClient.setLocationOption(mLocationOption);

            //启动定位

              mLocationClient.startLocation();

    在Activity的初始化中写入以上方法,setOnceLocation(true)为指定位一次,然后在LocationChangeListener的监听方法中处理定位事件。

          @Override

            public voidonLocationChanged(AMapLocation aMapLocation) {

                        aMapLocation.getLocationType();//获取当前定位结果来源,如网络定位结果,详见官方定位类型表

                        startLatitude=  aMapLocation.getLatitude();//获取纬度

                      startLongitude= aMapLocation.getLongitude();//获取经度

                       aMapLocation.getAccuracy();//获取精度信息

                      city= aMapLocation.getCity();//城市信息

                       area= aMapLocation.getDistrict();//城区信息

                      street= aMapLocation.getStreet();//街道信息

                      detailAddr= aMapLocation.getStreetNum();//街道门牌号信息

                      cityCode= aMapLocation.getCityCode();

                      if(cityCode==null||StringUtils.isEmpty(cityCode)){

                                Toast.makeText(ac,"定位失败,请检查后重试",Toast.LENGTH_SHORT).show();

                      }else{

                               startAddrText.setText(city+area+street+detailAddr);

                      }

            }

    记录下定位返回的城市Code,经度,纬度等信息,在接下来的实践中会用得到。

    4.搜索地址并自动补全

               创建搜索界面,并在EditText中设置addTextWatcher监听,在after方法中处理输入完成监听事件。

              代码:if(cityCode!=null) {    //之所以判空是因为本次实践是在同城路线规划

                            PoiSearch.Query query =newPoiSearch.Query(name,"",cityCode);

                            //keyWord表示搜索字符串,

                            //第二个参数表示POI搜索类型,二者选填其一,

                             //POI搜索类型共分为以下20种:汽车服务|汽车销售|

                        //汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|

                           //住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|

                           //金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施

                         //cityCode表示POI搜索区域,可以是城市编码也可以是城市名称,也可以传空字符串,空字符串代表全国在全国范围内进行搜索

                        query.setPageSize(10);// 设置每页最多返回多少条poiitem

                         query.setPageNum(1);//设置查询页码

                          poiSearch=newPoiSearch(ac, query);

                          poiSearch.setOnPoiSearchListener(this);

                          poiSearch.searchPOIAsyn();

                  }

                  在onPoiSearched方法的返回结果中进行处理初始化搜索的列表项。

                 if(rCode ==1000) {

                          if(poiResult !=null&& poiResult.getQuery() !=null) {// 搜索poi的结果

                                     poiItems= poiResult.getPois();// 取得第一页的poiitem数据,页数从数字0开始

                                      initListView();

                              }

                 } else{

                             Toast.makeText(ac,"错误码为:"+rCode,Toast.LENGTH_SHORT).show();

                   }

              选中LIstView的某项后记录下选中地址的经纬度等信息。

    5.线路规划并在地图上画出路线

              //根据以上记录下的开始经纬度和结束经纬度进行查询路线

            LatLonPointstartPoint =newLatLonPoint(startLatitude,startLongitude);

            LatLonPointendPoint =newLatLonPoint(endLatitude,endLongitude);

            RouteSearch.FromAndTo fromAndto =newRouteSearch.FromAndTo(startPoint,endPoint);

             RouteSearch.DriveRouteQuery query =newRouteSearch.DriveRouteQuery(fromAndto,2,null,null,""); //第二个参数传2为默认驾车路线查询,1为公交路线,3为步行路线。

            在onDriveRouteSearched相应方法中进行路线处理,

            //驾车路线规划

            if(i==1000){

                  if(driveRouteResult !=null&& driveRouteResult.getPaths() !=null&& driveRouteResult.getPaths().size() >0) {

                           DrivePath drivePath = driveRouteResult.getPaths().get(0);

                            amap.clear();// 清理地图上的所有覆盖物

                            DrivingRouteOverlay drivingRouteOverlay =newDrivingRouteOverlay(ac,amap, drivePath, driveRouteResult.getStartPos(),

                             driveRouteResult.getTargetPos());

                              drivingRouteOverlay.removeFromMap();

                                drivingRouteOverlay.addToMap();

                                drivingRouteOverlay.zoomToSpan();

                   }else{

                            Toast.makeText(ac,"距离太短无法显示路线",Toast.LENGTH_SHORT).show();

                    }

          }else if(i ==27) {

                  Toast.makeText(ac,"网络连接异常",Toast.LENGTH_SHORT).show();

            }else if(i ==32) {

                  Toast.makeText(ac,"技术异常,请联系客服人员",Toast.LENGTH_SHORT).show();

             }else{

                  Toast.makeText(ac,"错误码为:"+i,Toast.LENGTH_SHORT).show();;

            }

        如果需要计算公里数,时间等功能在DrivePath的List<DriveStep>对象中进行叠加计算,代码:

        List steps =  drivePath.getSteps();

       distance=0;

        totalSecond=0;

         hour=0;

          minutes=0;

          if(steps!=null&&steps.size()>0){

                     for(DriveStep step : steps){

                               distance+= step.getDistance();//距离

                               totalSecond+= step.getDuration();

                     }

          }

         if(distance!=0&&totalSecond!=0){

                       distance=distance/1000;

                      floattempMinute =totalSecond/60;

                    //second = totalSecond%60==0?0:(int)(totalSecond%60);

                    if(tempMinute>1){

                 minutes= (int)tempMinute;

          }else{

                  Toast.makeText(ac,"距离太短,无法计算价格",Toast.LENGTH_SHORT).show();

                  return;

            }

          if(minutes>59){

                   hour=minutes/60;

                   minutes=minutes%60;

             }

         if(distance<=0){

               Toast.makeText(ac,"规划有误,请检查网络重试",Toast.LENGTH_SHORT).show();

               return;

         }

          DecimalFormat df =newDecimalFormat("###.00");

            distance= Float.parseFloat(df.format(distance));

         if(hour!=0&&minutes!=0){

               totalTimeTexts.setText("共"+distance+"公里;需"+hour+"小时"+minutes+"分钟");

         }else if(hour==0){

               totalTimeTexts.setText("共"+distance+"公里;需"+minutes+"分钟");

        }else if(minutes==0){

               totalTimeTexts.setText("共"+distance+"公里;需"+hour+"小时");

           }

    第五条讲解为两点之间的路线查询,后续功能会在新的博客中继续分享....与君共勉

    相关文章

      网友评论

          本文标题:android studio高德地图基础应用+定位规划路线

          本文链接:https://www.haomeiwen.com/subject/yemouttx.html