app内接入高德地图常用设置及工具方法整理

地图初始化、权限设置、代码混淆等不再赘述,官方文档都有

1、常用基础设置 

UiSettings uiSettings = aMap.getUiSettings();
uiSettings.setZoomPosition(AMapOptions.ZOOM_POSITION_RIGHT_CENTER);//地图缩放按钮显示位置
uiSettings.setZoomControlsEnabled(false);//去除地图缩放按钮(默认显示)
uiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_RIGHT);//高德地图logo显示位置(无法去掉)
uiSettings.setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示

2、我的位置定位监听   页面实现  AMapLocationListener,LocationSource 接口

case R.id.ib_my_location://我的位置 自定义图标
    //先获取定位权限
    setupLocationStyle();
//我的位置定位
private void setupLocationStyle() {
    // 自定义系统定位小蓝点
    myLocationStyle = new MyLocationStyle();
    myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//定位一次,且将视角移动到地图中心点。
    // 圆圈的边框颜色
    myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
    // 圆圈的填充颜色
    myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
    // 圆圈的边框宽度
    myLocationStyle.strokeWidth(0);
    aMap.setMyLocationStyle(myLocationStyle);
    aMap.setLocationSource(this);// 设置定位监听
    aMap.setMyLocationEnabled(true);// 设置为true表示可触发定位,false表示不可触发定位,默认是false
    // aMap.setMyLocationType()
}
/**
 * 定位成功后回调函数
 */
@Override
public void onLocationChanged(AMapLocation amapLocation) {
    if (mListener != null && amapLocation != null) {
        if (amapLocation != null
                && amapLocation.getErrorCode() == 0) {
            mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
        } else {
            String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
            Log.w("AmapErr", errText);
        }
    }
}
/**
 * 激活定位
 */
@Override
public void activate(OnLocationChangedListener listener) {
    mListener = listener;
    if (mlocationClient == null) {
        mlocationClient = new AMapLocationClient(this);
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mlocationClient.setLocationListener(this);
        //设置为高精度定位模式
        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;
}

3、设置某一坐标点回到屏模中心位置,适用于点击类似我的位置的某一常驻地点

//位置移动到地图中心位
aMap.moveCamera(CameraUpdateFactory.changeLatLng(latlng));

4、添加marker及infoWindow

自定义infoWindow

/**
 * 地图上自定义的infowindow的适配器
 */
public class InfoWinAdapter implements AMap.InfoWindowAdapter {
    private Context mContext;
    private LatLng latLng;
    private TextView nameTV;
    private ImageView navigation;
    private TextView addrTV;
    private String agentName;
    private String snippet;

    public InfoWinAdapter(Context context) {
        this.mContext = context;
    }

    @Override
    public View getInfoWindow(Marker marker) {
        initData(marker);
        View view = initView();
        return view;
    }

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

    private void initData(Marker marker) {
        latLng = marker.getPosition();
        snippet = marker.getSnippet();
        agentName = marker.getTitle();
    }

    @NonNull
    private View initView() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.view_infowindow, null);
        nameTV = view.findViewById(R.id.name);//名称
        addrTV = view.findViewById(R.id.addr);//地址
        navigation = view.findViewById(R.id.guide);//导航

        nameTV.setText(agentName);
        addrTV.setText(snippet);

        navigation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //导航
                guide();
            }
        });
        return view;
    }

}

设置infoWindow适配器及添加marker

adapter = new InfoWinAdapter(this);
// 添加marker
addMarkerToMap(latitude,longitude, nameCn, addressCn);
//酒店位置打点
private void addMarkerToMap(String latitude, String longitude, String title, String snippet) {
    aMap.setInfoWindowAdapter(adapter);
    latlng = new LatLng(Double.valueOf(latitude),
            Double.valueOf(longitude));
    Marker marker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
            .position(latlng)
            .title(title)
            .snippet(snippet)
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.location_mark))
            .draggable(true));
    marker.showInfoWindow();
}

隐藏infoWindow的方法:     marker.hideInfoWindow();

设置marker图标的方法:     marker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.location_mark));

5、关键词或者poi编码搜周边  页面需实现    PoiSearch.OnPoiSearchListener 接口

