Mapbox GL JS 获取屏幕可视区域(四角)经纬度

其中 window.mapbox 为mapboxgl实例
  /**
   * 获取当前窗口可视区域的经纬度
   * @returns
   */
  function getWindowLngLat() {
    if (window.mapbox) {
      let widthRange = window.mapbox?.unproject([
        window.mapbox?.getCanvas().width,
        0,
      ]);
      let widthRange1 = window.mapbox?.unproject([
        0,
        window.mapbox?.getCanvas().width,
      ]);
      let heightRange = window.mapbox?.unproject([
        0,
        window.mapbox?.getCanvas().height,
      ]);
      let heightRange1 = window.mapbox?.unproject([
        window.mapbox?.getCanvas().height,
        0,
      ]);
      let maxLat = Math.max(
        widthRange.lat,
        widthRange1.lat,
        heightRange.lat,
        heightRange1.lat
      );
      let minLat = Math.min(
        widthRange.lat,
        widthRange1.lat,
        heightRange.lat,
        heightRange1.lat
      );
      let maxLng = Math.max(
        widthRange.lng,
        widthRange1.lng,
        heightRange.lng,
        heightRange1.lng
      );
      let minLng = Math.min(
        widthRange.lng,
        widthRange1.lng,
        heightRange.lng,
        heightRange1.lng
      );
      // console.log(minLat, maxLat,minLng,maxLng);
      return {
        minLat,
        minLng,
        maxLat,
        maxLng,
      };
    }
    return {
      minLat: 0,
      minLng: 0,
      maxLat: 0,
      maxLng: 0,
    };
  }

你可能感兴趣的:(javascript,前端)