关于hms-core:实现地图实时定位拯救路痴

80次阅读

共计 6366 个字符,预计需要花费 16 分钟才能阅读完成。

实时定位,曾经成为利用必备能力之一,尤其是导航利用,更须要疾速精确定位用户实时地位。

华为定位服务可能赋予应用程序疾速、精准地获取用户地位信息的能力,同时定位服务助力寰球开发者实现个性化地图出现与交互,全面晋升利用的 LBS 体验。

上面为您具体解析,华为定位服务与地图服务如何实现利用实时定位。

预期性能

获取实时定位,并且在地图上显示地位点,首次启动跳转以后地位点,并且地位扭转以后地位点和地图视角随之扭转。

应用能力

华为定位服务: 根底定位

华为地图服务:地图显示

实现原理
应用华为定位服务获取实时地位,在地图上显示“我的地位”按钮,在地位变动时,跳转地图到以后定位。

筹备工作

AGC 账号注册,我的项目创立

  1. 注册成为开发者

注册地址:

https://developer.huawei.com/…

  1. 创立利用,增加 sha256,开启 map/site 开关,下载 json 文件

https://developer.huawei.com/…

  1. 配置 android studio 工程

1) 将“agconnect-services.json”文件拷贝到利用级根目录下

· 在“allprojects > repositories”中配置 HMS Core SDK 的 Maven 仓地址。

· 在“buildscript > repositories”中配置 HMS Core SDK 的 Maven 仓地址。

· 如果 App 中增加了“agconnect-services.json”文件则须要在“buildscript > dependencies”中减少 agcp 配置。

buildscript {
    repositories {maven { url 'https://developer.huawei.com/repo/'}
        google()
        jcenter()}
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.2'
        classpath 'com.huawei.agconnect:agcp:1.3.1.300'
    }
}

allprojects {
    repositories {maven { url 'https://developer.huawei.com/repo/'}
        google()
        jcenter()}
}

2) 在“dependencies”中增加如下编译依赖

dependencies {implementation 'com.huawei.hms:maps:{version}'
    implementation 'com.huawei.hms:location:{version}'
}

3) 在文件头增加配置
apply plugin: 'com.huawei.agconnect'

4) 在 android 中配置签名。将生成签名证书指纹生成的签名文件复制到您工程的 app 目录下,并在“build.gradle”文件中配置签名

signingConfigs {
    release {
        // 签名证书
            storeFile file("**.**")
            // 密钥库口令
            storePassword "******"
            // 别名
            keyAlias "******"
            // 密钥口令
            keyPassword "******"
            v2SigningEnabled true
        v2SigningEnabled true
    }
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        debuggable true
    }
    debug {debuggable true}
}

要害代码实现
1) 编写一个 service 获取实时定位。

public class LocationService extends Service {private final String TAG = this.getClass().getSimpleName();

    List<ILocationChangedLister> locationChangedList = new ArrayList<>();

    // location
    private FusedLocationProviderClient fusedLocationProviderClient;

    private LocationRequest mLocationRequest;

    private final LocationCallback mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {super.onLocationResult(locationResult);
            locationResult.getLocations();
            Log.d(TAG, "onLocationResult:" + locationResult);
            Location location = locationResult.getLocations().get(0);
            Log.w(TAG, "onLocationResult:Latitude" + location.getLatitude());
            Log.w(TAG, "onLocationResult:Longitude" + location.getLongitude());

            for (ILocationChangedLister locationChanged : locationChangedList) {locationChanged.locationChanged(new LatLng(location.getLatitude(), location.getLongitude()));
            }
        }