/**
 * 向高德发送模糊地址匹配的请求
 *
 * @param key       模糊匹配的关键字
 * @param cityName  模糊匹配的城市返回
 * @param Latitude  具体的地址纬度(当首页有具体地址再跳转过来的时候有值,其他时候默认为0)
 * @param Longitude 具体的地址经度(当首页有具体地址再跳转过来的时候有值,其他时候默认为0)
 */
private void getSearchQueryData(String key, String cityName, double Latitude, double Longitude) {
    // 第一个参数表示搜索字符串,第二个参数表示poi搜索类型,第三个参数表示poi搜索区域(空字符串代表全国)
    query = new PoiSearch.Query(key, "050000|190000", cityName);
    query.setPageSize(10);// 设置每页最多返回多少条poiItem
    query.setPageNum(curPage);// 设置查第当前页
    query.setCityLimit(true);
    query.setDistanceSort(true);//设置按照距离排序
    poiSearch = new PoiSearch(this, query);//PoiSearch高德模糊查询类
    if (Latitude != 0.0 && Longitude != 0.0) {
        poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(Latitude, Longitude), 5000));
    } else {
        poiSearch = new PoiSearch(this, query);
    }
    poiSearch.setOnPoiSearchListener(this);
    poiSearch.searchPOIAsyn();
}

/**
 * 高德模糊搜索回调
 *
 * @param result 返回的数据
 * @param rCode  返回码 1000代表成功其他都是错误码
 */
@Override
public void onPoiSearched(PoiResult result, int rCode) {
    if (rCode == AMapException.CODE_AMAP_SUCCESS) {
        if (result != null && result.getQuery() != null) {// 搜索poi的结果
            if (result.getQuery().equals(query)) {// 是否是同一条
                poiResult = result;
                totalPage = poiResult.getPageCount();//总共多少页
                poiItems.clear();
                // 取得搜索到的poiitems有多少页
                poiItems.addAll(result.getPois());// 取得第一页的poiItem数据
            }
        }
    } else {
        if (poiItems != null && poiItems.size() > 0) {
            poiItems.clear();
        }
    }
}

6、导航工具类  高德地图  百度地图  腾讯地图

/**
 * 检查手机上是否安装的指定的软件
 * @param context
 * @param packageName
 * @return
 */
public static boolean checkMapAppsIsExist(Context context, String packageName){
   //获取packagemanager
   final PackageManager packageManager = context.getPackageManager();
   //获取所有已安装程序的包信息
   List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
   //用于存储所有已安装程序的包名
   List<String> packageNames = new ArrayList<String>();
   //从pinfo中将包名字逐一取出,压入pName list中
   if(packageInfos != null){
      for(int i = 0; i < packageInfos.size(); i++){
         String packName = packageInfos.get(i).packageName;
         packageNames.add(packName);
      }
   }
   //判断packageNames中是否有目标程序的包名,有TRUE,没有FALSE
   return packageNames.contains(packageName);
}

/**
 * 获取手机中安装的所有地图app
 * @param context
 * @return
 */
public static List<String> getMapApps(Context context){
   List<String> appNames = new ArrayList<>();
   if(checkMapAppsIsExist(context, "com.autonavi.minimap")){
      appNames.add("高德地图");
   }
   if(checkMapAppsIsExist(context, "com.baidu.BaiduMap")){
      appNames.add("百度地图");
   }
   if(checkMapAppsIsExist(context, "com.tencent.map")){
      appNames.add("腾讯地图");
   }
   return appNames;
}

/**
 * 打开高德地图(公交出行,起点位置使用地图当前位置)
 *
 * t = 0(驾车)= 1(公交)= 2(步行)= 3(骑行)= 4(火车)= 5(长途客车)
 *
 * @param dlat  终点纬度
 * @param dlon  终点经度
 * @param dname 终点名称
 */
public static void openGaoDeMap(Context context, double dlat, double dlon, String dname) {
   if (checkMapAppsIsExist(context, "com.autonavi.minimap")) {
      Intent intent = new Intent(Intent.ACTION_VIEW);
      intent.setPackage("com.autonavi.minimap");
      intent.addCategory("android.intent.category.DEFAULT");
      intent.setData(Uri.parse("androidamap://route?sourceApplication=" + R.string.app_name
            + "&slat="+36.2+"&slon="+116.1
            + "&sname=我的位置&dlat=" + dlat
            + "&dlon=" + dlon
            + "&dname=" + dname
            + "&dev=0&m=0&t=1"));
      context.startActivity(intent);
   }
}

