鸿蒙HarmonyOS 地图定位到当前位置 site查询等操作

news2024/11/19 4:08:21

应用服务Map使用 地图定位 地点查询及导航 周边查询 点位标记定义等

地图定位 

前提地图已经能正常显示,若不能显示请大家参考之前的那篇如何显示地图的博文

地图相关的api  

位置效果图:

 module.json5配置权限

"requestPermissions": [
      {
        "name": "ohos.permission.LOCATION",
        "reason": "$string:dependency_reason",
        "usedScene": {
          "abilities": [
            "EntryAbility"
          ],
          "when": "always"
        }
      },
      {
        "name": "ohos.permission.APPROXIMATELY_LOCATION",
        "reason": "$string:dependency_reason",
        "usedScene": {
          "abilities": [
            "EntryAbility"
          ],
          "when": "always"
        }
      },
      {
        "name": "ohos.permission.LOCATION_IN_BACKGROUND",
        "reason": "$string:dependency_reason",
        "usedScene": {
          "abilities": [
            "EntryAbility"
          ],
          "when": "always"
        }
      },
      {
        "name": "ohos.permission.INTERNET",
        "reason": "$string:dependency_reason",
        "usedScene": {
          "when": "always"
        }
      },
      {
        "name": "ohos.permission.GET_NETWORK_INFO",
        "reason": "$string:dependency_reason",
        "usedScene": {
          "when": "always"
        }
      },
      {
        "name": "ohos.permission.CAMERA",
        "reason": "$string:dependency_reason",
        "usedScene": {
          "abilities": [
            "EntryAbility"
          ],
          "when": "always"
        }
      }
    ]

确认在AGC中已配置地图权限 这里就不截图了!

MapUtil.ets

地图相关的代码 logger文件若无用则可以删除

import { map, mapCommon, navi } from '@kit.MapKit';
import { geoLocationManager } from '@kit.LocationKit';
import { abilityAccessCtrl, bundleManager, Permissions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import Logger from './Logger';

export class MapUtil {
  public static initializeMapWithLocation(mapController: map.MapComponentController): void {
    mapController?.setMyLocationEnabled(true);
    mapController?.setMyLocationControlsEnabled(true);
    let requestInfo: geoLocationManager.CurrentLocationRequest = {
      'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX,
      'scenario': geoLocationManager.LocationRequestScenario.UNSET,
      'maxAccuracy': 0
    };
    geoLocationManager.getCurrentLocation(requestInfo).then(async (result) => {
      let mapPosition: mapCommon.LatLng =
        await map.convertCoordinate(mapCommon.CoordinateType.WGS84, mapCommon.CoordinateType.GCJ02, result);
      AppStorage.setOrCreate('longitude', mapPosition.longitude);
      AppStorage.setOrCreate('latitude', mapPosition.latitude);
      let cameraPosition: mapCommon.CameraPosition = {
        target: mapPosition,
        zoom: 15,
        tilt: 0,
        bearing: 0
      };
      let cameraUpdate = map.newCameraPosition(cameraPosition);
      mapController?.moveCamera(cameraUpdate);
    })
  }

  public static async walkingRoutes(position: mapCommon.LatLng, myPosition?: mapCommon.LatLng) {
    let params: navi.RouteParams = {
      origins: [myPosition!],
      destination: position,
      language: 'zh_CN'
    };
    try {
      const result = await navi.getWalkingRoutes(params);
      Logger.info('naviDemo', 'getWalkingRoutes success result =' + JSON.stringify(result));
      return result;
    } catch (err) {
      Logger.error('naviDemo', 'getWalkingRoutes fail err =' + JSON.stringify(err));
    }
    return undefined;
  }

  public static async paintRoute(routeResult: navi.RouteResult, mapPolyline?: map.MapPolyline,
    mapController?: map.MapComponentController) {
    mapPolyline?.remove();
    let polylineOption: mapCommon.MapPolylineOptions = {
      points: routeResult.routes[0].overviewPolyline!,
      clickable: true,
      startCap: mapCommon.CapStyle.BUTT,
      endCap: mapCommon.CapStyle.BUTT,
      geodesic: false,
      jointType: mapCommon.JointType.BEVEL,
      visible: true,
      width: 20,
      zIndex: 10,
      gradient: false,
      color: 0xFF2970FF
    }
    mapPolyline = await mapController?.addPolyline(polylineOption);
  }

  public static async addMarker(position: mapCommon.LatLng,
    mapController?: map.MapComponentController): Promise<map.Marker | undefined> {
    let markerOptions: mapCommon.MarkerOptions = {
      position: position,
      rotation: 0,
      visible: true,
      zIndex: 0,
      alpha: 1,
      anchorU: 0.35,
      anchorV: 1,
      clickable: true,
      draggable: true,
      flat: false
    };
    return await mapController?.addMarker(markerOptions);
  }

  public static async checkPermissions(mapController?: map.MapComponentController): Promise<boolean> {
    const permissions: Permissions[] = ['ohos.permission.LOCATION', 'ohos.permission.APPROXIMATELY_LOCATION'];
    for (let permission of permissions) {
      let grantStatus: abilityAccessCtrl.GrantStatus = await MapUtil.checkAccessToken(permission);
      if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
        mapController?.setMyLocationEnabled(true);
        mapController?.setMyLocationControlsEnabled(true);
        return true;
      }
    }
    return false;
  }

  public static async checkAccessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
    let grantStatus: abilityAccessCtrl.GrantStatus = abilityAccessCtrl.GrantStatus.PERMISSION_DENIED;

    let tokenId: number = 0;
    try {
      let bundleInfo: bundleManager.BundleInfo =
        await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
      let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
      tokenId = appInfo.accessTokenId;
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      Logger.error(`Failed to get bundle info for self. Code is ${err.code}, message is ${err.message}`);
    }
    try {
      grantStatus = await atManager.checkAccessToken(tokenId, permission);
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      Logger.error(`Failed to check access token. Code is ${err.code}, message is ${err.message}`);
    }

    return grantStatus;
  }
}

 Map.ets

