提交 cdc04c71 编写于 作者: DCloud-WZF's avatar DCloud-WZF 💬

feat: chooseLocation 示例支持 app 端

上级 19a707a0
......@@ -3,22 +3,22 @@
<page-head :title="title"></page-head>
<view class="uni-padding-wrap">
<view style="background:#FFFFFF; padding:40rpx;">
<view class="uni-hello-text uni-center">当前位置信息</view>
<block v-if="hasLocation === false">
<view class="uni-hello-text uni-center">位置信息</view>
<view v-if="!hasLocation">
<view class="uni-h2 uni-center uni-common-mt">未选择位置</view>
</block>
<block v-if="hasLocation === true">
</view>
<view v-if="hasLocation">
<view class="uni-hello-text uni-center" style="margin-top:10px;">
{{locationAddress}}
</view>
<view class="uni-h2 uni-center uni-common-mt">
<view class="uni-h2 uni-center uni-common-mt" v-if="location.latitude.length>1">
<text>E: {{location.longitude[0]}}°{{location.longitude[1]}}′</text>
<text>\nN: {{location.latitude[0]}}°{{location.latitude[1]}}′</text>
</view>
</block>
</view>
</view>
<view class="uni-btn-v">
<view class="tips">注意:需要正确配置地图服务商的Key才能正常选择位置</view>
<view class="tips">注意:Web和App需要正确配置地图服务商的Key并且保证Key的权限和余额足够,才能正常选择位置</view>
<button type="primary" @tap="chooseLocation">选择位置</button>
<button @tap="clear">清空</button>
</view>
......@@ -26,24 +26,19 @@
</view>
</template>
<script lang="uts">
function formatLocation(longitude, latitude) {
if (typeof longitude === 'string' && typeof latitude === 'string') {
longitude = parseFloat(longitude)
latitude = parseFloat(latitude)
}
longitude = longitude.toFixed(2)
latitude = latitude.toFixed(2)
return {
longitude: longitude.toString().split('.'),
latitude: latitude.toString().split('.')
}
type Location = {
latitude: string[]
longitude: string[]
}
export default {
data() {
return {
title: 'chooseLocation',
hasLocation: false,
location: {},
location: {
latitude: [],
longitude: []
} as Location,
locationAddress: ''
}
},
......@@ -51,13 +46,27 @@
chooseLocation: function () {
uni.chooseLocation({
success: (res) => {
console.log(res, 123)
console.log('chooseLocation success', res)
this.hasLocation = true
this.location = formatLocation(res.longitude, res.latitude)
this.location = this.formatLocation(res.longitude, res.latitude)
this.locationAddress = res.address
}
})
},
formatLocation: function(longitude:number, latitude:number):Location {
const longitudeArr = longitude.toString().split('.')
const latitudeArr = latitude.toString().split('.')
if(longitudeArr.length>1){
longitudeArr[1] = longitudeArr[1].substring(0,2)
}
if(latitudeArr.length>1){
latitudeArr[1] = latitudeArr[1].substring(0,2)
}
return {
longitude: longitudeArr,
latitude: latitudeArr
}
},
clear: function () {
this.hasLocation = false
}
......
## 1.1.3(2024-11-11)
优化 chooseLocation 函数供 uni-app x 的 uni.chooseLocation 使用
## 1.1.2(2024-10-21)
新增chooseLocation函数供uni.chooseLocation使用
## 1.1.1(2024-07-23)
[调整] 移除db_init.json文件,初始化数据库请用新版方式(右键database,初始化数据库)
## 1.1.0(2024-03-25)
[重要] 支持支付宝小程序云
## 1.0.2(2023-08-01)
优化配置读取方式
## 1.0.1(2023-08-01)
初版
## 1.0.0(2023-08-01)
初版,文档地址:https://uniapp.dcloud.net.cn/uniCloud/uni-map-common.html
{
"id": "uni-map-common",
"displayName": "uni-map-common地图服务端API",
"version": "1.1.3",
"description": "聚合了多家地图供应商的服务端API,几行代码即可快速接入地图API",
"keywords": [
"uni-map-common",
"地图服务端API"
],
"repository": "",
"engines": {
"HBuilderX": "^3.1.0"
},
"dcloudext": {
"type": "unicloud-template-function",
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "插件不采集任何数据",
"permissions": "无"
},
"npmurl": ""
},
"uni_modules": {
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "y",
"aliyun": "y",
"alipay": "y"
},
"client": {
"Vue": {
"vue2": "u",
"vue3": "u"
},
"App": {
"app-vue": "u",
"app-nvue": "u"
},
"H5-mobile": {
"Safari": "u",
"Android Browser": "u",
"微信浏览器(Android)": "u",
"QQ浏览器(Android)": "u"
},
"H5-pc": {
"Chrome": "u",
"IE": "u",
"Edge": "u",
"Firefox": "u",
"Safari": "u"
},
"小程序": {
"微信": "u",
"阿里": "u",
"百度": "u",
"字节跳动": "u",
"QQ": "u",
"钉钉": "u",
"快手": "u",
"飞书": "u",
"京东": "u"
},
"快应用": {
"华为": "u",
"联盟": "u"
}
}
}
}
}
\ No newline at end of file
# uni-map-common
聚合了多家地图供应商的服务端API
## 使用教程
> 文档地址:[https://uniapp.dcloud.net.cn/uniCloud/uni-map-common.html](https://uniapp.dcloud.net.cn/uniCloud/uni-map-common.html)
## bug反馈地址
> 加群:[uni-map交流群](https://im.dcloud.net.cn/#/?joinGroup=64d62b106823de10406ad72f)
const service = require('./service/index.js');
class UniMap {
// 构造函数
constructor(data = {}) {
let {
provider, // 平台 weixin-mp 微信小程序 weixin-h5 微信公众号
key, // 密钥
needOriginalResult = false, // 是否需要返回原始信息,默认false
} = data;
let runService = service[provider];
if (!runService) {
throw new Error(`不支持平台:${provider}`);
}
this.service = new runService({
provider,
key,
needOriginalResult
});
//return this.service;
}
// API - 逆地址解析(坐标转地址)
async location2address(data = {}) {
let res = await this._call("location2address", data);
return res;
}
// API - 地址解析(地址转坐标)
async address2location(data = {}) {
let res = await this._call("address2location", data);
return res;
}
// API - 坐标转换
async translate(data = {}) {
let res = await this._call("translate", data);
return res;
}
// API - IP定位
async ip2location(data = {}) {
let res = await this._call("ip2location", data);
return res;
}
// API - 关键词输入提示
async inputtips(data = {}) {
let res = await this._call("inputtips", data);
return res;
}
// API - 周边搜索
async search(data = {}) {
let res = await this._call("search", data);
return res;
}
// API - 行政区划
async districtSearch(data = {}) {
let res = await this._call("districtSearch", data);
return res;
}
// API - 路线规划(驾车/步行/骑行/电动车/公交)
async route(data = {}) {
let urlObj = {
"driving": "drivingRoute",
"walking": "walkingRoute",
"bicycling": "bicyclingRoute",
"ebicycling": "ebicyclingRoute",
"transit": "transitRoute"
};
let res = await this._call(urlObj[data.mode], data);
res.result.mode = data.mode;
return res;
}
// 私有函数
async _call(name, data = {}) {
let runFunction = this.service[name];
if (!runFunction) {
throw new Error(`平台:${this.service.config.provider} 不支持API:${name}`);
}
let res = await runFunction.call(this.service, data); // 此处需要使用call,防止里面的this作用域被意外改变
if (!this.service.config.needOriginalResult) {
delete res.originalResult;
}
//res = JSON.parse(JSON.stringify(res));
return {
provider: this.service.config.provider,
...res
};
}
}
module.exports = UniMap;
\ No newline at end of file
/**
* 通用公共函数
*/
var common = {};
// 经纬度表示形式转换
common.getLocation = function(location = "", type = "", returnType = "") {
let lat;
let lng;
// 去除所有空格
type = type.trim();
returnType = returnType.replace(/\s+/g, '');
if (type === "lat,lng") {
location = location.replace(/\s+/g, '');
let arr = location.split(",");
lat = arr[0];
lng = arr[1];
} else if (type === "lng,lat") {
location = location.replace(/\s+/g, '');
let arr = location.split(",");
lat = arr[1];
lng = arr[0];
} else if (type === "lat lng") {
let arr = location.split(" ");
lat = arr[0];
lng = arr[1];
} else if (type === "lng lat") {
let arr = location.split(" ");
lat = arr[1];
lng = arr[0];
} else {
lat = location.lat;
lng = location.lng;
}
if (returnType == "lng,lat") {
return `${lng},${lat}`;
} else if (returnType == "lat,lng") {
return `${lat},${lng}`;
} else {
return {
lat: Number(lat),
lng: Number(lng)
}
}
};
// 字符串格式的坐标经纬度反转
common.getReversalLocation = function(input="") {
// 按分隔符拆分字符串
let parts = input.split("|");
// 遍历每个部分进行值交换
for (let i = 0; i < parts.length; i++) {
let pairs = parts[i].split(";");
for (let j = 0; j < pairs.length; j++) {
let values = pairs[j].split(",");
// 交换两个值
let temp = values[0];
values[0] = values[1];
values[1] = temp;
// 更新交换后的值
pairs[j] = values.join(",");
}
// 更新交换后的部分
parts[i] = pairs.join(";");
}
// 返回交换后的结果
return parts.join("|");
};
module.exports = common;
\ No newline at end of file
const errSubject = "uni-map-common";
class UniCloudError {
constructor(options = {}) {
this.errCode = options.errCode || options.code;
this.errMsg = options.errMsg || options.msg || options.message || "";
this.errSubject = options.subject || errSubject;
}
}
module.exports = {
UniCloudError
}
\ No newline at end of file
const common = require('./common');
const error = require('./error');
module.exports = {
common,
error
};
\ No newline at end of file
{
"name": "uni-map-common",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"uni-config-center": "file:..\/..\/..\/..\/..\/uni-config-center\/uniCloud\/cloudfunctions\/common\/uni-config-center"
},
"origin-plugin-dev-name": "uni-map-common",
"origin-plugin-version": "1.1.3",
"plugin-dev-name": "uni-map-common",
"plugin-version": "1.1.3"
}
\ No newline at end of file
module.exports = {
"qqmap": require('./qqmap.js'),
"amap": require('./amap.js')
}
\ No newline at end of file
const libs = require('../libs');
class Service {
// 构造函数
constructor(data = {}) {
let {
key,
needOriginalResult = false, // 是否需要返回原始信息,默认false
} = data;
this.config = {
provider: "qqmap",
key,
needOriginalResult,
serviceUrl: "https://apis.map.qq.com"
}
}
async request(obj = {}) {
let {
url,
data = {}
} = obj;
if (url.indexOf("http") !== 0) {
url = `${this.config.serviceUrl}/${url}`
}
if (this.config.key && !data.key) {
data.key = this.config.key;
}
obj.data = JSON.parse(JSON.stringify(obj.data));
let requestRes = await uniCloud.httpclient.request(url, obj);
let result = this.getResult(requestRes);
if (result.errCode != 0) {
throw new libs.error.UniCloudError(result);
}
return result;
}
getResult(requestRes) {
let {
data: originalResult = {}
} = requestRes;
let res = {
errCode: originalResult.status == 0 ? 0 : this.getErrCode(originalResult.status),
errMsg: originalResult.message,
originalResult,
};
return res;
}
getErrCode(errCode) {
return errCode;
}
// API - 逆地址解析(坐标转地址)
async location2address(data = {}) {
let {
location,
get_poi,
poi_options
} = data;
let _poi_options = "";
if (typeof poi_options === "object") {
let {
address_format,
radius,
policy,
page_index,
page_size
} = poi_options;
if (address_format && address_format !== "long") {
_poi_options += `address_format=${address_format};`
}
if (radius) {
_poi_options += `radius=${radius};`
}
if (policy) {
_poi_options += `policy=${policy};`
}
if (page_index) {
_poi_options += `page_index=${page_index};`
}
if (page_size) {
_poi_options += `page_size=${page_size};`
}
if (_poi_options.lastIndexOf(";") === _poi_options.length - 1) {
_poi_options = _poi_options.substring(0, _poi_options.length - 1);
}
}
if (!_poi_options) _poi_options = undefined;
let requestRes = await this.request({
method: "GET",
url: "ws/geocoder/v1/",
dataType: "json",
data: {
location,
get_poi,
poi_options: _poi_options,
}
});
let originalResult = requestRes.originalResult.result;
let pois;
if (originalResult.pois) {
pois = originalResult.pois.map((item) => {
return {
id: item.id,
title: item.title,
address: item.address,
location: item.location,
distance: item._distance,
direction: item._dir_desc,
category: item.category
}
});
}
let result = {
formatted_addresses: originalResult.address,
country: originalResult.address_component.nation,
province: originalResult.address_component.province,
city: originalResult.address_component.city,
district: originalResult.address_component.district,
street: originalResult.address_component.street,
street_number: originalResult.address_component.street_number,
adcode: originalResult.ad_info.adcode,
pois
};
let res = {
result,
...requestRes
};
return res;
}
// API - 地址解析(地址转坐标)
async address2location(data = {}) {
let {
address,
city,
} = data;
let requestRes = await this.request({
method: "GET",
url: "ws/geocoder/v1/",
dataType: "json",
data: {
address: address,
region: city,
}
});
let originalResult = requestRes.originalResult.result;
let result = {
location: originalResult.location,
adcode: originalResult.ad_info.adcode,
province: originalResult.address_components.province,
city: originalResult.address_components.city,
district: originalResult.address_components.district,
street: originalResult.address_components.street,
street_number: originalResult.address_components.street_number,
};
let res = {
result,
...requestRes
};