/**
 * 打开高德地图  指定起点、终点
 *
 * t = 0(驾车)= 1(公交)= 2(步行)= 3(骑行)= 4(火车)= 5(长途客车)
 *
 * @param slat  起点纬度
 * @param slon  起点经度
 * @param sname 起点名称
 * @param dlat  终点纬度
 * @param dlon  终点经度
 * @param dname 终点名称
 */
public static void openGaoDeMap(Context context, double slat, double slon, String sname,double dlat, double dlon, String dname) {
   if (checkMapAppsIsExist(context, "com.autonavi.minimap")) {
      Intent intent = new Intent(Intent.ACTION_VIEW);
      intent.setPackage("com.autonavi.minimap");
      intent.addCategory("android.intent.category.DEFAULT");
      intent.setData(Uri.parse("androidamap://route?sourceApplication=" + R.string.app_name
            + "&slat=" + slat
            + "&slon=" + slon
            + "&sname=" + sname
            + "&dlat=" + dlat
            + "&dlon=" + dlon
            + "&dname=" + dname
            + "&dev=0&m=0&t=1"));
      context.startActivity(intent);
   }
}

 /* 打开百度地图(公交出行,起点位置使用地图当前位置)
  *
  * mode = transit(公交)、driving(驾车)、walking(步行)和riding(骑行). 默认:driving
     * 当 mode=transit 时 : sy = 0:推荐路线 、 2:少换乘 、 3:少步行 、 4:不坐地铁 、 5:时间短 、 6:地铁优先
     *
  * @param dlat  终点纬度
     * @param dlon  终点经度
     * @param dname 终点名称
     */
public static void openBaiduMap(Context context, double dlat, double dlon, String dname) {
   if (checkMapAppsIsExist(context, "com.baidu.BaiduMap")) {
      Intent intent = new Intent(Intent.ACTION_VIEW);
      intent.setData(Uri.parse("baidumap://map/direction?origin=我的位置&destination=name:"
            + dname
            + "|latlng:" + dlat + "," + dlon
            + "&mode=transit&sy=3&index=0&target=1"));
      context.startActivity(intent);
   }
}

/* 打开百度地图  指定起点、终点
  *
  * mode = transit(公交)、driving(驾车)、walking(步行)和riding(骑行). 默认:driving
     * 当 mode=transit 时 : sy = 0:推荐路线 、 2:少换乘 、 3:少步行 、 4:不坐地铁 、 5:时间短 、 6:地铁优先
     *
     * @param slat  起点纬度
     * @param slon  起点经度
     * @param sname 起点名称
  * @param dlat  终点纬度
     * @param dlon  终点经度
     * @param dname 终点名称
     */
public static void openBaiduMap(Context context, double slat, double slon, String sname, double dlat, double dlon, String dname) {
   if (checkMapAppsIsExist(context, "com.baidu.BaiduMap")) {
      String uriString = null;
      double destination[] = gcj02_To_Bd09(dlat, dlon);
      dlat = destination[0];
      dlon = destination[1];
      StringBuilder builder = new StringBuilder("baidumap://map/direction?mode=driving&");
      if (slat != 0){
         double[] origin = gcj02_To_Bd09(slat, slon);
         slat = origin[0];
         slon = origin[1];
         builder.append("origin=latlng:")
               .append(slat)
               .append(",")
               .append(slon)
               .append("|name:")
               .append(sname);
      }
      builder.append("&destination=latlng:")
            .append(dlat)
            .append(",")
            .append(dlon)
            .append("|name:")
            .append(dname);
      uriString = builder.toString();
      Intent intent = new Intent(Intent.ACTION_VIEW);
      intent.setData(Uri.parse(uriString));
      context.startActivity(intent);
   }
}

/**
 * 打开腾讯地图(公交出行,起点位置使用地图当前位置)
 *
 * 公交:type=bus,policy有以下取值
 * 0:较快捷 、 1:少换乘 、 2:少步行 、 3:不坐地铁
 * 驾车:type=drive,policy有以下取值
 * 0:较快捷 、 1:无高速 、 2:距离短
 * policy的取值缺省为0
 *
 * @param dlat  终点纬度
 * @param dlon  终点经度
 * @param dname 终点名称
 */
