首页 > 其他分享 >umi项目集成高德地图的js-sdk ——亲测有效

umi项目集成高德地图的js-sdk ——亲测有效

时间:2022-10-05 16:57:54浏览次数:43  
标签:result longitude number lnglat js AMap latitude umi 亲测

1.开发前准备

  • 注册账号信息
  • 创建新应用

 

 

 

2.集成到项目

    • 引入到项目中
       
  • 相关代码util代码封装
//@ts-ignore
const AMap = window.AMap;
/**
 * 其他坐标转换成高德坐标转换
 */
export function convertFrom(
  lnglat?: [longitude: number, latitude: number],
  type?: any,
) {
  if (!type) {
    type = 'gps';
  }
  if (!lnglat) {
    lnglat = [104.071262, 30.692193];
  }
  AMap.convertFrom(lnglat, type, (status: string, result: any) => {
    if (result.info === 'ok') {
      let resLnglat = result.locations[0];
      lnglat = [resLnglat.lng, resLnglat.lat];
      console.log(3, lnglat);
    }
  });
  console.log(4, lnglat);
  return lnglat;
}
// convertFrom(lnglat, 'gps');

/**
 * 计算两者距离
 */
export function user_shop_distance(
  shop: {
    latitude: number;
    longitude: number;
  },
  user: {
    latitude: number;
    longitude: number;
  },
) {
  let p1 = [shop.longitude, shop.latitude];
  let p2 = [user.longitude, user.latitude];
  let dis = Math.round(AMap.GeometryUtil.distance(p1, p2));
  // Toast(dis + '');
  return dis <= 10;
}

/**高德浏览器定位 */
// export function gdGeolocation() {
//   //@ts-ignore
//   AMap.plugin('AMap.Geolocation', function () {
//     var geolocation = new AMap.Geolocation({
//       // 是否使用高精度定位,默认:true
//       enableHighAccuracy: true,
//       convert: true,
//       // 设置定位超时时间,默认:无穷大
//       timeout: 10000,
//       // 定位按钮的停靠位置的偏移量
//       offset: [10, 20],
//       //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
//       zoomToAccuracy: true,
//       //  定位按钮的排放位置,  RB表示右下
//       position: 'RB',
//     });

//     geolocation.getCurrentPosition(function (status: string, result: any) {
//       if (status == 'complete') {
//         onComplete(result);
//       } else {
//         one rror(result);
//       }
//     });

//     function onComplete(data: any) {
//       // data是具体的定位信息
//       console.log('onComplete', JSON.stringify(data));
//       alert('onComplete' + JSON.stringify(data));
//     }

//     function one rror(data: any) {
//       alert('onError' + JSON.stringify(data));
//       // 定位出错
//       console.log('onError', JSON.stringify(data));
//     }
//   });
// }

/**逆向地理编码方法 */
export function Geocoder(lnglat?: [longitude: number, latitude: number]) {
  AMap.plugin('AMap.Geocoder', () => {
    var geocoder = new AMap.Geocoder({
      // city 指定进行编码查询的城市,支持传入城市名、adcode 和 citycode
      city: '010',
      extensions: 'base', //默认值:base,返回基本地址信息;  取值为:all,返回地址信息及附近poi、道路、道路交叉口等信息
      batch: false, //是否批量查询  batch=true为批量查询,batch=false为单点查询, batch=false时即使传入多个点也只返回第一个点结果
    });
    geocoder.getAddress(lnglat, (status: any, result: any) => {
      let res = result;
      if (status === 'complete' && result.info === 'OK') {
        // result为对应的地理位置详细信息
        // console.log(result.regeocode.formattedAddress);
        let res = result.regeocode.formattedAddress;
        console.log('res', res);
      }
      console.log(res);
    });
  });
}
/**
 *
 * @param lnglat 经纬度
 * @param type 坐标体系 'gps' ,''
 */
export function gpstoaddress(
  lnglat?: [longitude: number, latitude: number],
  type?: any,
) {
  var reslut = '';
  if (!type) {
    type = 'gps';
  }
  if (!lnglat) {
    lnglat = [经度, 纬度];
  }
  try {
    AMap.plugin('AMap.Geocoder,AMap.convertFrom', function () {
      AMap.convertFrom(lnglat, type, function (status: string, result: any) {
        console.log(result);
        if (result.info === 'ok') {
          let resLnglat = result.locations[0];
          lnglat = [resLnglat.lng, resLnglat.lat];
          console.log(lnglat);
        }
      });
      let geocoder = new AMap.Geocoder({
        // city 指定进行编码查询的城市,支持传入城市名、adcode 和 citycode
        city: '010',
        extensions: 'all',
        batch: false, //是否批量查询  batch=true为批量查询,batch=false为单点查询, batch=false时即使传入多个点也只返回第一个点结果
      });
      geocoder.getAddress(lnglat, (status: any, res: any) => {
        if (status === 'complete' && res.info === 'OK') {
          reslut = res.regeocode.formattedAddress;
          console.log(reslut);
        }
      });
    });
  } catch (error) {
    console.log(error);
    return reslut;
  }
  return reslut;
}

