在Fragment中显示高德地图

一、首先在高德官网上申请key

  • 第一步:按照规定填写Key名称
  • 第二步:选择服务平台,运用在android上就勾选anroid就好了
  • 第三步:输入发布版安全码SHA1
    • 首先打开命令行按住windows+r两个按键
    • 在命令行中输入cd .android,定位到.android文件下
    • 调试版本使用 debug.keystore,命令为:keytool -list -v -keystore debug.keystore 发布版本使用 apk 对应的 keystore,命令为:keytool -list -v -keystore apk的keystore 如下所示:
    • 默认密钥库口令是:android
  • 第四步:输入PackageName:通常在清单文件的开头会有app的包名。
  • 第五步:点击确定就会生成一key

二、在Fragment中的运用

1.首先引入高德地图的依赖

XML 复制代码
//3D地图so及jar
    implementation 'com.amap.api:3dmap:latest.integration'

2.在清单文件中写如下代码

XML 复制代码
        <meta-data android:name="com.amap.api.v2.apikey" android:value="你的自己的key"/>
<service android:name="com.amap.api.location.APSService" />

3.在清单文件中申明权限

XML 复制代码
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

4.新建Fragment

java 复制代码
import static com.amap.api.location.AMapLocationClient.updatePrivacyAgree;
import static com.amap.api.location.AMapLocationClient.updatePrivacyShow;

import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

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.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.ear.ams.ui.baseActivity.BaseFragment;
import com.ear.ams.ui.baseActivity.BaseFragmentTitleBarListener;
import com.ear.ams.ui.functionpage.distinguish.ModifyWarehouseDetialViewModel;
import com.ear.ams.ui.functionpage.distinguish.WarehouseChipDetialViewModel;
import com.ear.ams.util.loginUtil.LoginUtil;
import com.ear.ams_android.databinding.FragmentDetailedMapBinding;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;

public class DetailedMapFragment extends BaseFragment implements AMapLocationListener {

    private DetailedMapViewModel viewModel;
    private FragmentDetailedMapBinding binding;
    private MapView mapView;
    private AMap aMap;
    private AMapLocationClient locationClient;
    private Marker centerMarker;


    public static DetailedMapFragment newInstance() {
        return new DetailedMapFragment();
    }