public static void openTencent(Context context, double dlat, double dlon, String dname) {
   if (checkMapAppsIsExist(context, "com.tencent.map")) {
      Intent intent = new Intent(Intent.ACTION_VIEW);
      intent.setData(Uri.parse("qqmap://map/routeplan?type=bus&from=我的位置&fromcoord=0,0"
            + "&to=" + dname
            + "&tocoord=" + dlat + "," + dlon
            + "&policy=1&referer=myapp"));
      context.startActivity(intent);
   }
}

/**
 * 打开腾讯地图指定起点、终点
 *
 * 公交:type=bus,policy有以下取值
 * 0:较快捷 、 1:少换乘 、 2:少步行 、 3:不坐地铁
 * 驾车:type=drive,policy有以下取值
 * 0:较快捷 、 1:无高速 、 2:距离短
 * policy的取值缺省为0
 *
 * @param slat  起点纬度
 * @param slon  起点经度
 * @param sname 起点名称
 * @param dlat  终点纬度
 * @param dlon  终点经度
 * @param dname 终点名称
 */
public static void openTencent(Context context, double slat, double slon, String sname,double dlat, double dlon, String dname) {
   if (checkMapAppsIsExist(context, "com.tencent.map")) {
      Intent intent = new Intent(Intent.ACTION_VIEW);
      intent.setData(Uri.parse("qqmap://map/routeplan?type=bus&from="+sname
            + "&fromcoord=" + slat + "," + slon
            + "&to=" + dname
            + "&tocoord=" + dlat + "," + dlon
            + "&policy=1&referer=myapp"));
      context.startActivity(intent);
   }
}


private static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
/**
 * 高德 == 》 百度
 *
 * @param lat
 * @param lon
 */
public static double[] gcj02_To_Bd09(double lat, double lon) {
   double x = lon, y = lat;
   double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
   double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
   double tempLon = z * Math.cos(theta) + 0.0065;
   double tempLat = z * Math.sin(theta) + 0.006;
   double[] gps = {tempLat, tempLon};
   return gps;
}

/**
 * 百度 == 》 高德
 *
 * @param lat
 * @param lon
 */
public static double[] bd09_To_Gcj02(double lat, double lon) {
   double x = lon - 0.0065, y = lat - 0.006;
   double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
   double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
   double tempLon = z * Math.cos(theta);
   double tempLat = z * Math.sin(theta);
   double[] gps = {tempLat, tempLon};
   return gps;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在uniapp项目中接入高德地图,可以按照以下步骤进行操作: 1. 在高德开放平台申请应用并获取应用的AppKey。 2. 安装uni-app高德地图插件,可以通过uni-app官方插件市场或npm进行安装。 3. 在App.vue中引入高德地图插件,并初始化地图。 ```javascript <template> <view> <map :longitude="longitude" :latitude="latitude" :scale="scale" :markers="markers" :include-points="includePoints"></map> </view> </template> <script> import QQMapWX from '@/common/js/qqmap-wx-jssdk.min.js';//引入高德地图插件 export default { data() { return { longitude: 113.324520, latitude: 23.099994, scale: 14, markers: [], includePoints: [] }; }, onReady() { this.mapCtx = uni.createMapContext('map'); this.initMap(); }, methods: { //初始化地图 initMap() { let key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';//AppKey let qqmapsdk = new QQMapWX({ key: key }); qqmapsdk.reverseGeocoder({ success: res => { let { latitude, longitude } = res.result.location; this.longitude = longitude; this.latitude = latitude; this.markers.push({ id: 0, longitude: this.longitude, latitude: this.latitude, iconPath: "/static/img/map-marker.png", width: 30, height: 30 }); this.includePoints.push({ latitude: this.latitude, longitude: this.longitude }); } }); } } }; </script> ``` 4. 在manifest.json文件中配置高德地图插件的AppKey。 ```json { "mp-weixin": { "appid": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "miniprogramRoot": "pages", "plugins": { "myPlugin": { "version": "1.0.0", "provider": "wxid" }, "myOtherPlugin": { "version": "1.2.3", "provider": "wxid" }, "myAmap": { "version": "1.0.0", "provider": "wxid", "options": { "apiKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } } } } } ``` 这样就可以在uniapp项目中成功接入高德地图了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值