小程序实践现现搜索地图标记记录功能代码
时间: 2023-05-28 09:01:21 浏览: 46
很抱歉,作为 AI 语言模型,我无法编写完整的小程序代码。以下是参考的代码示例,可以在代码中加以修改和完善。
1. 在小程序页面中添加搜索框和地图组件。
```
<view class="search-box">
<input placeholder="搜索地点" bindinput="searchInput"/>
<button bindtap="search">搜索</button>
</view>
<map id="map" latitude="{{latitude}}" longitude="{{longitude}}" markers="{{markers}}"
show-location bindmarker.tap="markerTap"></map>
```
2. 定义地图标记的数据结构和搜索功能函数。
```
data: {
longitude: '', // 地图中心经度
latitude: '', // 地图中心纬度
markers: [], // 地图标记数组
searchValue: '', // 搜索关键词
},
// 搜索框输入事件
searchInput: function(e) {
this.setData({
searchValue: e.detail.value
})
},
// 搜索按钮点击事件
search: function() {
const that = this
wx.showLoading({
title: '搜索中...',
})
wx.request({
url: `https://apis.map.qq.com/ws/place/v1/search?keyword=${that.data.searchValue}&location=${that.data.latitude},${that.data.longitude}&key=你的地图 API key`,
success: function(res) {
wx.hideLoading()
const markers = []
res.data.data.forEach(item => {
const marker = {
id: item.id,
latitude: item.location.lat,
longitude: item.location.lng,
title: item.title,
iconPath: '/images/marker.png',
width: 32,
height: 32,
}
markers.push(marker)
})
that.setData({
markers: markers
})
if (markers.length === 0) {
wx.showToast({
title: '没有搜索到结果',
icon: 'none'
})
}
}
})
},
// 地图标记点击事件
markerTap: function(e) {
wx.navigateTo({
url: `/pages/detail/detail?id=${e.markerId}`
})
}
```
3. 在小程序中引入地图 SDK 并获取用户位置信息。
```
// 在 app.js 中引入地图 SDK
App({
globalData: {
QQMapWX: require('./libs/qqmap-wx-jssdk.min')
}
})
// 在页面 onLoad 中获取用户位置信息并设置地图中心
const app = getApp()
const qqmapsdk = new app.globalData.QQMapWX({
key: '你的地图 API key'
})
wx.getLocation({
type: 'gcj02',
success: function(res) {
that.setData({
latitude: res.latitude,
longitude: res.longitude
})
qqmapsdk.reverseGeocoder({
location: {
latitude: res.latitude,
longitude: res.longitude
},
success: function(addressRes) {
that.setData({
address: addressRes.result.formatted_addresses.recommend
})
}
})
}
})
```