    @Override
    public void onStart() {
        super.onStart();
        setTitle("位置");
        }

    }

    private String a;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewModel = new ViewModelProvider(this).get(DetailedMapViewModel.class);
        initListener();
        setTitleBarListener(new BaseFragmentTitleBarListener() {
            @Override
            public void onRightClick() {
                if (centerMarker != null) {
                    LatLng position = centerMarker.getPosition();
                    viewModel.latDL.setValue(position.latitude);
                    viewModel.lngDL.setValue(position.longitude);
                    Toast.makeText(getActivity(), "您选择的位置是: Lat=" + position.latitude + ", Lon=" + position.longitude, Toast.LENGTH_SHORT).show();
                }
                viewModel.selectSuccessfulLD.setValue(true);
            }
        });

    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        if (binding == null) {
            binding = FragmentDetailedMapBinding.inflate(inflater, container, false);
            binding.setViewModel(viewModel);
            binding.setLifecycleOwner(this);
            updatePrivacyShow(getContext(), true, true);
            updatePrivacyAgree(getContext(), true);
            mapView = binding.map;
            mapView.onCreate(savedInstanceState);
            if (aMap == null) {
                aMap = mapView.getMap();
            }
            try {
                setupLocation();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            // 初始化中心标记
            centerMarker = null;
            aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
                @Override
                public void onMapLoaded() {
                    // 地图加载完成后,将中心标记添加到地图中心
                    LatLng center = aMap.getCameraPosition().target;
                    MarkerOptions markerOptions = new MarkerOptions();
                    markerOptions.position(center);
                    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                    centerMarker = aMap.addMarker(markerOptions);
                    // 监听地图移动事件以更新中心标记的位置
                    aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
                        @Override
                        public void onCameraChange(CameraPosition cameraPosition) {
                            if (centerMarker != null) {
                                centerMarker.setPosition(cameraPosition.target);
                            }
                        }

                        @Override
                        public void onCameraChangeFinish(CameraPosition cameraPosition) {
                            // 可以选择在这里添加额外的处理
                        }
                    });

                }
            });

        }

        View root = binding.getRoot();
        return root;
    }

    private void setupLocation() throws Exception {
        locationClient = new AMapLocationClient(getActivity().getApplicationContext());
        locationClient.setLocationListener(this);
        AMapLocationClientOption locationOption = new AMapLocationClientOption();
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        locationClient.setLocationOption(locationOption);
        locationClient.startLocation();
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {//这里为Fragment的视图设置了一个键盘监听器。当用户在键盘上按下一个键时,这个监听器会被触发。
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_UP) {
                    LoginUtil.getInstance().setFlag("0");
                }
                return false;
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
        // 如果需要停止定位服务,可以在这里调用locationClient.stopLocation();
        locationClient.stopLocation();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mapView.onDestroy();
        if (null != locationClient) {
            locationClient.onDestroy();
            locationClient = null;
        }
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {

    }

    AMapLocation aMapLocation;
    private boolean isCurrentLocationMarkerAdded = false;
    private void initListener() {
        viewModel.selectSuccessfulLD.observe(this, a1 -> {
            new XPopup.Builder(getContext()).dismissOnBackPressed(false).dismissOnTouchOutside(false).asConfirm("提示", "选择成功!", null, "确定", new OnConfirmListener() {
                @Override
                public void onConfirm() {
                    if (a.equals("3")) {
                        LoginUtil.getInstance().setlat3(String.valueOf(viewModel.latDL.getValue()));
                        LoginUtil.getInstance().setlng3(String.valueOf(viewModel.lngDL.getValue()));
                    } else if (a.equals("2")) {
                        LoginUtil.getInstance().setlat2(String.valueOf(viewModel.latDL.getValue()));
                        LoginUtil.getInstance().setlng2(String.valueOf(viewModel.lngDL.getValue()));
                    }
                    popBackFragment();
                }
            }, null, true).show();
        });
        viewModel.getIsLoadingLD().observe(this, result -> {
            if (viewModel.latDL.getValue()==0.0) {
                if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                    LatLng latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
                    // 检查是否已经添加了当前位置的标记
                    if (!isCurrentLocationMarkerAdded) {
                        MarkerOptions markerOptions = new MarkerOptions();
                        markerOptions.position(latLng);
                        markerOptions.title("当前位置");

                        if (centerMarker != null) {
                            centerMarker.setPosition(latLng);
                            centerMarker.setTitle("当前位置");
                        } else {
                            centerMarker = aMap.addMarker(markerOptions);
                            isCurrentLocationMarkerAdded = true; // 标记已添加
                        }
                    } else {
                        // 如果已经添加了当前位置的标记,则只需更新其位置
                        if (centerMarker != null) {
                            centerMarker.setPosition(latLng);
                        }
                    }
                }
            } else {
                double latitude = viewModel.latDL.getValue();
                double longitude = viewModel.lngDL.getValue();
                LatLng latLng = new LatLng(latitude, longitude);
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));

                // 更新中心标记的位置和标题(如果它存在的话)
                if (centerMarker != null) {
                    centerMarker.setPosition(latLng);
                    centerMarker.setTitle(viewModel.warehouseNameLD.getValue());
                } else {
                    MarkerOptions markerOptions = new MarkerOptions();
                    markerOptions.position(latLng);
                    markerOptions.title(viewModel.warehouseNameLD.getValue());
                    centerMarker = aMap.addMarker(markerOptions);
                }
            }
        });

    }
}

对应的布局文件

XML 复制代码
<?xml version="1.0" encoding="utf-8"?>
<layout>

    <data>

        <variable
            name="viewModel"
            type="com.ear.ams.ui.functionpage.warehousemanagement.DetailedMapViewModel" />
    </data>

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.ear.ams.ui.functionpage.warehousemanagement.DetailedMapFragment">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <com.amap.api.maps.MapView
                    android:id="@+id/map"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />

            </RelativeLayout>
        </androidx.constraintlayout.widget.ConstraintLayout>

    </FrameLayout>
</layout>

三、运行结果

可以在地图上选择位置并获取经纬度,在地图的中心点有一个红色的图标通过滑动图标实现位置选择。

相关推荐
帅得不敢出门10 小时前
安卓设备adb执行AT指令控制电话卡
android·adb·sim卡·at指令·电话卡
我又来搬代码了12 小时前
【Android】使用productFlavors构建多个变体
android
德育处主任13 小时前
Mac和安卓手机互传文件(ADB)
android·macos
芦半山13 小时前
Android“引用们”的底层原理
android·java
迃-幵14 小时前
力扣:225 用队列实现栈
android·javascript·leetcode
大风起兮云飞扬丶14 小时前
Android——从相机/相册获取图片
android
Rverdoser14 小时前
Android Studio 多工程公用module引用
android·ide·android studio
aaajj15 小时前
[Android]从FLAG_SECURE禁止截屏看surface
android
@OuYang15 小时前
android10 蓝牙(二)配对源码解析
android
Liknana15 小时前
Android 网易游戏面经
android·面试