1.解决报当前定位失败Geolocation permission denied:

 

 可以去高德api查看:常见问题 | 高德地图API (amap.com)

 

图中红圈2,3,4,5,6对应Geolocation permission denied报错的原因,可对应修改。

如红圈2:用户打开定位选项即可:

 

 2.进入定位页面偶尔报 AMap没有找到的。

1.在index.html文件中;

  <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.12&key=自己的key">
      window.AMap = AMap;
    </script>

2.在封装高德api的文件下对应调整:

  /**
   * 用高德地图定位
   */
  amapLocate(
    complete?: (cityCode: string, cityName: string) => void,
    error?: () => void
  ): void {
    const AMap = (window as any).AMap;
    const mapObj = new AMap.Map("iCenter");
    mapObj.plugin("AMap.Geolocation", () => {
      const geolocation = new AMap.Geolocation({
        timeout: 100000, // 超过 100 秒后停止定位
      });
      mapObj.addControl(geolocation);

      geolocation.getCurrentPosition();
      AMap.event.addListener(
        geolocation,
        "complete",
        (data: {
          position: { lat: number; lng: number };
          addressComponent: { adcode?: string; province: string; city: string };
        }) => {
          const position = data.position;
          const addressComponent = data.addressComponent;
          this.LocationModule.SET_longitude_PERSIST(position.lng);
          this.LocationModule.SET_latitude_PERSIST(position.lat);
          if (complete) {
            complete(
              getCityCodeByAdcode(
                addressComponent
                  ? addressComponent.adcode
                  : LocationModule.defaultCityCode
              ),
              addressComponent
                ? addressComponent.city || addressComponent.province
                : LocationModule.defaultCityName // 直辖市 addressComponent.city 为空字符串,这时要取 province
            );
          }
        }
      );
      AMap.event.addListener(geolocation, "error", (errorData: unknown) => {
        console.error("locate >>> errorData", errorData);
        this.LocationModule.SET_longitude_PERSIST(-1);
        this.LocationModule.SET_latitude_PERSIST(-1);
        if (error) {
          error();
        }
      });
    });
  }

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