import { MapComponent, mapCommon, map , sceneMap,site} from '@kit.MapKit';
import { geoLocationManager } from '@kit.LocationKit';
import { AsyncCallback ,BusinessError} from '@kit.BasicServicesKit';
import { abilityAccessCtrl,common } from '@kit.AbilityKit';
import { JSON } from '@kit.ArkTS';
import { http } from '@kit.NetworkKit';
import Logger from '../utils/Logger';

import { MapUtil } from '../utils/MapUtil';
interface testListType {
  name: string;
  latitude: string | number,
  longitude: string | number,
  color:string
}


@Entry
@Component
export  struct Map {
  private TAG = "HuaweiMapDemo";
  private mapOptions?: mapCommon.MapOptions;
  private callback?: AsyncCallback<map.MapComponentController>;
  private mapController?: map.MapComponentController;
  private mapEventManager?: map.MapEventManager;
  private marker?: map.Marker;
  // 重庆
  // @State longitude:number = 106.45952
  // @State latitude:number = 29.567283
  // 北京
  @State longitude:number = 116.4
  @State latitude:number = 39.9
  @State testList:testListType[] = []



aboutToAppear(): void {
  console.log('result0', 'result0')
    let http1 = http.createHttp();
// 替换成大家公司自己的接口地址
    let responseResult = 
http1.request('xxxxx/water/app/estuary/listRhpwk?typeId=13&riverId=1', {
      method: http.RequestMethod.GET,
      header: {
        'Content-Type': 'application/json'
      },
      readTimeout: 20000,
      connectTimeout: 10000
    });
    responseResult.then((value: http.HttpResponse) => {
      let res = JSON.stringify(value)
      let result = `${value.result}`;
      let resCode = `${value.code}`
      console.log('result1', result)

      // let resultObj: Object = JSON.parse(result)
      let resultObj: object = JSON.parse(result) as object
      console.log('result2', JSON.stringify(resultObj['data']))
      this.testList = resultObj['data']
    }).catch(() => {
    })

    // 地图初始化参数,设置地图中心点坐标及层级
    this.mapOptions = {
      position: {
        target: {
          latitude: this.latitude,
          longitude: this.longitude
        },
        zoom: 10
      },
      mapType: mapCommon.MapType.STANDARD
    };

    // 地图初始化的回调
    this.callback = async (err, mapController) => {
      if (!err) {
        // 获取地图的控制器类,用来操作地图
        this.mapController = mapController;
        this.mapEventManager = this.mapController.getEventManager();
        let callback = () => {
          console.info(this.TAG, `on-mapLoad`);
        }
        this.mapEventManager.on("mapLoad", callback);


        //确认是否已配置权限(AGC中配置) 无权限则拉起位置
        let hasPermissions = await MapUtil.checkPermissions(this.mapController);
        console.log('hasPermissions==>',hasPermissions)
        if (!hasPermissions) {
          this.requestPermissions();
        }
        if (hasPermissions) {
          let requestInfo: geoLocationManager.CurrentLocationRequest = {
            'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX,
            'scenario': geoLocationManager.LocationRequestScenario.UNSET,
            'maxAccuracy': 0
          };
          let locationChange = async (): Promise<void> => {
          };
          geoLocationManager.on('locationChange', requestInfo, locationChange);
          // 获取当前用户位置
          geoLocationManager.getCurrentLocation(requestInfo).then(async (result) => {
            let mapPosition: mapCommon.LatLng =
              await map.convertCoordinate(mapCommon.CoordinateType.WGS84, mapCommon.CoordinateType.GCJ02, result);
            AppStorage.setOrCreate('longitude', mapPosition.longitude);
            AppStorage.setOrCreate('latitude', mapPosition.latitude);
            console.log('longitude==>',mapPosition.latitude,mapPosition.longitude)
            // 飞入 类似setView flyTo camera
            let cameraPosition: mapCommon.CameraPosition = {
              target: mapPosition,
              zoom: 15,
              tilt: 0,
              bearing: 0
            };
            let cameraUpdate = map.newCameraPosition(cameraPosition);
            mapController?.animateCamera(cameraUpdate, 1000);
          })
        }


       


        //点击事件
        let callback1 = (position: mapCommon.LatLng) => {
          console.info("mapClick", `on-mapClick position = ${position.longitude} -${position.latitude}`);
        };
        this.mapEventManager.on("mapClick", callback1);
    };
  }

  // 页面每次显示时触发一次,包括路由过程、应用进入前台等场景,仅@Entry装饰的自定义组件生效
  onPageShow(): void {
    // 将地图切换到前台
    if (this.mapController !== undefined) {
      this.mapController.show();
    }
  }

  // 页面每次隐藏时触发一次,包括路由过程、应用进入后台等场景,仅@Entry装饰的自定义组件生效。
  onPageHide(): void {
    // 将地图切换到后台
    if (this.mapController !== undefined) {
      this.mapController.hide();
    }
  }

  build() {
    Stack() {
      // 调用MapComponent组件初始化地图
      MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback }).width('100%').height('100%');
      // 当前位置
      // LocationButton().onClick((event: ClickEvent, result: LocationButtonOnClickResult)=>{
      //   console.info("result " + result)
      // })


    }.height('100%')
  }
