entry/src/main/ets/pages/Sign.ets
import { router } from '@kit.ArkUI';
import { MapComponent, mapCommon, map } from '@kit.MapKit';
import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
import { geoLocationManager } from '@kit.LocationKit';
import { abilityAccessCtrl, common, Permissions } from '@kit.AbilityKit';
import { JSON } from '@kit.ArkTS';
@Entry
@Component
struct Sign {
private mapOption?: mapCommon.MapOptions;
private TAG = "HuaweiMapDemo";
private callback?: AsyncCallback<map.MapComponentController>;
private mapController?: map.MapComponentController;
@State placeName:string = ''
// Marker mMarker = null;
// 用户是否开启定位权限
reqPermissionsFromUser(permissions: Array<Permissions>) {
let context = getContext(this) as common.UIAbilityContext; //获取去上下文实例
let atManager = abilityAccessCtrl.createAtManager();
return atManager.requestPermissionsFromUser(context, permissions).then((res) => {
let grantStatus: Array<number> = res.authResults;
let length: number = grantStatus.length;
let str: boolean = true
for (let index = 0; index < length; index++) {
if (grantStatus[index] === 0) {
str = true
} else {
str = false
}
}
return str
}).catch((err: string) => {
})
}
onPageShow(): void {
// 绘制地图页面的生命周期onPageShow,将地图切换到前台
if (this.mapController !== undefined) {
this.mapController.show();
}
}
aboutToAppear() {
this.mapOption = {
position: {
target: {
latitude:30.495350,
longitude: 114.414917
},
zoom: 16
},
zoomControlsEnabled: false, //取消缩放按钮
myLocationControlsEnabled: true, //支持定位按钮
};
// 地图初始化的回调
this.callback = (err, mapController) => {
if (!err) {
// 获取地图的控制器类,用来操作地图
this.mapController = mapController;
this.mapController?.setMyLocationEnabled(true);
this.mapController.on("mapLoad", () => {
});
}
};
}
onBackPress(){
this.colesMonitorLocation()
}
openMonitorLocation(marker:map.Marker|undefined){
let request : geoLocationManager.ContinuousLocationRequest = {
'interval': 0,
'locationScenario': geoLocationManager.UserActivityScenario.SPORT
}
let locationCallback = (location: geoLocationManager.Location): void => {
marker?.setRotation(location.direction);//设置旋转角度
// console.log('xuchen','定位信息111:' + JSON.stringify(location));
// console.log('xuchen','定位信息2222:' + JSON.stringify(location.direction));
};
geoLocationManager.on('locationChange', request, locationCallback);
}
aboutToDisappear(){
this.colesMonitorLocation()
}
colesMonitorLocation(){
geoLocationManager.off('locationChange')
}
openMarkerDrag (){
this.mapController?.on("markerDragEnd",(marker)=>{
// if(marker){
this.placeName = marker.getTitle()
console.log('xuchen',marker.getTitle(),JSON.stringify(marker.getPosition()));
// }
this.mapController?.off("markerDragEnd",()=>{ })
})
// this.mapController?.off("markerDragEnd",(marker)=>{
// console.log('xuchen',JSON.stringify(marker.getTitle()))
// })
}
Shuaxin (){
this.placeName = ''
this.mapController?.clear();
this.mapController?.setMyLocationEnabled(false);
this.colesMonitorLocation()//关闭监听
}
// marker.setRotation(30);//设置旋转角度
//线
addPolyline(){
let polylineOption: mapCommon.MapPolylineOptions = {
// 折线坐标点,必传
points: [
{ latitude: 30.477095, longitude: 114.40226 },
{ latitude: 30.476943, longitude: 114.401742 },
{ latitude:30.476696, longitude: 114.402559 },
{ latitude:30.476584, longitude: 114.401709 },
{ latitude:30.476384, longitude: 114.402206 },
],
clickable: true,
color: 0xff000000,
startCap: mapCommon.CapStyle.BUTT,
endCap: mapCommon.CapStyle.BUTT,
geodesic: false,
jointType: mapCommon.JointType.DEFAULT,
visible: true,
width: 10,
zIndex: 0,
gradient: false
};
this.mapController?.addPolyline(polylineOption);
}
addPolygon(){
let polygonOptions: mapCommon.MapPolygonOptions = {
// 多边形坐标点,必传
points: [
{latitude: 30.476836, longitude: 114.401139 },
{latitude: 30.476976, longitude:114.40091},
{latitude: 30.477179, longitude:114.400985},
{latitude: 30.477078, longitude: 114.401541 },
{latitude: 30.476772, longitude: 114.401833 },
{latitude: 30.476641, longitude:114.40128 },
{latitude: 30.476437, longitude: 114.401649 },
{latitude: 30.476259, longitude: 114.401398 },
{latitude: 30.476836, longitude: 114.401139 },
],
clickable: true,//是否可点击
fillColor: 0xff00DE00,//填充色
geodesic: false,
strokeColor: 0xff000000,
jointType: mapCommon.JointType.DEFAULT,//拐角样式
strokeWidth: 10,
visible: true,
zIndex: 10
};
this.mapController?.addPolygon(polygonOptions)
}
async getLocation() {
//询问用户是否开启权限
let status = await this.reqPermissionsFromUser(['ohos.permission.LOCATION', 'ohos.permission.APPROXIMATELY_LOCATION']);
if (status) {
try {
let location = await geoLocationManager.getCurrentLocation()
this.mapController?.setMyLocation(location);//地图缩放到指定的位置
this.mapController?.animateCamera(map.newLatLng({
latitude:location.latitude,
longitude: location.longitude
},18), 200);
this.addPolyline()//添加线
this.addPolygon()//添加多边形
geoLocationManager.getAddressesFromLocation(location, async (err, data) => { //用户的当前信息转换为文字描述
console.log('xuchen','111'+JSON.stringify(data));
if (data) {
let result:ESObject = JSON.parse(JSON.stringify(data[0]))
// let style: mapCommon.MyLocationStyle = {
// anchorU: 0.5,
// anchorV: 0.5,
// radiusFillColor: 0x00ff0000,
// // icon为自定义图标资源,使用时需要替换,图标存放在resources/rawfile
// icon: $r('app.media.locate_icon'),
// displayType:mapCommon.MyLocationDisplayType.FOLLOW
// };
// this.mapController?.setMyLocationStyle(style);
this.mapController?.setMyLocationEnabled(false);
let markerOptions: mapCommon.MarkerOptions = {
position:{
latitude: result.latitude,
longitude: result.longitude
},
draggable:true,
title: result.placeName,
clickable: true,
icon: $r('app.media.flow_locate_icon'),
};
let marker:map.Marker|undefined = await this.mapController?.addMarker(markerOptions)
this.openMonitorLocation(marker);
this.openMarkerDrag()
this.placeName = result.placeName
}
})
} catch (err) {
console.error("xuchen", '3331' + JSON.stringify(err));
}
}
}
build() {
Column() {
Row() {
Row() {
Image($r('app.media.back'))
.width(14)
.height(24)
.fillColor('#fff')
Text('首页')
.margin({ left: 6 })
.fontSize(12)
.fontColor('#fff')
}
.onClick(() => {
router.back({
url: 'pages/MusicInfo'
})
})
Text('签到')
.fontSize('20')
.fontColor('#fff')
Image($r('app.media.shuaxin'))
.fillColor('#fff')
.width(30)
.height(30)
.onClick(()=>{
this.Shuaxin()
})
}
.padding({ left: 10, right: 10 })
.width('100%')
.height(60)
.backgroundColor('#5b73de')
.justifyContent(FlexAlign.SpaceBetween)
MapComponent({ mapOptions: this.mapOption, mapCallback: this.callback })
.width('100%')
.height('100%');
if(this.placeName){
Row() {
Text(this.placeName)
.fontSize(20)
.fontColor('#fff')
}
.width('100%')
.height(60)
.backgroundColor(Color.Pink)
.margin({ left: 10, right: 10 })
.position({ top: 70 })
}
// Blank()
Row() {
Text('签到')
.textAlign(TextAlign.Center)
.fontSize(26)
.fontColor('#fff')
.height(100)
.width(100)
.borderRadius(50)
.backgroundColor('#75c0d7')
}
.onClick(() => {
this.getLocation()
})
.justifyContent(FlexAlign.Center)
.width('100%')
.zIndex(10)
.position({ bottom: 10 })
.margin({ bottom: 10 })
}
.backgroundColor(Color.Pink)
.height('100%')
.width('100%')
}
}
entry/src/main/module.json5
{
"module": {
"name": "entry",
"type": "entry",
"description": "$string:module_desc",
"mainElement": "EntryAbility",
"deviceTypes": [
"phone",
"tablet",
"2in1"
],
"deliveryWithInstall": true,
"installationFree": false,
"pages": "$profile:main_pages",
"abilities": [
{
"name": "EntryAbility",
"srcEntry": "./ets/entryability/EntryAbility.ets",
"description": "$string:EntryAbility_desc",
"icon": "$media:layered_image",
"label": "$string:EntryAbility_label",
"startWindowIcon": "$media:startIcon",
"startWindowBackground": "$color:start_window_background",
"exported": true,
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"action.system.home"
]
}
]
}
],
"extensionAbilities": [
{
"name": "EntryBackupAbility",
"srcEntry": "./ets/entrybackupability/EntryBackupAbility.ets",
"type": "backup",
"exported": false,
"metadata": [
{
"name": "ohos.extension.backup",
"resource": "$profile:backup_config"
}
],
}
],
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
},
{
"name": "ohos.permission.LOCATION", // 权限名称,为系统已定义的权限
"reason": "$string:location_reason", // 申请权限的原因,当申请权限为user_grant权限时该字段为必填
"usedScene": { // 用于描述权限使用场景,当申请权限为user_grant权限时该字段为必填
"abilities": [
"EntryAbility"
],
"when": "always" // 调用时机(inuse:使用时;always:始终)
}
},
{
"name": "ohos.permission.APPROXIMATELY_LOCATION",
"reason": "$string:location_reason",
"usedScene": {
"abilities": [
"EntryAbility"
],
"when": "always"
}
}
]
}
}