mapBox 加载后自动定位到IP归属地

如果可以实现记得点赞分享,谢谢老铁~

根据项目需求,地图加载完后需要定位到当前设备的所在IP归属地。这个得利于html5的新特性navigator.geolocation

首先在工具类中创建一个获取当前设备经纬度的方法 getCurrentPosition() ,这里结合了promise ,将获取到的设备所在经纬度resolve.

// 获取当前设备的经纬度
export const getCurrentPosition = () => {
  const options = {
    enableHighAccuracy: true,
    maximumAge: 30000,
    timeout: 1200,
  };
  return new Promise((resolve, reject) => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (pos) => {
          let lat = pos.coords.latitude;
          let lng = pos.coords.longitude;
          // 获取到了用户当前位置的坐标
          console.warn('获取到了用户当前位置的坐标');
          resolve([lng, lat]);
        },
        (error) => {
          switch (error.code) {
            case error.PERMISSION_DENIED:
              console.warn('用户不允许获取当前位置');
              break;
            case error.POSITION_UNAVAILABLE:
              console.warn('定位失败,请退出重试!');
              break;
            case error.TIMEOUT:
              console.warn('获取位置超时,请退出重试!');
              break;
            default:
              console.warn('获取定位失败!');
          }
          reject()
        },
        options,
      );
    } else {
      // 当前浏览器不支持定位服务
      console.warn('当前浏览器不支持定位服务!');
    }
  });

};

然后 在我们的业务代码里,引入该方法即可, 最后将curArrList 赋值给地图API里的center。

 useMount( () => {
    getCurrentPosition().then((curPosition: any) => {
      initMap(curPosition);
    }).catch(() => {
      initMap([]);
    });
  })
  
  // 地图初始化
  const initMap = (position: any) => {
    let curArrList = position.length > 0 ? position : [113.99531507468646, 22.27542382137679];
    mapboxgl.accessToken =
      'pk.eyJ1Ijoia2ltYm9obiIsImEiOxxxxx';
    const mapInstance = new mapboxgl.Map({
      container, // container ID
      style: `mapbox://styles/mapbox/`, // style URL
      center: curArrList, // starting position [lng, lat]
      zoom: position.length > 0 ? 11.6 : 3, // starting zoom
      projection: { name: 'globe' }, // display the map as a 3D globe
      trackResize: true
    });
  }

PS: 当然浏览器会提示当前用户是否允许,同意了才可用哦

mapBox 加载后自动定位到IP归属地_第1张图片

你可能感兴趣的:(mapBox地图,javascript)