// 点击是否允许的位置权限页面
  requestPermissions(): void {
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
    atManager.requestPermissionsFromUser(getContext() as common.UIAbilityContext,
      ['ohos.permission.LOCATION', 'ohos.permission.APPROXIMATELY_LOCATION'])
      .then(() => {
        this.mapController?.setMyLocationEnabled(true);
        this.mapController?.setMyLocationControlsEnabled(true);
        this.mapController?.setCompassControlsEnabled(false);
        this.mapController?.setMyLocationStyle({ displayType: mapCommon.MyLocationDisplayType.FOLLOW });
        geoLocationManager.getCurrentLocation().then(async (result) => {
          let mapPosition: mapCommon.LatLng =
            await map.convertCoordinate(mapCommon.CoordinateType.WGS84, mapCommon.CoordinateType.GCJ02, result);
          AppStorage.setOrCreate('longitude', mapPosition.longitude);
          AppStorage.setOrCreate('latitude', mapPosition.latitude);
          let cameraPosition: mapCommon.CameraPosition = {
            target: mapPosition,
            zoom: 15,
            tilt: 0,
            bearing: 0
          };
          let cameraUpdate = map.newCameraPosition(cameraPosition);
          this.mapController?.animateCamera(cameraUpdate, 1000);
        })
      })
      .catch((err: BusinessError) => {
        Logger.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`);
      })
  }
}

地点查询

 地点查询效果图:

完整示例代码:

import { MapComponent, mapCommon, map , sceneMap,site} from '@kit.MapKit';
import { geoLocationManager } from '@kit.LocationKit';
import { AsyncCallback ,BusinessError} from '@kit.BasicServicesKit';
import { abilityAccessCtrl,common } from '@kit.AbilityKit';
import { JSON } from '@kit.ArkTS';
import { http } from '@kit.NetworkKit';
import Logger from '../utils/Logger';

import { MapUtil } from '../utils/MapUtil';
interface testListType {
  name: string;
  latitude: string | number,
  longitude: string | number,
  color:string
}


@Entry
@Component
export  struct Map {
  private TAG = "HuaweiMapDemo";
  private mapOptions?: mapCommon.MapOptions;
  private callback?: AsyncCallback<map.MapComponentController>;
  private mapController?: map.MapComponentController;
  private mapEventManager?: map.MapEventManager;
  private marker?: map.Marker;
  // 重庆
  // @State longitude:number = 106.45952
  // @State latitude:number = 29.567283
  // 北京
  @State longitude:number = 116.4
  @State latitude:number = 39.9
  @State testList:testListType[] = []



aboutToAppear(): void {
  console.log('result0', 'result0')
    let http1 = http.createHttp();
    let responseResult = http1.request('xxxxx/water/app/estuary/listRhpwk?typeId=13&riverId=1', {
      method: http.RequestMethod.GET,
      header: {
        'Content-Type': 'application/json'
      },
      readTimeout: 20000,
      connectTimeout: 10000
    });
    responseResult.then((value: http.HttpResponse) => {
      let res = JSON.stringify(value)
      let result = `${value.result}`;
      let resCode = `${value.code}`
      console.log('result1', result)

      // let resultObj: Object = JSON.parse(result)
      let resultObj: object = JSON.parse(result) as object
      console.log('result2', JSON.stringify(resultObj['data']))
      this.testList = resultObj['data']
    }).catch(() => {
    })

    // 地图初始化参数,设置地图中心点坐标及层级
    this.mapOptions = {
      position: {
        target: {
          latitude: this.latitude,
          longitude: this.longitude
        },
        zoom: 10
      },
      mapType: mapCommon.MapType.STANDARD
    };

    // 地图初始化的回调
    this.callback = async (err, mapController) => {
      if (!err) {
        // 获取地图的控制器类,用来操作地图
        this.mapController = mapController;
        this.mapEventManager = this.mapController.getEventManager();
        let callback = () => {
          console.info(this.TAG, `on-mapLoad`);
        }
        this.mapEventManager.on("mapLoad", callback);


        //确认是否已配置权限(AGC中配置) 无权限则拉起位置
        let hasPermissions = await MapUtil.checkPermissions(this.mapController);
        console.log('hasPermissions==>',hasPermissions)
        if (!hasPermissions) {
          this.requestPermissions();
        }
        if (hasPermissions) {
          let requestInfo: geoLocationManager.CurrentLocationRequest = {
            'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX,
            'scenario': geoLocationManager.LocationRequestScenario.UNSET,
            'maxAccuracy': 0
          };
          let locationChange = async (): Promise<void> => {
          };
          geoLocationManager.on('locationChange', requestInfo, locationChange);
          // 获取当前用户位置
          geoLocationManager.getCurrentLocation(requestInfo).then(async (result) => {
            let mapPosition: mapCommon.LatLng =
              await map.convertCoordinate(mapCommon.CoordinateType.WGS84, mapCommon.CoordinateType.GCJ02, result);
            AppStorage.setOrCreate('longitude', mapPosition.longitude);
            AppStorage.setOrCreate('latitude', mapPosition.latitude);
            console.log('longitude==>',mapPosition.latitude,mapPosition.longitude)
            // 飞入 类似setView flyTo camera
            let cameraPosition: mapCommon.CameraPosition = {
              target: mapPosition,
              zoom: 15,
              tilt: 0,
              bearing: 0
            };
            let cameraUpdate = map.newCameraPosition(cameraPosition);
            mapController?.animateCamera(cameraUpdate, 1000);
          })
        }


        // Marker初始化参数
        for (let i = 0; i < this.testList.length - 1; i++) {
          console.log('this.testList[i].color',this.testList[i].color)
          let markerOptions: mapCommon.MarkerOptions = {
            position: {
              latitude:  this.testList[i].latitude as number,
              longitude: this.testList[i].longitude as number,
            },
            rotation: 0,
            visible: true,
            zIndex: 0,
            alpha: 1,
            anchorU: 2.5,
            anchorV: 10.5,
            clickable: true,
            draggable: true,
            flat: false,
            title:this.testList[i].name,
            icon: `icon_rhkpwk_blue.png`,
          };
          // 创建Marker
          this.marker = await this.mapController.addMarker(markerOptions);

          let callbackMarker = (marker: map.Marker) => {
            console.info(`on-markerClick marker = ${JSON.stringify(marker)}`);
            // 设置信息窗的标题
            // marker.setTitle('南京');
            // 设置信息窗的子标题
            // marker.setSnippet('华东地区');
            // 设置标记可点击
            marker.setClickable(true);
            // 设置信息窗的锚点位置
            marker.setInfoWindowAnchor(1, 1);
            // 设置信息窗可见
            marker.setInfoWindowVisible(true);

          };
          this.mapEventManager.on("markerClick", callbackMarker);
        }



        /*let initNumber = 0;
        let position: geoLocationManager.Location = {
          "latitude": this.latitude,
          "longitude":this.longitude,
          "altitude": 0,
          "accuracy": 0,
          "speed": 0,
          "timeStamp": 0,
          "direction": 0,
          "timeSinceBoot": 0,
          altitudeAccuracy: 0,
          speedAccuracy: 0,
          directionAccuracy: 0,
          uncertaintyOfTimeSinceBoot: 0,
          sourceType: 1
        };
        let count = 0;
        const intervalId = setInterval(async () => {
          position.direction = initNumber + count * 3;
          position.accuracy = initNumber + count * 100;
          position.latitude = initNumber + count * 0.1;
          position.longitude = initNumber + count * 0.1;
          this.mapController?.setMyLocation(position);
          if (count++ === 10) {
            clearInterval(intervalId);
          }
        }, 200);*/


        //点击事件
        let callback1 = (position: mapCommon.LatLng) => {
          console.info("mapClick", `on-mapClick position = ${position.longitude} -${position.latitude}`);
        };
        this.mapEventManager.on("mapClick", callback1);

        // 获取siteid 并显示地点详情 及地图导航
        let callback2 = (poi: mapCommon.Poi) => {
          console.info("poiClick", `callback1 poi = ${poi.id}`);
          let siteId:string = poi.id
          let queryLocationOptions: sceneMap.LocationQueryOptions = { siteId };
          // 拉起地点详情页
          sceneMap.queryLocation(getContext(this) as common.UIAbilityContext, queryLocationOptions).then(() => {
            console.info("QueryLocation", "Succeeded in querying location.");
          }).catch((err: BusinessError) => {
            console.error("QueryLocation", `Failed to query Location, code: ${err.code}, message: ${err.message}`);
          });
        };
        this.mapEventManager.on("poiClick", callback2);


        // 周边搜索,通过用户传入自己的位置,可以返回周边地点列表。
        let params: site.NearbySearchParams = {
          // 指定关键字
          query: "hotel",
          // 经纬度坐标
          location: {
            latitude: 31.984410259206815,
            longitude: 118.76625379397866
          },
          // 指定地理位置的范围半径
          radius: 5000,
          // 指定需要展示的poi类别
          poiTypes: ["NATIONAL_RAILWAY_STATION"],
          language: "en",
          pageIndex: 1,
          pageSize: 1
        };
        // 返回周边搜索结果
        const result = await site.nearbySearch(params);
        console.info("Succeeded in searching nearby.",JSON.stringify(result))


      }
    };
  }

  // 页面每次显示时触发一次,包括路由过程、应用进入前台等场景,仅@Entry装饰的自定义组件生效
  onPageShow(): void {
    // 将地图切换到前台
    if (this.mapController !== undefined) {
      this.mapController.show();
    }
  }

  // 页面每次隐藏时触发一次,包括路由过程、应用进入后台等场景,仅@Entry装饰的自定义组件生效。
  onPageHide(): void {
    // 将地图切换到后台
    if (this.mapController !== undefined) {
      this.mapController.hide();
    }
  }

  build() {
    Stack() {
      // 调用MapComponent组件初始化地图
      MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback }).width('100%').height('100%');
      // 当前位置
      // LocationButton().onClick((event: ClickEvent, result: LocationButtonOnClickResult)=>{
      //   console.info("result " + result)
      // })


    }.height('100%')
  }
  requestPermissions(): void {
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
    atManager.requestPermissionsFromUser(getContext() as common.UIAbilityContext,
      ['ohos.permission.LOCATION', 'ohos.permission.APPROXIMATELY_LOCATION'])
      .then(() => {
        this.mapController?.setMyLocationEnabled(true);
        this.mapController?.setMyLocationControlsEnabled(true);
        this.mapController?.setCompassControlsEnabled(false);
        this.mapController?.setMyLocationStyle({ displayType: mapCommon.MyLocationDisplayType.FOLLOW });
        geoLocationManager.getCurrentLocation().then(async (result) => {
          let mapPosition: mapCommon.LatLng =
            await map.convertCoordinate(mapCommon.CoordinateType.WGS84, mapCommon.CoordinateType.GCJ02, result);
          AppStorage.setOrCreate('longitude', mapPosition.longitude);
          AppStorage.setOrCreate('latitude', mapPosition.latitude);
          let cameraPosition: mapCommon.CameraPosition = {
            target: mapPosition,
            zoom: 15,
            tilt: 0,
            bearing: 0
          };
          let cameraUpdate = map.newCameraPosition(cameraPosition);
          this.mapController?.animateCamera(cameraUpdate, 1000);
        })
      })
      .catch((err: BusinessError) => {
        Logger.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`);
      })
  }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2243150.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

