您的位置:首页 > 移动开发 > 微信开发

EA&UML日拱一卒-微信小程序实战:位置闹铃 (2)-在地图上显示自己的位置

2018-01-31 18:23 886 查看
有了最终目标以后,我们继续采取每天一小步的方式进行开发,今天首先实现在地图上显示自己位置的功能。

画面截图



index.wxml

<!--index.wxml-->

<view class="container">

 <map longitude="{{longitude}}" latitude="{{latitude}}" markers="{{markers}}" style="
width: 375px; height: 500px;"></map>

 <text class="angle_text">{{location}}</text>

</view>

 

内容很简单,画面上布置了一个map对象和text对象。

其中map对象分别指定了longitude,latitude和markers。相信你还记得:在双重花括号{{}}包围的部分是变量,它们的值在对应页面的js文件中定义。

index.js

//index.js

//获取应用实例

const app = getApp()

Page({

 data: {                   //数据定义

   longitude: 0,       //
对应wxml文件中的longitude变量

   latitude: 0,          //
对应wxml文件中的latitude变量

   location: ',',         //
对应wxml文件中的location变量

   markers: [{          //
对应wxml文件中的markers变量

     id: 0,

     latitude: 0,

     longitude: 0,

     width: 50,

     height: 50

   }],

 },

 

 onShow: function()
{

   var that
= this

   wx.getLocation({

     type: 'gcj02', //
返回 可以 用于 wx. openLocation 的 经纬度

     success: function (res)
{

       var latitude
= res.latitude

       var longitude
= res.longitude

       console.log(res)

       var location
= latitude.toFixed(2) + ',' +
longitude.toFixed(2)

       that.setData({ longitude: longitude,

                      latitude: latitude,

                      location: location,

                      markers: [{latitude: latitude,

                                 longitude: longitude,

                               }]

                   });

     }

   })

 },

})

这段代码实现了生命周期函数onShow,它的核心是ws.getLocation,它的输出通过传递的success:function来处理。处理的内容很简单,就是通过setData函数设定到各个数据上。

虽然有点突然,但是这就是全部了。

参考资料

地图表示
https://mp.weixin.qq.com/debug/wxadoc/dev/component/map.html#map
获取位置
https://mp.weixin.qq.com/debug/wxadoc/dev/api/location.html
写在文章的最后

既然已经读到这里了,拜托大家再用一分钟时间,将文章转发到各位的朋友圈,微信群中。本公众号的成长需要您的支持!
以上就是今天的文章,欢迎点赞并推荐给您的朋友!
阅读更多更新文章,请扫描下面二维码,关注微信公众号【面向对象思考】

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