美文网首页大前端开发
关于小程序地图的基础使用

关于小程序地图的基础使用

作者: Vaja_wlu | 来源:发表于2019-06-28 11:53 被阅读4次

    小程序提供的map组件是原生组件,基础使用比较简单,用的时候可以查看相关API,本篇文章介绍的都是最简单的方法,让刚接触的同学有个大致的了解。
    首先如何展示一张地图,最简单粗暴的方法,找到index.wxml文件,写下一个<map></map>标签即可,但此方法只是调用出一个地图组件,仅仅能显示地图而已,并无其他功能。然后再让我们添加一些属性,使之稍微丰富一点:

    <map style='width:500px;height:500px' longitude="113.941133" latitude="22.545999"></map>
    

    当然,我们可以设置地图是否支持3D,是否能开启指南针,是否支持插件等功能:

    <map style='width:500px;height:500px' longitude="113.941133" latitude="22.545999" scale="18" show-compass="ture" enable-3D="ture" enable-overlooking="ture" enable-rotate="ture" enable-zoom="ture" enable-scroll="ture"></map>
    

    当然,其中有些效果需要在真机上才能看到。地图离不开标记,小程序提供了markers属性:

    <map style='width:500px;height:500px' longitude="113.941133" latitude="22.545999" scale="18" show-compass="ture" enable-3D="ture" enable-overlooking="ture" enable-rotate="ture" enable-zoom="ture" enable-scroll="ture" markers="{{markers}}"></map>
    

    再在index.js中添加markers数据:

    Page({
      data:{
        markers: [{
          iconPath: "./test.png",
          id: 0,
          latitude: 22.545999,
          longitude: 113.941133,
          width: 30,
          height: 30
        }]
      }
    })
    

    我们还可以给markers添加说明label属性,将其直接添加到height等属性后面即可,label示例如下:

    label: {
            content: "我在这里",
            color: "#fff",
            fontSize: 20,
            bgColor: "#000"
          }
    

    使用场景中,常常有路线需要显示,关于路线,首先需要在map标签中添加polyline="{{polyline}}",然后在data中写一些点的数据:

    polyline: [{
          points: [{
            longitude: 113.941133,
            latitude: 22.545999
          }, {
            longitude: 113.941868,
            latitude: 22.528408
          },
          {
            longitude: 113.951183,
            latitude: 22.55359
          }],
          color: "#FF0000DD",
          width: 10,
          dottedLine: true
        }],
    

    地图会通过我们给的点坐标画出一条路线,实际应用中肯定要比这个复杂,但基本原理是一样的。
    最后再来看一看小程序定位的问题,也非常简单,直接调用wx.getLocation即可:

    wx.getLocation({
          type: 'wgs84',
          success: function (res) {
            console.log(res);
            longitude: res.longitude,
            latitude: res.latitude,
            speed: res.speed,
            altitude: res.altitude,
          }
        })
    

    需要说明一下的是type字段,默认为wgs84的gps坐标,gcj02 返回可用于 wx.openLocation 的坐标。

    相关文章

      网友评论

        本文标题:关于小程序地图的基础使用

        本文链接:https://www.haomeiwen.com/subject/gmrscctx.html