AntFlow 0.11.0版发布,增加springboot starter模块,一款设计上借鉴钉钉工作流的免费企业级审批流平台

AntFlow 0.11.0版发布,增加springboot starter模块,一款设计上借鉴钉钉工作流的免费企业级审批流平台 传统老牌工作流引擎比如activiti,flowable或者camunda等虽然功能强大&#xff0c;也被企业广泛采用&#xff0c;然后也存着在诸如学习曲线陡峭&#xff0c;上手难度大&#x…

Timeline动画「硬切」的问题

1&#xff09;Timeline动画「硬切」的问题 2&#xff09;移动平台纹理压缩格式选择ASTC&#xff0c;美术出图还需遵守POT吗 3&#xff09;如何去掉DOTS Unity.Entities.Graphics创建的BatchRendererGroup的UI相机回调 4&#xff09;Timeline播放动画会产生位移的问题 这是第409…

《设计模式》创建型模式总结

目录 创建型模式概述 Factory Method: 唯一的类创建型模式 Abstract Factory Builder模式 Prototype模式 Singleton模式 最近在参与一个量化交易系统的项目&#xff0c;里面涉及到用java来重构部分vnpy的开源框架&#xff0c;因为是框架的搭建&#xff0c;所以会涉及到像…

【论文阅读】主动推理:作为感知行为的理论