        @Override
        public void onLocationAvailability(LocationAvailability locationAvailability) {super.onLocationAvailability(locationAvailability);
            Log.d(TAG, "onLocationAvailability:" + locationAvailability.toString());
        }
    };

    private final MyBinder binder = new MyBinder();

    private final Random generator = new Random();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {return binder;}

    @Override
    public void onCreate() {Log.i("DemoLog", "TestService -> onCreate, Thread:" + Thread.currentThread().getName());
        super.onCreate();}

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("DemoLog",
            "TestService -> onStartCommand, startId:" + startId + ", Thread:" + Thread.currentThread().getName());
        return START_NOT_STICKY;
    }

    @Override
    public boolean onUnbind(Intent intent) {Log.i("DemoLog", "TestService -> onUnbind, from:" + intent.getStringExtra("from"));
        return false;
    }

    @Override
    public void onDestroy() {Log.i("DemoLog", "TestService -> onDestroy, Thread:" + Thread.currentThread().getName());
        super.onDestroy();}

    public int getRandomNumber() {return generator.nextInt();
    }

    public void addLocationChangedlister(ILocationChangedLister iLocationChangedLister) {locationChangedList.add(iLocationChangedLister);
    }

    public void getMyLoction() {Log.d(TAG, "getMyLoction:");
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        SettingsClient settingsClient = LocationServices.getSettingsClient(this);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        mLocationRequest = new LocationRequest();
        builder.addLocationRequest(mLocationRequest);
        LocationSettingsRequest locationSettingsRequest = builder.build();
        // location setting
        settingsClient.checkLocationSettings(locationSettingsRequest)
            .addOnSuccessListener(locationSettingsResponse -> fusedLocationProviderClient
                .requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper())
                .addOnSuccessListener(aVoid -> Log.d(TAG, "onSuccess:" + aVoid)))
            .addOnFailureListener(Throwable::printStackTrace);
    }

    public class MyBinder extends Binder {public LocationService getService() {return LocationService.this;}
    }

    public interface ILocationChangedLister {

        /**
         * Update the location information
         *
         * @param latLng The new location information
         */
        public void locationChanged(LatLng latLng);
    }

}

2) 在 Activity 中绘制地图,监听实时地位

Xml 中增加地图:

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

activity 地图绘制:

mapView.onCreate(null);
mapView.getMapAsync(this);

绘制是关上我的地位 按钮显示

@Override
public void onMapReady(HuaweiMap huaweiMap) {
    hMap = huaweiMap;
    hMap.setMyLocationEnabled(true);
}

设置定位服务绑定监听

private ServiceConnection conn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        isBound = true;
        if (binder instanceof LocationService.MyBinder) {LocationService.MyBinder myBinder = (LocationService.MyBinder) binder;
            locationService = myBinder.getService();
            Log.i(TAG, "ActivityA onServiceConnected");
            locationService.addLocationChangedlister(iLocationChangedLister);
            locationService.getMyLoction();}
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        isBound = false;
        locationService = null;
        Log.i(TAG, "ActivityA onServiceDisconnected");
    }
};

绑定到 LocationService:

private void bindLocationService() {Intent intent = new Intent(mActivity, LocationService.class);
    intent.putExtra("from", "ActivityA");
    Log.i(TAG, "-------------------------------------------------------------");
    Log.i(TAG, "bindService to ActivityA");
    mActivity.bindService(intent, conn, Context.BIND_AUTO_CREATE);
}

在地位变动监听中解决 地位扭转

LocationService.ILocationChangedLister iLocationChangedLister = new LocationService.ILocationChangedLister() {
    @Override
    public void locationChanged(LatLng latLng) {Log.d(TAG, "locationChanged:" + latLng.latitude);
        Log.d(TAG, "locationChanged:" + latLng.longitude);
        updateLocation(latLng);
    }
};

更新地图 经纬度视角

private void updateLocation(LatLng latLng) {
    mLatLng = latLng;
    hMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 1));
}

测试
应用模仿地位软件扭转模仿地位,地图视角和我的地位按钮能够随之跳动。性能实现。

欲了解 HMS Core 更多详情,请参阅:
华为开发者联盟官网
获取开发领导文档
参加开发者探讨请到 CSDN 社区或者 Reddit 社区
下载 demo 和示例代码请到 Github 或者 Gitee
解决集成问题请到 Stack Overflow

原文链接:https://developer.huawei.com/…
原作者:HMS Core 官网帐号

正文完
 0