onLoad
是页面生命周期函数,在页面加载时自动调用
wx.getLocation
是微信小程序提供的API,用于获取用户的地理位置信息。type: 'gcj02'
表示使用国测局坐标系
成功获取用户位置信息后,调用 addMark
函数将经纬度信息传入,并更新页面数据中的经纬度信息
addMark
函数用于向地图上添加标记点。如果 markers
数组为空,则创建一个新的标记点对象,并将其添加到 markers
数组中
标记点对象包括一些属性,如标记点的 ID、宽度、高度、经纬度、气泡内容、颜色、字体大小和图标路径等
最后,通过 setData
方法更新页面数据,将 markers
数组设置为新的标记点数组
<navigator url="">
<view class="pos" bindtap="gotoMap" data-latitude="{{detail.coordinate.latitude}}" data-longitude="{{detail.coordinate.longitude}}">
<view class="lef">
<image src="/images/artpos.png" mode=""/>
<view>{{detail.addr}}</view>
</view>
<image class="rig" src="/images/artarrow.png" mode=""/>
</view>
</navigator>
gotoMap(e){
let latitude = e.currentTarget.dataset["latitude"]
let longitude = e.currentTarget.dataset["longitude"]
wx.navigateTo({
url: '/pages/article/map/index?latitude=' + latitude + '&longitude=' + longitude
})
},
/pages/article/map/index 如下:
wxml
<!-- <map id="map" longitude="{{longitude}}" latitude="{{latitude}}" show-location show-compass enable-satellite></map> -->
<!-- <map id="map" longitude="{{longitude}}" latitude="{{latitude}}" show-location></map> -->
<map id="map" longitude="{{longitude}}" latitude="{{latitude}}" markers="{{markers}}" show-location scale="{{scale}}"></map>
wxss
#map{
width: 100vw;
height: 100vh;
}
wxjs
data: {
longitude:"", // 中心经度
latitude:"", // 中心纬度
markers:[], // 标记点
scale:18 // 缩放级别,取值范围为3-20
},
onLoad: function (options) {
wx.getLocation({
type:'gcj02',
success: res=>{
this.addMark({
longitude: options.longitude,
latitude: options.latitude
})
this.setData({
longitude: options.longitude,
latitude: options.latitude
})
}
})
},
addMark(res){
if(this.data.markers.length == 0){
var marker=[]
marker.push({
id:1, //标记点 id
width:30,
height:30,
longitude: res.longitude,
latitude: res.latitude,
// label:{
// content:'ga ',
// color:'#f00',
// fontSize:60
// },
callout:{
content:'气泡',
color:"#f00",
fontSize:30
},
iconPath:'/images/dw.png'
})
this.setData({
markers:marker
})
}
},
// 自定义markers
getMarkers(){
// 假设请求数据返回 markers
this.setData({
markers:[{
joinCluster:true, // 是否点聚合
iconPath:"https://img2.baidu.com/it/u=3618236253,1028428296&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500", // 项目目录下的图片路径
longitude:'131.29', // 经度
latitude:'78.21', // 纬度
width:30, // 标注图标宽度
height:30, // 标注图标高度
callout:{ // 标记点上方的气泡窗口
content:"文本", // 文本
color:"red", // 文本颜色
fontSize:24, // 文本大小
borderRadius:10, // 边框圆角
bgColor:"bule", // 背景色
padding:10, // 文本边缘留白
display:"ALWAYS", // 'BYCLICK':点击显示; 'ALWAYS':常显
textAlign:"center"//文本对齐方式。有效值: left, right, center
}
}]
})
},