文章目录 主动推理&#xff1a;作为感知行为的理论摘要1.引言2. 主动推理的概念和历史根源3. 主动推理的规范视角—以及它的发展历程 未完待续 主动推理&#xff1a;作为感知行为的理论 Active inference as a theory of sentient behavior 摘要 这篇文章综述了主动推理的历…

React--》如何高效管理前端环境变量:开发与生产环境配置详解

在前端开发中&#xff0c;如何让项目在不同环境下表现得更为灵活与高效&#xff0c;是每个开发者必须面对的挑战&#xff0c;从开发阶段的调试到生产环境的优化&#xff0c;环境变量配置无疑是其中的关键。 env配置文件&#xff1a;通常用于管理项目的环境变量&#xff0c;环境…

【工具插件类教学】在 Unity 中使用 iTextSharp 实现 PDF 文件生成与导出

目录 一、准备工作 1. 安装 iTextSharp 2. 准备资源文件 二、创建 ExportPDFTool 脚本 1、初始化 PDF 文件,设置字体 2、添加标题、内容、表格和图片 三、使用工具类生成 PDF 四、源码地址 在 Unity 项目中,我们有时会需要生成带有文本、表格和图片的 PDF 文件,以便…

【AlphaFold3】开源本地的安装及使用

文章目录 安装安装DockerInstalling Docker on Host启用Rootless Docker 安装 GPU 支持安装 NVIDIA 驱动程序安装 NVIDIA 对 Docker 的支持 获取 AlphaFold 3 源代码获取基因数据库获取模型参数构建将运行 AlphaFold 3 的 Docker 容器 参考 AlphaFold3: https://github.com/goo…

