引入高德地图提供的JavaScriptAPI
- <script src="http://webapi.amap.com/mapsv=1.4.4&key=注册高德地图你申请的JavaScriptApiKey"></script>
定位函数
- //获取位置
- function getAddress() {
- //高德地图API
- //AMap.service解决只使用高德Geolocation功能提示Geolocation不是构造函数问题
- AMap.service(["AMap.Geolocation"],function(){
- var geolocation = new AMap.Geolocation();
- geolocation.getCurrentPosition(function(status,result) {
- if(status=="complete"){
- attendanceVue.currentAddress.ADDRESS=result.formattedAddress; //设置当前地址
- attendanceVue.currentCityCode = result.addressComponent.citycode; //设置当前城市code
- //设置当前经纬度
- attendanceVue.currentLngLat.push(result.position.lng);
- attendanceVue.currentLngLat.push(result.position.lat);
- }else{
- attendanceVue.currentAddress.ADDRESS=result.message;
- }
- });
- });
- }
geolocation的getCurrentPosition函数默认配置基本上就能满足我的需求,配置详情可参考高德地图定位文档。使用该方法打包后的定位基本上与html5 自带的定位插件定位没有差距且在Android4.0与ios10.0版本及以上版本均做过测试且测试无问题。但难免定位会有一定差距,高德地图还额外提供了根据当前位置获取附近位置的Api(web服务Api),本文使用的Web服务Api ,JavaScriptApi 也提供了获取附近位置接口但考虑到获取附近位置页面将做为公共页面且引用网络路径的JavaScript占带宽最终选择了web服务Api。
- /**
- * 获取附近位置
- * 使用高德地图web搜索服务接口,Api文档地址:http://lbs.amap.com/api/webservice/guide/api/search
- * @param {Object} keywords 搜索关键字
- * @param {Object} currentCityCode 当前城市编码
- * @param {Object} currentLngLat 当前经纬度
- * @param {Object} pageIndex 页码
- * @param {Object} pageSize 记录条数(强烈建议不超过25,若超过25可能造成访问报错)
- * @param {Object} radius 根据当前经纬度查询范围单位米
- */
- function searchAddress(keywords,currentCityCode,currentLngLat,pageIndex,pageSize,radius) {
- ca.get({
- url: 'http://restapi.amap.com/v3/place/around?key=申请高德地图Web服务API的Key',
- data: {
- 'keywords':keywords,
- 'city': currentCityCode,
- 'types': '公司企业|道路附属设施|公共设施|商务住宅|餐饮服务|购物服务|生活服务|交通设施服务|',
- 'location': currentLngLat,
- 'offset': pageSize,
- 'page': pageIndex,
- 'radius': radius
- },
- succFn: function(result) {
- var data = evalObj(result);
- if(data.status == 1 && data.info === 'OK') {
- //如果查询关键字为空则重置查询结果,关键字不为空的查询结果需迭代追加否则会造成数据结构混乱Vue绑定不到Dom上
- if(isEmpty(keywords)){
- mui.each(data.pois,function(index,element){
- addressVue.ADDRESS_LIST.push(element);
- });
- }else{
- addressVue.ADDRESS_LIST=data.pois;
- }
- }
- }
- });
- }
暂时就写到这里吧,到时候抽空把相关代码单独抽出来在更新吧。