EA&UML日拱一卒-微信小程序实战:位置闹铃 (2)-在地图上显示自己的位置
有了最终目标以后,我们继续采取每天一小步的方式进行开发,今天首先实现在地图上显示自己位置的功能。
画面截图
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
写在文章的最后