[JAVA]MyBatis框架—获取SqlSession对象

SqlSessionFactory作为MyBatis框架的核心接口有三大特性 SqlSessionFactory是MyBatis的核心对象 用于初始化MyBatis&#xff0c;创建SqlSession对象 保证SqlSessionFactory在应用中全局唯一 1.SqlSessionFactory是MyBatis的核心对象 假设我们要查询数据库的用户信息&#x…

ArkTS学习笔记:ArkTS起步

ArkTS是HarmonyOS的主力应用开发语言&#xff0c;基于TypeScript扩展&#xff0c;强化了静态检查和分析&#xff0c;旨在提升程序稳定性和性能。它采用静态类型&#xff0c;禁止运行时改变对象布局&#xff0c;并对UI开发框架能力进行扩展&#xff0c;支持声明式UI描述和自定义…

JAVA 之 JDBC

JDBC概述 基本介绍 1.JDBC为访问不同的数据库提供了统一的接口&#xff0c;为使用者屏蔽了细节问题。 2.Java程序员使用JDBC,可以连接任何提供了JDBC驱动程序的数据库系统&#xff0c;从而完成对数据库的各种操作。 3.JDBC的基本原理[ 重要 ] 4.模拟JDBC com.lmbc.myjdbc…

用 Python 从零开始创建神经网络(五):损失函数(Loss Functions)计算网络误差

