微信小程序使用高德地图🎃

5,907 阅读3分钟

这是我参与11月更文挑战的第9天,活动详情查看:2021最后一次更文挑战

获得高德地图用户Key

没有申请key需要先申请,进入高德开发平台 lbs.amap.com/ , 在 开发指南 -> 获取key 中有详细操作步骤,在 控制台 -> 应用管理 -> 我的应用中可以查看我们创建的key

QQ图片20211120175509.png

我们可以把key封装在起来,这样就不用每次都找了,在 lib文件夹下新建一个 config.js 文件

var config = {
  key: "你的key"
}
module.exports.config = config;

在js里导入 高德的js和key就可以调用高德地图api了

var amapFile = require('../../lib/amap-wx.130.js'); //高德js
var config = require('../../lib/config.js'); //引用我们的配置文件  

获得当前位置

🎈 创建高德地图实例并命名为myAmapFun

var key = config.config.key;
var myAmapFun = new amapFile.AMapWX({
    key: key
});

🎈 调用 getRegeo 方法

myAmapFun.getRegeo({
    success: (data) => {
        🎈 保存位置的描述信息( longitude经度 latitude纬度 和位置信息 )
        let textData = {};
        textData.name = data[0].name;
        textData.desc = data[0].desc
        🎈 将获取的信息保存
        this.setData({
          textData: textData,
          longitude: data[0].longitude,
          latitude: data[0].latitude,
          🎈 给该经度纬度加上icon做标记,并调节大小
          markers: [{
            latitude: data[0].latitude,
            longitude: data[0].longitude,
            height: 30,
            width: 35,
            iconPath: '../../imgs/locationIcon/site1.png'
          }]
        })
      },
      fail: function(info){
        console.log("get Location fail");
      }    
    });

我们可以看下输出成功的data,里面的信息我们根据自己的需要取

屏幕截图 2021-11-20 201645.png

在wxml文件中将地图显示出来,这边设置的是宽度100%,高度400px, scale是地图的缩放比例

<view class="map_container">
  <map class="map" name="" longitude="{{longitude}}" latitude="{{latitude}}" scale="16"  show-location="true" markers="{{markers}}">
  </map>
</view>
<view class="map_text">
  <text class="h1">{{textData.name}}</text>
  <text>{{textData.desc}}</text>
</view>

红色的标记点就是markers的数据;蓝色的标记点是show-location="true"展示的,但是真机预览就没有了 0.png

获取附近的点,只取前十个

1637473217406.gif

data: {
    # 当前位置经度
    longitude: "",
    # 当前位置纬度
    latitude: "",
    # 获取位置的标记信息
    markers: [],
    # 获取位置的位置信息
    poisdatas : [],
    # 简单展示信息使用的
    textData: {}
}

调用高德地图的getPoiAround接口根据关键字获取附近信息

get_current_PoiAround(){
    var key = config.config.key;
    var myAmapFun = new amapFile.AMapWX({
      key: key
    });
    🎈 getRegeo 获得当前位置信息(上面有用到过这个方法)
    myAmapFun.getRegeo({
      success: (data) => {
        let textData = {};
        textData.name = data[0].name;
        textData.desc = data[0].desc
        this.setData({
          textData: textData,
          longitude: data[0].longitude,
          latitude: data[0].latitude,
        })
      },
      fail: function(info){
        console.log("get Location fail");
      }    
    });
    🎈 通过关键词获取附近的点
    myAmapFun.getPoiAround({
      🎈 改变icon图标的样式,点击前和点击后的我都暂时设成blue.svg, 如果不设置的话,默认就是一个红色的小图标
      iconPath: '../../icon/keshan/blue.svg',
      iconPathSelected: '../../icon/keshan/blue.svg',
      🎈 搜索的关键字(POI分类编码),在官方文档https://lbs.amap.com/api/javascript-api/download/ 可以下载查看
      querykeywords: '购物',
      querytypes: '060100',
      success: (data) => {
        const markers = data.markers;
        const poisdatas = data.poisData;
        let markers_new = []
        markers.forEach((item, index) => {
          🎈 只取10个点,超过就continue了,forEach是不能使用breakcontinue关键字的
          if( index >= 10 ){
            return;
          }
          🎈 将我们需要的markers数据重新整理一下存入markers_new中
          markers_new.push({
            id: item.id,
            width: item.width,
            height: item.height,
            iconPath: item.iconPath,
            latitude: item.latitude,
            longitude: item.longitude,
            🎈 自定义标记点上方的气泡窗口
            🎈 display | 'BYCLICK':点击显示; 'ALWAYS':常显 |
            callout: {
              padding: 2,
              fontSize: 15,
              bgColor: "#f78063",
              color: '#ffffff',
              borderRadius: 5,
              display: 'BYCLICK',
              content: poisdatas[index].name
            }
          })
        })
        🎈  将数据保存
        this.setData({
          markers: markers_new,
          poisdatas: poisdatas
        })
      },
      fail: function(info){
        wx.showModal({title:info.errMsg})
      }
    }) 
  },

调用getPoiAround接口返回成功的结果

1.png

2.png

bindmarkertap 激活 makertap图标点击事件,改变map_text里面内容

<view class="map_container">
  <map class="map" id="map" name="" longitude="{{longitude}}" latitude="{{latitude}}" scale="16"  show-location="true" markers="{{markers}}" bindmarkertap="makertap">
  </map>
  
</view>
<view class="map_text">
  <text class="h1">{{textData.name}}</text>
  <text wx:if="{{textData.distance != null}}">{{textData.distance}}m</text>
  <text>{{textData.desc}}</text>
</view>

makertap 激活showMarkerInfo展示标记点信息,changeMarkerColor改变标记点颜色

makertap(e) {
    var id = e.detail.markerId;
    this.showMarkerInfo(id);
    this.changeMarkerColor(id);
},

之前不是说poisdatas存放该点的位置信息嘛,我们拿到 id 就可以取出来存到textData里面显示了

 // 展示标记点信息
  showMarkerInfo(i) {
    const {poisdatas} = this.data;
    this.setData({
      textData: {
        name: poisdatas[i].name,
        desc: poisdatas[i].address,
        distance: poisdatas[i].distance
      }
    })
  },

如果是点击的那个位置就把iconPath替换成orange.svg,其余都是blue.svg,并设置被点击的气泡 display为显示('ALWAYS'),将修改后的数据重新保存就可以啦

// 改变标记点颜色
  changeMarkerColor(index) {
    let {markers} = this.data;
    for (var i = 0; i < markers.length; i++) {
      if (i == index) {
        markers[i].iconPath = "../../icon/keshan/orange.svg"; 
        markers[i].callout.display = 'ALWAYS'
      } else {
        markers[i].iconPath = "../../icon/keshan/blue.svg"; 
        markers[i].callout.display = 'BYCLICK'
      }
    }
    this.setData({
      markers: markers
    })
  },

测试代码.gif