以下是一个微信小程序中使用 wx.getLocation、wx.openLocation 和 wx.chooseLocation 的案例,包含 wxml、js 和 css 文件:
wxml 文件:
html
Copy code
<view class="container">
<view class="header">
<button bindtap="getLocation">获取位置</button>
<button bindtap="openLocation">打开地图</button>
<button bindtap="chooseLocation">选择位置</button>
</view>
<view class="map-container">
<map id="map" latitude="{{latitude}}" longitude="{{longitude}}" markers="{{markers}}" bindmarkertap="markertap"></map>
</view>
<view class="location-info">
<view class="item">
<text>当前位置:</text>
<text>{{locationInfo}}</text>
</view>
<view class="item">
<text>选择位置:</text>
<text>{{selectedLocation.name}}</text>
</view>
</view>
</view>
js 文件:
js
Copy code
Page({
data: {
latitude: null, // 当前位置的纬度
longitude: null, // 当前位置的经度
markers: [], // 地图标记
selectedLocation: {}, // 选择的位置信息
locationInfo: '暂无'
},
// 点击获取位置按钮触发事件
getLocation: function () {
wx.getLocation({
type: 'gcj02',
success: (res) => {
this.setData({
latitude: res.latitude,
longitude: res.longitude,
markers: [{
id: 1,
latitude: res.latitude,
longitude: res.longitude,
iconPath: '/images/location.png',
width: 30,
height: 30
}],
locationInfo: res.address || '暂无'
});
wx.showToast({
title: '获取位置成功'
});
},
fail: (err) => {
wx.showToast({
icon: 'none',
title: '获取位置失败'
});
}
});
},
// 点击打开地图按钮触发事件
openLocation: function () {
if (this.data.latitude && this.data.longitude) {
wx.openLocation({
latitude: this.data.latitude,
longitude: this.data.longitude,
name: '当前位置',
address: this.data.locationInfo || ''
});
} else {
wx.showToast({
icon: 'none',
title: '当前位置信息为空'
});
}
},
// 点击选择位置按钮触发事件
chooseLocation: function () {
wx.chooseLocation({
success: (res) => {
this.setData({
selectedLocation: {
latitude: res.latitude,
longitude: res.longitude,
name: res.name,
address: res.address
},
markers: [{
id: 1,
latitude: res.latitude,
longitude: res.longitude,
iconPath: '/images/location.png',
width: 30,
height: 30
}]
});
wx.showToast({
title: '选择位置成功'
});
},
fail: (err) => {
wx.showToast({
icon: 'none',
title: '选择位置失败'
});
}
});
},
// 点击地图标记触发事件
markertap: function (event) {
const markerId = event.detail.markerId;
if (





继续

ChatGPT
kotlin
Copy code
markerId === 1) {
this.openLocation();
}
}
});
css
Copy code
**css 文件:**
```css
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.header {
display: flex;
justify-content: space-around;
width: 100%;
}
.map-container {
margin: 20px 0;
width: 80%;
height: 400px;
}
.location-info {
display: flex;
flex-direction: column;
align-items: center;
}
.item {
margin: 10px 0;
}