用损失函数&#xff08;Loss Functions&#xff09;计算网络误差 引言1. 分类交叉熵损失&#xff08;Categorical Cross-Entropy Loss&#xff09;2. 分类交叉熵损失类&#xff08;The Categorical Cross-Entropy Loss Class&#xff09;展示到目前为止的所有代码3. 准确率计算…

Redis做分布式锁

&#xff08;一&#xff09;为什么要有分布式锁以及本质 在一个分布式的系统中&#xff0c;会涉及到多个客户端访问同一个公共资源的问题&#xff0c;这时候我们就需要通过锁来做互斥控制&#xff0c;来避免类似于线程安全的问题 因为我们学过的sychronized只能对线程加锁&…

阿里云引领智算集群网络架构的新一轮变革

阿里云引领智算集群网络架构的新一轮变革 云布道师 11 月 8 日~ 10 日在江苏张家港召开的 CCF ChinaNet&#xff08;即中国网络大会&#xff09;上&#xff0c;众多院士、教授和业界技术领袖齐聚一堂&#xff0c;畅谈网络未来的发展方向&#xff0c;聚焦智算集群网络的创新变…

预处理(1)(手绘)

大家好&#xff0c;今天给大家分享一下编译器预处理阶段&#xff0c;那么我们来看看。 上面是一些预处理阶段的知识&#xff0c;那么明天给大家讲讲宏吧。 今天分享就到这里&#xff0c;谢谢大家&#xff01;&#xff01;

