腾讯位置服务城市选择器插件可以让用户快速、准确地选择城市,并将城市信息回传给开发者。我们的插件提供单页模式和组件模式两种形式,并支持搜索和索引等功能。
在腾讯公众平台中, “微信小程序官方后台-设置-第三方服务-插件管理” 里点击 “添加插件”,搜索 “腾讯位置服务城市选择器” 申请,申请后小程序开发者可在小程序内使用该插件。
// app.json
{
"plugins": {
"citySelector": {
"version": "1.0.2",
"provider": "wx63ffb7b7894e99ae"
}
}
}
城市选择器插件需要小程序提供定位授权才能够正常使用定位功能:
// app.json
{
"permission": {
"scope. userFuzzyLocation": {
"desc": "你的位置信息将用于小程序定位"
}
}
}
const key = ''; // 使用在腾讯位置服务申请的key
const referer = ''; // 调用插件的app的名称
const hotCitys = ''; // 用户自定义的的热门城市
wx.navigateTo({
url: `plugin://citySelector/index?key=${key}&referer=${referer}&hotCitys=${hotCitys}`,
})
插件页面参数
| 属性 | 类型 | 说明 | 是否必须传入 |
|---|---|---|---|
| key | string | 调用城市选择器插件需要申请腾讯位置服务的服务账号,key是开发者的唯一标识。申请key | 是 |
| referer | string | 调用来源,一般为您的应用名称,请务必填写! | 是 |
| hotCitys | string | 用户自定义的热门城市,城市名称之间用英文逗号分隔,名称需要与列表中的城市名称匹配。默认热门城市:北京、上海、天津、重庆、广州、深圳、成都、杭州 | 否,数量限制为12个 |
const citySelector = requirePlugin('citySelector');
Page({
// 从城市选择器插件返回后,在页面的onShow生命周期函数中能够调用插件接口,获取cityInfo结果对象
onShow() {
const selectedCity = citySelector.getCity(); // 选择城市后返回城市信息对象,若未选择返回null
},
onUnload () {
// 页面卸载时清空插件数据,防止再次进入页面,getCity返回的是上次的结果
citySelector.clearCity();
}
})
| 属性 | 类型 | 说明 |
|---|---|---|
| id | string | 城市的adcode |
| name | string | 城市名称 |
| fullname | string | 城市全名 |
| location | object | 城市位置信息 |
| pinyin | array | 城市名称拼音 |
location 对象说明
| 属性 | 类型 | 说明 |
|---|---|---|
| latitude | number | 纬度,范围为-90~90,负数表示南纬。使用 gcj02 国测局坐标系 |
| longitude | number | 经度,范围为-180~180,负数表示西经。使用 gcj02 国测局坐标系 |
在需要使用城市选择器组件的页面 json 文件中注册该组件
// page.json
{
"usingComponents": {
"selector-component": "plugin://citySelector/selector-component"
}
}
在小程序页面内使用
<!-- page.wxml -->
<!-- key、referer和hotCitys通过组件的属性传入 -->
<selector-component
show="{{selectorVisible}}"
key=""
referer=""
hotCitys=""
bindselect="onSelectCity"
></selector-component>
// page.js
Page({
data: {
selectorVisible: false,
selectedProvince: null,
selectedCity: null,
},
// 显示组件
showSelector() {
this.setData({
selectorVisible: true,
});
},
// 当用户选择了组件中的城市之后的回调函数
onSelectCity(e) {
const { province, city } = e.detail;
this.setData({
selectedProvince: province,
selectedCity: city,
});
},
})
插件页面传递参数错误处理说明:
页面错误码列表:
| 错误码 | 含义 |
|---|---|
| -1000 | 网络请求失败 |
| -1001 | 定位失败 |
| -1002 | 定位授权失败 |
页面模式效果图:
| Head | Head |
|---|---|
组件模式效果图:
| Head | Head |
|---|---|
有帮助
没帮助