const convertFroms = (
  getzuobiao: (res: any) => void,
  lnglat?: [longitude: number, latitude: number],
  type?: any,
) => {
  AMap.convertFrom(lnglat, type, (status: string, result: any) => {
    if (result.info === 'ok') {
      let resLnglat = result.locations[0];
      // lnglat = [resLnglat.lng, resLnglat.lat];
      // console.log(3, lnglat);
      getzuobiao([resLnglat.lng, resLnglat.lat]);
    }
  });
};

/**
 * 获取定位地址信息
 */
export const getGeocoder = (
  fun: (res: string) => void,
  lnglat?: [longitude: number, latitude: number],
  type?: string,
) => {
  convertFroms(
    (obj) => {
      AMap.plugin('AMap.Geocoder', async () => {
        let geocoder = new AMap.Geocoder({
          // city 指定进行编码查询的城市,支持传入城市名、adcode 和 citycode
          city: '010',
          extensions: 'base', //默认值:base,返回基本地址信息;  取值为:all,返回地址信息及附近poi、道路、道路交叉口等信息
          batch: false, //是否批量查询  batch=true为批量查询,batch=false为单点查询, batch=false时即使传入多个点也只返回第一个点结果
        });
        await geocoder.getAddress(obj, (status: any, result: any) => {
          if (status === 'complete' && result.info === 'OK') {
            // result为对应的地理位置详细信息
            fun(result.regeocode.formattedAddress);
          }
        });
      });
    },
    lnglat,
    type ?? 'gps',
  );
};

/**
 * 获取gps经纬度
 */
export function getGpsLongLat(
  fun: (longitude: number, latitude: number) => void,
) {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(async function (position) {
      let latitude = position.coords.latitude; //获取纬度
      let longitude = position.coords.longitude; //获取经度
      // 经度每隔0.00001度,距离相差约1米;
      fun(longitude, latitude);
    });
  } else {
    alert('不支持定位功能');
  }
}

 

  • 引用

  

//获取定位地址信息

getGeocoder(
        async (res) => {
          let result = await addShopLocation({
            shopId: initialState?.user?.shopId ?? '',
            latitude,
            longitude,
            shopAddress: res,
          });
          Toast(JSON.stringify(result));
          if (result.success) {
            Toast(result.message);
            setIisLocation(true);
          }
        },
        [longitude, latitude],
        'gps',
      );

 

 

3.测试

 

 

 获取定位成功,获取地址成功,并水印在图片上

4.注意事项

  • 测试地址应该移动端测试,并开启gps定位,最好用https来引用
  • 代码只是测试代码,运用之前还是需要适当自己修改

 

标签:result,longitude,number,lnglat,js,AMap,latitude,umi,亲测
From: https://www.cnblogs.com/study-together/p/16755828.html

相关文章

  • 一文了解JSON
    目录JSON在JavaScript中的使用。json的定义json的访问json的两个常用方法JSON在在java中的使用javaBean和和json的互转List和和json的互转map和和json......
  • flexible分析.js
    (functionflexible(window,document){//获取的html的根元素vardocEl=document.documentElement//dpr物理像素比vardpr=window.devi......
  • flexible.js
    (functionflexible(window,document){vardocEl=document.documentElementvardpr=window.devicePixelRatio||1//adjustbodyfontsizef......
  • CommonJs与ESModule的区别
    两者的模块导入导出语法不同,CommonJs是通过module.exports,exports导出,require导入;ESModule则是export导出,import导入。CommonJs是运行时加载模块,ESModule是在静态编译期......
  • js:防抖动与节流
    针对一些会频繁触发的事件如scroll、resize,如果正常绑定事件处理函数的话,有可能在很短的时间内多次连续触发事件,十分影响性能。因此针对这类事件要进行防抖动或者节流处理防......
  • SAP UI5 应用元数据文件 manifest.json 的加载和解析原理讲解试读版
    一套适合SAPUI5初学者循序渐进的学习教程本专栏计划的文章数在​​300​​​篇左右,到​​2022年9月22日​​​为止,目前已经更新了​​133​​​篇,专栏完成度为​​......
  • 【nodejs开发】nodejs实现socket网络通信
    (本节内容如下:)1、简介在NodeJS中有三种socket:1.TCP,2.UDP,3.Unix域套接字。UDP/datagramsocketsClass:dgram.SocketEvent:'close'Event:'connect'Event:'erro......
  • 令人头秃的js隐式转换面试题,你能做对吗
    你有没有在面试中遇到特别奇葩的js隐形转换的面试题,第一反应是怎么会是这样呢?难以自信,js到底是怎么去计算得到结果,你是否有深入去了解其原理呢?下面将深入讲解其实现原理。......
  • 一道80%的前端开发都答不上来的js异步面试题
    最近面试中碰到了一道关于JS执行顺序的题目,题目比较基础,但是如果对于JS不熟的话,还是容易答不上来。再次记录和分析此次面试题,希望对大家有所帮助。asyncfunctiona......
  • [RxJS] Defer task execution with the asapScheduler (microtask)
    asapSchedulerissimilarto queueMicroTask()and Promise. AsapSchedulerletsyouscheduleworkonthemicrotaskqueue,executingtaskassoonaspossible,o......