ZYNQ程序固化——ZYNQ学习笔记7

一、ZYNQ启动过程 二、 SD卡启动实操 1、对ZYNQ进行配置添加Flash 2、添加SD卡 3、重新生成硬件信息 4、创建vitis工程文件 5、勾选板级支持包 6、对系统工程进行整体编译&#xff0c;生成两个Debug文件&#xff0c;如图所示。 7、插入SD卡&#xff0c;格式化为 8、考入BOOT.…

FPGA实现PCIE采集电脑端视频转SFP光口万兆UDP输出,基于XDMA+GTX架构,提供2套工程源码和技术支持

目录 1、前言工程概述免责声明 2、相关方案推荐我已有的PCIE方案10G Ethernet Subsystem实现万兆以太网物理层方案 3、PCIE基础知识扫描4、工程详细设计方案工程设计原理框图电脑端视频PCIE视频采集QT上位机XDMA配置及使用XDMA中断模块FDMA图像缓存UDP视频组包发送UDP协议栈MAC…

Mongo数据库集群搭建

目录 1、Mongo集群优势 1.1 高可用性 1.2 水平扩展性 1.3 高性能 1.4 灵活的架构设计 1.5 数据安全 1.6 管理与监控 2、下载指定操作系统版本包 3、部署和验证工作 3.1 准备配置文件及依赖 3.2 启动第一个节点 3.3 部署更多的节点 3.4 初始化副本集 3.5 设置管理…

创建vue3项目步骤

脚手架创建项目&#xff1a; pnpm create vue Cd 项目名称安装依赖&#xff1a;Pnpm iPnpm Lint&#xff1a;修复所有文件风格 &#xff0c;不然eslint语法警告报错要双引号Pnpm dev启动项目 拦截错误代码提交到git仓库&#xff1a;提交前做代码检查 pnpm dlx husky-in…

C语言项⽬实践-贪吃蛇

目录 1.项目要点 2.窗口设置 2.1mode命令 2.2title命令 2.3system函数 2.Win32 API 2.1 COORD 2.2 GetStdHandle 2.3 CONSOLE_CURSOR_INFO 2.4 GetConsoleCursorInfo 2.5 SetConsoleCursorInfo 2.5 SetConsoleCursorPosition 2.7 GetAsyncKeyState 3.贪吃蛇游戏设…

nfs服务器--RHCE

一&#xff0c;简介 NFS&#xff08;Network File System&#xff0c;网络文件系统&#xff09;是FreeBSD支持的文件系统中的一种&#xff0c;它允许网络中的计 算机&#xff08;不同的计算机、不同的操作系统&#xff09;之间通过TCP/IP网络共享资源&#xff0c;主要在unix系…