开发中uniapp的map组件无法选择本地之外的地区,所以要自定义组件,在uniapp中因为双向绑定会有问题所以,经过大佬指点做成如下
(此处需注意因为原生组件z-index 大于任何前端组件,要按实际需求处理)
<template>
<view class="card map_address">
<view class="mapBox" :style="[{height:$g_.CustomBar + 'px'},{paddingTop:$g_.StatusBar + 'px'}]">
<view class="mapTitBack" @tap="backClik">
<text class="cuIcon-back"><span></span></text>
</view>
<view class="mapTitNanem">选择位置</view>
<view class="mapSure" @tap="sureMap">
<text>完成</text>
</view>
</view>
<view class="serchCont">
<input class="uni-input serchBtn" :class="mapHiden?'serchBtn1':''" :focus="mapHiden" v-model="serarchText" @input="onKeyInput"
placeholder="搜索地点" @focus='fusHiden(true)' placeholder-style='text-align: center' />
<text class="clearText" @tap='fusHiden(false)' v-if="mapHiden">取消</text>
</view>
<view class="" style="width: 100%; height: 600upx;" v-show="!mapHiden">
<map id="map1" ref="map1" style="width: 100%; height: 600upx;" @regionchange='selectMap' :markers="covers"
show-location :scale="16"></map>
</view>
<view class="" style="position: relative;">
<view class="tmapList" :class="mapHiden?'tmapList1':''" v-if="!mapHiden">
<view class="mapSing" v-for="(item,index) in mapResult" :key='index' @tap='selectAddress(item)'>
<view class="mapleflt">
<view class="weiz">{{index == 0&&!mapHiden?'我的位置':item.name}} </view>
<view class="adress">{{item.address}}</view>
</view>
<view class="mapright">
<image src="../../../static/map/currentPos.png" mode="" v-if="item.check"></image>
</view>
</view>
</view>
<view class="tmapList" :class="mapHiden?'tmapList1':''" v-else>
<view class="mapSing" v-for="(item,index) in keyResult" :key='index' @tap='keySelect(item)'>
<view class="mapleflt">
<view class="weiz">{{item.name}} </view>
<view class="adress">{{item.address}}</view>
</view>
<view class="mapright">
<image src="../../../static/map/currentPos.png" mode="" v-if="item.check"></image>
</view>
</view>
</view>
<view class="mapLoading2" v-if="!shoeLoding">
<image src="../../../static/center/loading.png"></image>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
title: 'map',
searchNeary: 4000,
covers: [{
width: 20,
height: 20,
latitude: 31.972952,
longitude: 118.78025,
iconPath: '../../../static/map/location.png',
address: ''
}],
aaa: 'bg-gradual-fff',
map: null,
keyResult: [],
mapResult: [],
mapHiden: false,
inputClearValue: '',
showClearIcon: false,
serarchText: '',
keyUser: {},
shoeLoding: false
}
},
computed: {
...global.mapState(['$g_'])
},
mounted() {
sHeight = uni.upx2px(360);
//#ifndef MP-WEIXIN
// document.querySelector('body').setAttribute('style', 'background-color:#ffffff');
//#endif
},
beforeDestroy() {
//#ifndef MP-WEIXIN
// document.querySelector('body').setAttribute('style', 'background-color:""')
//#endif
},
onReady() {
console.log('onReady')
this.newMap()
},
onLoad: function(option) { //option为object类型,会序列化上个页面传递的参数
},
onShow() {},
methods: {
pushData(data) {
console.log("data: " + JSON.stringify(data));
setTimeout(() => {
console.log("data.lng: " + JSON.stringify(data.lng));
this.setPoint(data.lng, data.lat, true, true)
}, 500)
},
newMap() {
let self = this;
var mapCtx = uni.createMapContext('map1', self)
// console.log(mapCtx.$getAppMap())
self.map = mapCtx.$getAppMap()
self.map.showUserLocation(true);
self.searchKeyObj = new plus.maps.Search(self.map);
self.searchKeyObj.onPoiSearchComplete = function(state, result) {
console.log('onPoiSearchComplete ' + state)
if (state == 0) {
if (result.currentNumber <= 0) {
// self.ab_.load(0)
self.shoeLoding = true
console.log("没有检索到结果");
} else {
// self.ab_.load(0)
self.shoeLoding = true
self.keyResult = result.poiList;
self.keyUser = self.keyResult[0]
}
} else {
// self.ab_.load(0)
self.shoeLoding = true
console.log("检索失败");
}
}
self.searchObj = new plus.maps.Search(self.map);
self.searchObj.onPoiSearchComplete = function(state, result) {
console.log('onPoiSearchComplete ' + state)
if (state == 0) {
if (result.currentNumber <= 0) {
// self.ab_.load(0)
self.shoeLoding = true
console.log("没有检索到结果");
if (self.searchNeary < 5000) {
self.searchNeary *= 2
var searchNeary = self.searchNeary
setTimeout(function() {
if (self.mapResult.length <= 0 && searchNeary == self.searchNeary) {
// self.ab_.load(1)
self.shoeLoding = false;
self.searchObj.poiSearchNearBy('', new plus.maps.Point(self.covers[0].longitude, self.covers[0].latitude),
self.searchNeary, 0)
} else {
// self.ab_.load(0)
self.shoeLoding = true
}
}, 100)
} else {
// self.ab_.load(0)
self.shoeLoding = true
}
} else {
// self.ab_.load(0)
self.shoeLoding = true
for (var i = 0, len = result.poiList.length; i < len; i++) {
result.poiList[i].check = false;
}
console.log("self.keyUser: " + JSON.stringify(self.keyUser));
if (self.keyUser && self.keyUser.point) {
result.poiList.unshift(self.keyUser);
self.keyUser = {};
}
self.mapResult = result.poiList
}
} else {
// self.ab_.load(0)
self.shoeLoding = true
console.log("检索失败");
}
}
},
setPoint(lng, lat, cover, center) {
let self = this;
console.log('setPoint')
if (cover) {
self.covers[0].longitude = lng
self.covers[0].latitude = lat
}
if (center) {
self.map.setCenter(new plus.maps.Point(lng, lat))
// setTimeout(function() {
// self.searchObj.poiSearchNearBy('', new plus.maps.Point(lng, lat), self.searchNeary, 0)
// }, 100);
}
},
keySelect(item) {
let self = this;
let poi = item.point;
console.log("poipoi: " + JSON.stringify(poi));
self.setPoint(poi.getLng(), poi.getLat(), true, true)
self.mapHiden = false;
self.serarchText = '';
self.keyUser = item;
self.keyResult = [];
},
//搜索框获得焦点就隐藏地图
fusHiden(blone) {
let self = this;
self.mapHiden = blone
//失去焦点搜索附近
if (!blone) {
self.serarchText = '';
}
self.keyResult = [];
self.keyUser = {}
// if (!blone) {
// this.selectMap();
// } else {
// //获得焦点列表置空
// this.mapResult = [];
// }
},
//选择地址
selectAddress(item) {
let self = this;
console.log("item.city: " + JSON.stringify(item.city));
self.covers[0].address = item.city + item.address;
let poi = item.point;
//当前数据不给不选中
for (var i = 0, len = self.mapResult.length; i < len; i++) {
self.mapResult[i].check = false;
}
console.log("item: " + JSON.stringify(item));
//当前选中
item.check = true;
self.mapHiden = false;
//清空当前关键字搜索列表
self.keyResult = [];
//self.newMap()
setTimeout(function() {
self.setPoint(poi.getLng(), poi.getLat(), true)
}, 100)
},
//
//关键字搜索
onKeyInput(e) {
console.log('onKeyInput')
let self = this;
if (e.target.value == '') return;
// self.mapResult = []
// self.ab_.load(1)
self.searchKeyObj.poiSearchInCity("", e.target.value)
},
//移动获取中心点
selectMap(e) {
console.log('selectMap')
let self = this
self.mapResult = []
self.searchNeary = 300
try {
self.map.getCurrentCenter(function(state, point) {
console.log('getCurrentCenter back')
if (0 == state) {
//给经纬度和中心点赋值
//self.longitude = point.getLng()
//self.latitude = point.getLat()
try {
console.log("point: " + JSON.stringify(point));
self.setPoint(point.getLng(), point.getLat(), true)
// setTimeout(function() {
// self.ab_.load(1)
// self.searchObj.poiSearchNearBy('', point, self.searchNeary, 0)
// }, 100)
setTimeout(function() {
// self.ab_.load(1)
self.searchObj.poiSearchNearBy('', new plus.maps.Point(point.longitude, point.latitude), self.searchNeary,
0)
}, 100)
} catch (e) {
console.error(e)
}
} else {
console.log("Failed!");
}
console.log('getCurrentCenter back done')
})
} catch (e) {
console.error(e)
}
},
//经纬度赋值方法 index == 0 赋值当前位置
latOrLon(lng, lat, index) {
let self = this;
if (index == 0) {
self.longitude = lng;
self.latitude = lat;
}
self.covers[0].longitude = lng;
self.covers[0].latitude = lat;
},
//确定选择位置
sureMap() {
if (this.covers[0].address == '') {
uni.showModal({
// title: '提示',
content: '您尚未选择位置!',
showCancel: false,
success: function(res) {
if (res.confirm) {
console.log('用户点击确定');
} else if (res.cancel) {
console.log('用户点击取消');
}
}
});
} else {
this.$emit('getMapSite', this.covers)
}
},
backClik() {
// this.ab_.navBack()
this.$emit('hideModal')
},
//清空按钮
clearInput: function(event) {
this.inputClearValue = event.target.value;
if (event.target.value.length > 0) {
this.showClearIcon = true;
} else {
this.showClearIcon = false;
this.mapHiden = false;
}
},
}
}
</script>
<style lang='scss' scoped>
.map_address {
width: 100%;
min-height: 100vh;
background: #fff;
position: fixed;
top: 0;
left: 0;
z-index: 10000;
overflow: hidden;
.mapLoading2 {
width: 80rpx;
height: 80rpx;
position: absolute;
top: 15%;
left: 50%;
margin-left: -40rpx;
/* margin-top: -40rpx; */
z-index: 99999;
image {
width: 100%;
height: 100%;
}
}
.mapBox {
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
text-align: center;
.mapTitBack {
margin-left: 30upx;
}
.mapSure {
font-size: 28upx;
font-weight: bold;
text-align: center;
text {
margin-right: 30upx;
}
}
.mapTitBack {
font-size: 44upx;
}
.mapTitNanem {
color: #000;
font-size: 32upx;
}
}
.serchCont {
width: 100%;
height: 80upx;
display: flex;
justify-content: center;
align-items: center;
.serchBtn {
width: 96%;
height: 60upx;
background-color: #eee;
border-radius: 12upx;
text-align: center;
.icon {
padding: 0 15upx;
&.icon-del {
font-size: 38upx;
&:before {
content: "\e644";
}
}
&.icon-serach:before {
content: "\e61c";
}
}
}
.serchBtn1 {
width: 80% !important;
}
.clearText {
width: 10%;
text-align: center;
color: #6767EA;
font-size: 32upx;
}
}
.tmapList1 {
height: calc(100vh - 80upx - 44upx) !important;
}
.tmapList {
width: 100%;
height: calc(100vh - 80upx - 600upx - 44upx);
overflow-x: hidden;
overflow-y: auto;
border-top: 2upx solid #ccc;
.mapSing {
width: calc(100% - 20upx);
display: flex;
justify-content: space-between;
align-items: flex-start;
border-bottom: 2upx solid #ccc;
padding: 20upx 0;
margin-left: 20upx;
.mapleflt {
width: calc(100% - 80upx);
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
view {
width: 100%;
}
.weiz {
color: #333;
font-size: 28upx;
}
.adress {
color: gray;
font-size: 24upx;
margin-top: 10upx;
}
}
.mapright {
width: 80upx;
height: 80upx;
display: flex;
justify-content: center;
align-items: center;
image {
width: 32upx;
height: 32upx;
}
}
}
}
}
</style>
页面调用(此处删除部分代码)
<template>
<view class="card add_address">
<aCustom :isBack="true" :bgColor="aaa">
<block slot="content">收货地址</block>
</aCustom>
<view class="address-info">
<view class="unit name">
<view class="tit">收货人</view>
<view class="cont"><input v-model="recipient" maxlength='8' name="recipient" /></view>
</view>
<view class="unit phone">
<view class="tit">手机号码</view>
<view class="cont"><input v-model="phone" name="phone" maxlength='11' type='number' /></view>
</view>
<!-- #ifdef H5 || MP-WEIXIN -->
<view class="unit addr" @tap='chooseLocation'>
<view class="tit">所在地区</view>
<view class="cont">
<view class="adress">{{plan.address}}</view>
</view>
<view class="address_s"></view>
</view>
<!-- #endif -->
<!-- #ifdef APP-PLUS -->
<view class="unit addr" @tap='siteSelection'>
<view class="tit">所在地区</view>
<view class="cont">
<view class="adress">{{plan.address}}</view>
</view>
<view class="address_s"></view>
</view>
<!-- #endif -->
<view class="unit phone">
<view class="tit">详细地址</view>
<view class="cont"><input v-model="detail" placeholder="例如:道路/门牌号/小区/单元" name="detail" /></view>
</view>
</view>
<view class="btn" @tap="addAddresses">保存</view>
<map-sit :class="!showMap?'':'mapShow'" class='maphidden' ref="mapSite" @getMapSite="getMapSite" @hideModal='hideModal'></map-sit>
</view>
</template>
<script>
import mapSit from '../../../component/mapSite/siteSelection.vue'
var sHeight = 180
export default {
data() {
return {
aaa: 'bg-gradual-fff',
state: 0,
recipient: '',
phone: '',
address: '',
detail: '',
steps: {},
canPost: true,
latitude: 0,
longitude: 0,
line_address: [],
plans: [],
plan: {
address:'请在地图上点选位置'
},
travelDistance: 0,
includePoints: [],
markers: [],
polyline: [{
points: [],
color: "#FF4500",
width: 3,
dottedLine: true,
arrowLine: true
}],
flage:true,
showMap:false,
}
},
computed: {
...global.mapState(['$g_'])
},
components: {
//引用mSearch组件,如不需要删除即可
mapSit
},
onLoad: function(option) { //option为object类型,会序列化上个页面传递的参数
let self = this;
if (option.item && option.item.length > 0) {
let plan = JSON.parse(option.item);
self.plan = plan;
self.state = plan.ord;
self.recipient = plan.recipient;
self.phone = plan.phone;
self.address = plan.address;
self.detail = plan.detail;
}else{
}
},
onShow() {
},
methods: {
//获得选择地图数据
getMapSite(data){
console.log("data: " + JSON.stringify(data));
this.plan.address = data[0].address;
this.plan.lat = data[0].latitude;
this.plan.lng = data[0].longitude;
this.hideModal();
},
//关闭地图
hideModal(){
let self = this;
self.showMap = false;
},
//app时打开地图
siteSelection(){
let self = this;
console.log("self.plan: " + JSON.stringify(self.plan));
self.showMap = true;
self.$refs.mapSite.pushData(self.plan);
},
}
}
</script>
<style lang='scss' scoped>
.add_address{
min-height: 100vh;
background:#fff;
.mapShow{
display: block!important;
}
.maphidden{
display: none;
}
}
</style>
经过实际使用发现h5+提供的搜索api,搜索时会有很多地方遗漏,所以引入搞的地图api
修改组件如下
<template>
<view class="card map_address">
<view class="mapBox" :style="[{height:$g_.CustomBar + 'px'},{paddingTop:$g_.StatusBar + 'px'}]">
<view class="mapTitBack" @tap="backClik">
<text class="cuIcon-back"><span></span></text>
</view>
<view class="mapTitNanem">选择位置</view>
<view class="mapSure" @tap="sureMap">
<text>完成</text>
</view>
</view>
<view class="serchCont">
<input class="uni-input serchBtn" :class="mapHiden?'serchBtn1':''" :focus="mapHiden" v-model="serarchText" @input="onKeyInput"
placeholder="搜索地点" @focus='fusHiden(true)' placeholder-style='text-align: center' />
<text class="clearText" @tap='fusHiden(false)' v-if="mapHiden">取消</text>
</view>
<view class="" style="width: 100%; height: 600upx;overflow: hidden;" v-show="!mapHiden" @touchmove.stop="">
<map id="map1" ref="map1" style="width: 100%; height: 600upx;" @regionchange='selectMap'
show-location :scale="16"></map>
<!-- :markers="covers" -->
</view>
<view class="">
<view class="tmapList" :class="mapHiden?'tmapList1':''" v-if="!mapHiden">
<view class="mapSing" v-for="(item,index) in mapResult" :key='index' @tap='selectAddress(item)'>
<view class="mapleflt">
<view class="weiz">{{index == 0&&!mapHiden?'我的位置':item.name}} </view>
<view class="adress">{{item.address}}</view>
</view>
<view class="mapright">
<image src="../../../static/map/currentPos.png" mode="" v-if="item.check"></image>
</view>
</view>
</view>
<view class="tmapList" :class="mapHiden?'tmapList1':''" v-else>
<view class="mapSing" v-for="(item,index) in keyResult" :key='index' @tap='keySelect(item)'>
<view class="mapleflt">
<view class="weiz">{{item.name}} </view>
<view class="adress">{{item.address}}</view>
</view>
<view class="mapright">
<image src="../../../static/map/currentPos.png" mode="" v-if="item.check"></image>
</view>
</view>
</view>
<!-- <view class="mapLoading2" v-if="!shoeLoding">
<image src="../../../static/center/loading.png"></image>
</view> -->
</view>
</view>
</template>
<script>
import AMap from '../../lib/amap-wx.js'; //此处为引入高德js
export default {
data() {
return {
key: '9541ccc4a3eb95641300f91f3e9cb3d2',
addressName: '',
weather: {
hasData: false,
data: []
},
title: 'map',
searchNeary: 4000,
covers: [{
width: 20,
height: 20,
latitude: 31.972952,
longitude: 118.78025,
iconPath: '../../../static/map/location.png',
address: ''
}],
aaa: 'bg-gradual-fff',
map: null,
keyResult: [],
mapResult: [],
mapHiden: false,
inputClearValue: '',
showClearIcon: false,
serarchText: '',
keyUser: {},
shoeLoding: false,
}
},
computed: {
...global.mapState(['$g_'])
},
mounted() {
let that = this;
sHeight = uni.upx2px(360);
//#ifndef MP-WEIXIN
// document.querySelector('body').setAttribute('style', 'background-color:#ffffff');
//#endif
},
beforeDestroy() {
//#ifndef MP-WEIXIN
// document.querySelector('body').setAttribute('style', 'background-color:""')
//#endif
},
// onReady() {
// console.log('onReady')
// var mapCtx = uni.createMapContext('map1', this)
// // console.log(mapCtx.$getAppMap())
// this.map = mapCtx.$getAppMap()
// this.map.showUserLocation(true);
// },
onReady() {
console.log('onReady')
this.newMap()
this.amapPlugin = new AMap.AMapWX({
key: this.key
});
console.log(this.key)
// this.aMapSearchNearBy('',[114.30, 30.60], '武汉');
},
onLoad: function(option) { //option为object类型,会序列化上个页面传递的参数
},
onShow() {},
methods: {
// 高德地图查询周边
getPoiAround(keywords,centerPoint, city) {
console.log(this.amapPlugin)
console.log(keywords)
console.log(centerPoint)
console.log(city)
let self = this;
self.amapPlugin.getPoiAround({
keywords: keywords,
location: centerPoint[0] + ',' + centerPoint[1],
city: city,
success: function(data) {
// self.mapResult = data.poisData;
// for (var i = 0, len = self.mapResult.length; i < len; i++) {
// self.mapResult[i].check = false;
// }
// self.mapHiden = false;
// self.shoeLoding = false;
// console.log("回调成功1111111111: " + JSON.stringify(self.mapResult));
if(data.poisData){
self.getMapSta1(data.poisData,0)
}
},
fail:function(err){
self.shoeLoding = false;
}
})
},
//搜索查周边
getInputtips(keywords) {
let self = this;
console.log('执行getInputtips:' +keywords )
self.amapPlugin.getInputtips({
keywords: keywords,
success: function(data) {
// self.keyResult = data.tips;
// for (var i = 0, len = self.keyResult.length; i < len; i++) {
// self.keyResult[i].check = false;
// }
// self.mapHiden = true;
// self.shoeLoding = false;
// console.log("回调成功222222: " + JSON.stringify(self.keyResult));
console.log(data.tips)
if(data.tips){
self.getMapSta1(data.tips,1)
}
},
fail:function(err){
self.shoeLoding = false;
}
})
},
//公共赋值
getMapSta1(data,index){
let self = this;
console.log("公共赋值data: " + JSON.stringify(data));
for (var i = 0, len = data.length; i < len; i++) {
// data[i].check = false;
if(data[i].location.length<=0){
data.splice(i,1);
}
len-=1;
}
if(index == 0){
self.mapResult = data;
self.mapHiden = false;
console.log("回调成功11111 +++ mapResult : " + JSON.stringify(self.mapResult));
}else{
self.keyResult = data
self.mapHiden = true;
console.log("回调成功222222 +++ keyResult : " + JSON.stringify(self.keyResult));
}
self.shoeLoding = false;
},
pushData(data) {
console.log("data: " + JSON.stringify(data));
setTimeout(() => {
console.log("data.lng: " + JSON.stringify(data.lng));
this.setPoint(data.lng, data.lat, true, true)
}, 500)
},
newMap() {
let self = this;
var mapCtx = uni.createMapContext('map1', self)
// console.log(mapCtx.$getAppMap())
self.map = mapCtx.$getAppMap()
self.map.showUserLocation(true);
self.searchKeyObj = new plus.maps.Search(self.map);
self.searchKeyObj.onPoiSearchComplete = function(state, result) {
console.log('onPoiSearchComplete ' + state)
if (state == 0) {
if (result.currentNumber <= 0) {
// self.ab_.load(0)
// self.shoeLoding = true
console.log("没有检索到结果");
} else {
// self.ab_.load(0)
// self.shoeLoding = true
self.keyResult = result.poiList;
self.keyUser = self.keyResult[0]
}
} else {
// self.ab_.load(0)
// self.shoeLoding = true
console.log("检索失败");
}
}
self.searchObj = new plus.maps.Search(self.map);
// self.searchObj.onPoiSearchComplete = function(state, result) {
// console.log('onPoiSearchComplete ' + state)
// if (state == 0) {
// if (result.currentNumber <= 0) {
// // self.ab_.load(0)
// // self.shoeLoding = true
// console.log("没有检索到结果");
// if (self.searchNeary < 5000) {
// self.searchNeary *= 2
// var searchNeary = self.searchNeary
// setTimeout(function() {
// if (self.mapResult.length <= 0 && searchNeary == self.searchNeary) {
// // self.ab_.load(1)
// self.shoeLoding = false;
// self.searchObj.poiSearchNearBy('', new plus.maps.Point(self.covers[0].longitude, self.covers[0].latitude),
// self.searchNeary, 0)
// } else {
// // self.ab_.load(0)
// // self.shoeLoding = true
// }
// }, 100)
// } else {
// // self.ab_.load(0)
// // self.shoeLoding = true
// }
// } else {
// // self.ab_.load(0)
// // self.shoeLoding = true
// for (var i = 0, len = result.poiList.length; i < len; i++) {
// result.poiList[i].check = false;
// }
// console.log("self.keyUser: " + JSON.stringify(self.keyUser));
// if (self.keyUser && self.keyUser.point) {
// result.poiList.unshift(self.keyUser);
// self.keyUser = {};
// }
// self.mapResult = result.poiList
// }
// } else {
// // self.ab_.load(0)
// // self.shoeLoding = true
// console.log("检索失败");
// }
// }
},
//搜索框获得焦点就隐藏地图
fusHiden(blone) {
let self = this;
self.mapHiden = blone
//失去焦点搜索附近
if (!blone) {
self.serarchText = '';
}
self.keyResult = [];
self.keyUser = {}
self.shoeLoding = false;
// if (!blone) {
// this.selectMap();
// } else {
// //获得焦点列表置空
// this.mapResult = [];
// }
},
setPoint(lng, lat, cover, center) {
let self = this;
console.log('setPoint')
if (cover) {
self.covers[0].longitude = lng
self.covers[0].latitude = lat
self.getPoiAround('',[self.covers[0].longitude, self.covers[0].latitude], '');
}
self.map.removeOverlay(self.marker);
self.marker=new plus.maps.Marker(new plus.maps.Point(lng,lat));
self.marker.setIcon("./static/map/location.png");
// marker.setLabel("HBuilder");
var bubble = new plus.maps.Bubble("打造最好的HTML5移动开发工具");
self.marker.setBubble(bubble);
self.map.addOverlay(self.marker);
if (center) {
self.map.setCenter(new plus.maps.Point(lng, lat))
// setTimeout(function() {
// self.searchObj.poiSearchNearBy('', new plus.maps.Point(lng, lat), self.searchNeary, 0)
// }, 100);
}
},
keySelect(item) {
let self = this;
// let poi = item.location;
console.log(" item.location111: " + JSON.stringify( item.location));
if(item.location.length<=0)return;
let poi = item.location.split(',');;
console.log("poipoi: " + JSON.stringify(poi));
self.setPoint(poi[0], poi[1], false, true)
self.mapHiden = false;
self.serarchText = '';
self.keyUser = item;
self.keyResult = [];
},
//选择地址
selectAddress(item) {
let self = this;
if(item.location.length<=0)return;
console.log("item.city: " + JSON.stringify(item));
self.covers[0].address = item.pname + item.cityname + item.adname + item.address;
let poi = item.location.split(',');;
//当前数据不给不选中
for (var i = 0, len = self.mapResult.length; i < len; i++) {
self.mapResult[i].check = false;
}
console.log("item: " + JSON.stringify(item));
//当前选中
item.check = true;
self.mapHiden = false;
//清空当前关键字搜索列表
self.keyResult = [];
self.setPoint(poi[0] , poi[1] , false)
// var marker=new plus.maps.Marker(new plus.maps.Point(poi[0] , poi[1] ));
// marker.setIcon("/logo.png");
// self.map.addOverlay(marker);
// self.newMap()
// setTimeout(function() {
// self.setPoint(poi[0] , poi[1] , true,true)
// }, 100)
},
//
//关键字搜索
onKeyInput(e) {
console.log('onKeyInput')
let self = this;
if (e.target.value == '') return;
// self.mapResult = []
// self.ab_.load(1)
// self.searchKeyObj.poiSearchInCity("", e.target.value)
self.getInputtips(e.target.value,['', ''], '');
},
//移动获取中心点
selectMap(e) {
console.log('selectMap')
let self = this
self.mapResult = []
self.searchNeary = 300
try {
self.map.getCurrentCenter(function(state, point) {
console.log('getCurrentCenter back')
if (0 == state) {
//给经纬度和中心点赋值
//self.longitude = point.getLng()
//self.latitude = point.getLat()
try {
console.log("point: " + JSON.stringify(point));
self.setPoint(point.getLng(), point.getLat(), true)
// setTimeout(function() {
// self.ab_.load(1)
// self.searchObj.poiSearchNearBy('', point, self.searchNeary, 0)
// }, 100)
// setTimeout(function() {
// // self.ab_.load(1)
// self.searchObj.poiSearchNearBy('', new plus.maps.Point(point.longitude, point.latitude), self.searchNeary,
// 0)
// }, 100)
} catch (e) {
console.error(e)
}
} else {
console.log("Failed!");
}
console.log('getCurrentCenter back done')
})
} catch (e) {
console.error(e)
}
},
//经纬度赋值方法 index == 0 赋值当前位置
latOrLon(lng, lat, index) {
let self = this;
if (index == 0) {
self.longitude = lng;
self.latitude = lat;
}
self.covers[0].longitude = lng;
self.covers[0].latitude = lat;
},
//确定选择位置
sureMap() {
if (this.covers[0].address == '') {
uni.showModal({
// title: '提示',
content: '您尚未选择位置!',
showCancel: false,
success: function(res) {
if (res.confirm) {
console.log('用户点击确定');
} else if (res.cancel) {
console.log('用户点击取消');
}
}
});
} else {
this.$emit('getMapSite', this.covers)
}
},
backClik() {
// this.ab_.navBack()
this.$emit('hideModal')
},
//清空按钮
clearInput: function(event) {
this.inputClearValue = event.target.value;
if (event.target.value.length > 0) {
this.showClearIcon = true;
} else {
this.showClearIcon = false;
this.mapHiden = false;
}
},
}
}
</script>
<style lang='scss' scoped>
.map_address {
width: 100%;
min-height: 100vh;
background: #fff;
position: fixed;
top: 0;
left: 0;
z-index: 10000;
overflow: hidden;
.mapLoading2 {
width: 80rpx;
height: 80rpx;
position: absolute;
top: 15%;
left: 50%;
margin-left: -40rpx;
/* margin-top: -40rpx; */
z-index: 99999;
image {
width: 100%;
height: 100%;
}
}
.mapBox {
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
text-align: center;
.mapTitBack {
margin-left: 30upx;
}
.mapSure {
font-size: 28upx;
font-weight: bold;
text-align: center;
text {
margin-right: 30upx;
}
}
.mapTitBack {
font-size: 44upx;
}
.mapTitNanem {
color: #000;
font-size: 32upx;
}
}
.serchCont {
width: 100%;
height: 80upx;
display: flex;
justify-content: center;
align-items: center;
.serchBtn {
width: 96%;
height: 60upx;
background-color: #eee;
border-radius: 12upx;
text-align: center;
.icon {
padding: 0 15upx;
&.icon-del {
font-size: 38upx;
&:before {
content: "\e644";
}
}
&.icon-serach:before {
content: "\e61c";
}
}
}
.serchBtn1 {
width: 80% !important;
}
.clearText {
width: 10%;
text-align: center;
color: #6767EA;
font-size: 32upx;
}
}
.tmapList1 {
height: calc(100vh - 80upx - 44upx) !important;
}
.tmapList {
width: 100%;
height: calc(100vh - 80upx - 600upx - 120upx - 44upx);
overflow-x: hidden;
overflow-y: scroll;
border-top: 2upx solid #ccc;
position: static;
-webkit-overflow-scrolling: touch;
.mapSing {
width: calc(100% - 20upx);
display: flex;
justify-content: space-between;
align-items: flex-start;
border-bottom: 2upx solid #ccc;
padding: 20upx 0;
margin-left: 20upx;
.mapleflt {
width: calc(100% - 80upx);
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
view {
width: 100%;
}
.weiz {
color: #333;
font-size: 28upx;
}
.adress {
color: gray;
font-size: 24upx;
margin-top: 10upx;
}
}
.mapright {
width: 80upx;
height: 80upx;
display: flex;
justify-content: center;
align-items: center;
image {
width: 32upx;
height: 32upx;
}
}
}
}
}
</style>
此方法特定的unisdk版本会造成地图加载不出来,需要重新初始化,ios初始化得不得当前位置,故组件修改如下
在这里插入代码片
```<template>
<view class="card map_address">
<view class="mapBox" :style="[{height:$g_.CustomBar + 'px'},{paddingTop:$g_.StatusBar + 'px'}]">
<view class="mapTitBack" @tap="backClik">
<text class="cuIcon-back"><span></span></text>
</view>
<view class="mapTitNanem">选择位置</view>
<view class="mapSure" @tap="sureMap">
<text>完成</text>
</view>
</view>
<view class="serchCont">
<input class="uni-input serchBtn" :class="mapHiden?'serchBtn1':''" :focus="mapHiden" v-model="serarchText" @input="onKeyInput"
placeholder="搜索地点" @focus='fusHiden(true)' placeholder-style='text-align: center' />
<text class="clearText" @tap='fusHiden(false)' v-if="mapHiden">取消</text>
</view>
<view class="" style="width: 100%; height: 600upx;overflow: hidden;" v-show="!mapHiden" @touchmove.stop="">
<map id="map1" ref="map1" style="width: 100%; height: 600upx;" @regionchange='selectMap'
show-location :scale="16"></map>
<!-- :markers="covers" -->
</view>
<view class="">
<view class="tmapList" :class="mapHiden?'tmapList1':''" v-if="!mapHiden">
<view class="mapSing" v-for="(item,index) in mapResult" :key='index' @tap='selectAddress(item)'>
<view class="mapleflt">
<view class="weiz">{{index == 0&&!mapHiden?'我的位置':item.name}} </view>
<view class="adress">{{item.address}}</view>
</view>
<view class="mapright">
<image src="../../static/map/currentPos.png" mode="" v-if="item.check"></image>
</view>
</view>
</view>
<view class="tmapList" :class="mapHiden?'tmapList1':''" v-else>
<view class="mapSing" v-for="(item,index) in keyResult" :key='index' @tap='keySelect(item)'>
<view class="mapleflt">
<view class="weiz">{{item.name}} </view>
<view class="adress">{{ item.address }}</view>
</view>
<view class="mapright">
<image src="../../static/map/currentPos.png" mode="" v-if="item.check"></image>
</view>
</view>
</view>
<!-- <view class="mapLoading2" v-if="!shoeLoding">
<image src="../../../static/center/loading.png"></image>
</view> -->
</view>
</view>
</template>
<script>
import AMap from '../../lib/amap-wx.js'; //如:../../libs/amap-wx.js
export default {
data() {
return {
key: '9541ccc4a3eb95641300f91f3e9cb3d2',
addressName: '',
weather: {
hasData: false,
data: []
},
title: 'map',
searchNeary: 4000,
covers: [{
width: 20,
height: 20,
latitude: 31.972952,
longitude: 118.78025,
iconPath: '../../../static/map/location.png',
address: ''
}],
aaa: 'bg-gradual-fff',
map: null,
keyResult: [],
mapResult: [],
mapHiden: false,
inputClearValue: '',
showClearIcon: false,
serarchText: '',
keyUser: {},
shoeLoding: false,
}
},
computed: {
...global.mapState(['$g_'])
},
mounted() {
let that = this;
sHeight = uni.upx2px(360);
//#ifndef MP-WEIXIN
// document.querySelector('body').setAttribute('style', 'background-color:#ffffff');
//#endif
},
beforeDestroy() {
//#ifndef MP-WEIXIN
// document.querySelector('body').setAttribute('style', 'background-color:""')
//#endif
},
// onReady() {
// console.log('onReady')
// var mapCtx = uni.createMapContext('map1', this)
// // console.log(mapCtx.$getAppMap())
// this.map = mapCtx.$getAppMap()
// this.map.showUserLocation(true);
// },
onReady() {
console.log('onReady')
this.newMap()
this.amapPlugin = new AMap.AMapWX({
key: this.key
});
console.log(this.key)
// this.aMapSearchNearBy('',[114.30, 30.60], '武汉');
},
onLoad: function(e) { //option为object类型,会序列化上个页面传递的参数
this._select = e.s
conosle.log('接收到seldrct' +this._select )
},
onShow() {},
methods: {
// 高德地图查询周边
getPoiAround(keywords,centerPoint, city) {
console.log(this.amapPlugin)
console.log(keywords)
console.log(centerPoint)
console.log(city)
let self = this;
if (!self.amapPlugin) {
self.amapPlugin = new AMap.AMapWX({
key: this.key
});
}
console.log('amapPlugin', self.amapPlugin)
self.amapPlugin.getPoiAround({
keywords: keywords,
location: centerPoint[0] + ',' + centerPoint[1],
city: city,
success: function(data) {
// self.mapResult = data.poisData;
// for (var i = 0, len = self.mapResult.length; i < len; i++) {
// self.mapResult[i].check = false;
// }
// self.mapHiden = false;
// self.shoeLoding = false;
// console.log("回调成功1111111111: " + JSON.stringify(self.mapResult));
if(data.poisData){
self.getMapSta1(data.poisData,0)
}
},
fail:function(err){
self.shoeLoding = false;
}
})
},
//搜索查周边
getInputtips(keywords) {
let self = this;
console.log('执行getInputtips:' +keywords )
console.log('self.amapPlugin', self.amapPlugin)
if (!self.amapPlugin) {
self.amapPlugin = new AMap.AMapWX({
key: this.key
});
}
self.amapPlugin.getInputtips({
keywords: keywords,
success: function(data) {
// self.keyResult = data.tips;
// for (var i = 0, len = self.keyResult.length; i < len; i++) {
// self.keyResult[i].check = false;
// }
// self.mapHiden = true;
// self.shoeLoding = false;
// console.log("回调成功222222: " + JSON.stringify(self.keyResult));
console.log(data.tips)
if(data.tips){
self.getMapSta1(data.tips,1)
}
},
fail:function(err){
self.shoeLoding = false;
}
})
},
//公共赋值
getMapSta1(data,index){
let self = this;
console.log("公共赋值data: " + JSON.stringify(data));
for (var i = 0, len = data.length; i < len; i++) {
// data[i].check = false;
if(data[i].location.length<=0){
data.splice(i,1);
}
len-=1;
}
if(index == 0){
self.mapResult = data;
self.mapHiden = false;
console.log("回调成功11111 +++ mapResult : " + JSON.stringify(self.mapResult));
}else{
for (let i=0,len=data.length;i<len;i++) {
if(typeof( data[i].address.length<=0) != 'string' ){
data[i].address = data[i].district
}
}
self.keyResult = data
self.mapHiden = true;
console.log("回调成功222222 +++ keyResult : " + JSON.stringify(self.keyResult));
}
self.shoeLoding = false;
},
pushData(data) {
console.log("data: " + JSON.stringify(data));
setTimeout(() => {
console.log("data.lng: " + JSON.stringify(data.lng));
this.setPoint(data.lng, data.lat, true, true)
}, 500)
},
newMap() {
let self = this;
var mapCtx = uni.createMapContext('map1', self)
// console.log(mapCtx.$getAppMap())
self.map = mapCtx.$getAppMap()
//self.map.showUserLocation(true);
uni.getLocation({
altitude:true,
success: function(res) {
console.log('success ' + JSON.stringify(res))
self.setPoint(res.longitude, res.latitude, true, true)
},
fail(err) {
console.error('fail ' + JSON.stringify(err))
},
})
self.searchKeyObj = new plus.maps.Search(self.map);
self.searchKeyObj.onPoiSearchComplete = function(state, result) {
console.log('onPoiSearchComplete ' + state)
if (state == 0) {
if (result.currentNumber <= 0) {
// self.ab_.load(0)
// self.shoeLoding = true
console.log("没有检索到结果");
} else {
// self.ab_.load(0)
// self.shoeLoding = true
self.keyResult = result.poiList;
self.keyUser = self.keyResult[0]
}
} else {
// self.ab_.load(0)
// self.shoeLoding = true
console.log("检索失败");
}
}
self.searchObj = new plus.maps.Search(self.map);
// self.searchObj.onPoiSearchComplete = function(state, result) {
// console.log('onPoiSearchComplete ' + state)
// if (state == 0) {
// if (result.currentNumber <= 0) {
// // self.ab_.load(0)
// // self.shoeLoding = true
// console.log("没有检索到结果");
// if (self.searchNeary < 5000) {
// self.searchNeary *= 2
// var searchNeary = self.searchNeary
// setTimeout(function() {
// if (self.mapResult.length <= 0 && searchNeary == self.searchNeary) {
// // self.ab_.load(1)
// self.shoeLoding = false;
// self.searchObj.poiSearchNearBy('', new plus.maps.Point(self.covers[0].longitude, self.covers[0].latitude),
// self.searchNeary, 0)
// } else {
// // self.ab_.load(0)
// // self.shoeLoding = true
// }
// }, 100)
// } else {
// // self.ab_.load(0)
// // self.shoeLoding = true
// }
// } else {
// // self.ab_.load(0)
// // self.shoeLoding = true
// for (var i = 0, len = result.poiList.length; i < len; i++) {
// result.poiList[i].check = false;
// }
// console.log("self.keyUser: " + JSON.stringify(self.keyUser));
// if (self.keyUser && self.keyUser.point) {
// result.poiList.unshift(self.keyUser);
// self.keyUser = {};
// }
// self.mapResult = result.poiList
// }
// } else {
// // self.ab_.load(0)
// // self.shoeLoding = true
// console.log("检索失败");
// }
// }
},
//搜索框获得焦点就隐藏地图
fusHiden(blone) {
let self = this;
self.mapHiden = blone
//失去焦点搜索附近
if (!blone) {
self.serarchText = '';
}
self.keyResult = [];
self.keyUser = {}
self.shoeLoding = false;
// if (!blone) {
// this.selectMap();
// } else {
// //获得焦点列表置空
// this.mapResult = [];
// }
},
setPoint(lng, lat, cover, center) {
let self = this;
console.log('setPoint')
if (cover) {
self.covers[0].longitude = lng
self.covers[0].latitude = lat
self.getPoiAround('',[self.covers[0].longitude, self.covers[0].latitude], '');
}
self.map.removeOverlay(self.marker);
self.marker=new plus.maps.Marker(new plus.maps.Point(lng,lat));
self.marker.setIcon("./static/map/location.png");
// marker.setLabel("HBuilder");
var bubble = new plus.maps.Bubble("打造最好的HTML5移动开发工具");
self.marker.setBubble(bubble);
self.map.addOverlay(self.marker);
if (center) {
self.map.setCenter(new plus.maps.Point(lng, lat))
// setTimeout(function() {
// self.searchObj.poiSearchNearBy('', new plus.maps.Point(lng, lat), self.searchNeary, 0)
// }, 100);
}
},
keySelect(item) {
let self = this;
// let poi = item.location;
console.log(" item.location111: " + JSON.stringify( item.location));
if(item.location.length<=0)return;
let poi = item.location.split(',');;
console.log("poipoi: " + JSON.stringify(poi));
self.setPoint(poi[0], poi[1], false, true)
self.mapHiden = false;
self.serarchText = '';
self.keyUser = item;
self.keyResult = [];
},
//选择地址
selectAddress(item) {
let self = this;
if(item.location.length<=0)return;
// console.log("item.city: " + JSON.stringify(item));
self.covers[0].address = item.pname + item.cityname + item.adname + item.address;
let poi = item.location.split(',');;
//当前数据不给不选中
for (var i = 0, len = self.mapResult.length; i < len; i++) {
if(item.id == self.mapResult[i].id){
self.mapResult[i].check = true;
}else{
self.mapResult[i].check = false;
}
}
console.log("selectAddressitem: " + JSON.stringify(item));
//当前选中
// item.check = true;
console.log("item.check: " + JSON.stringify(item.check));
self.mapHiden = false;
self.$forceUpdate();
//清空当前关键字搜索列表
self.keyResult = [];
self.setPoint(poi[0] , poi[1] , false)
// var marker=new plus.maps.Marker(new plus.maps.Point(poi[0] , poi[1] ));
// marker.setIcon("/logo.png");
// self.map.addOverlay(marker);
// self.newMap()
// setTimeout(function() {
// self.setPoint(poi[0] , poi[1] , true,true)
// }, 100)
},
//
//关键字搜索
onKeyInput(e) {
console.log('onKeyInput')
let self = this;
if (e.target.value == '') return;
// self.mapResult = []
// self.ab_.load(1)
// self.searchKeyObj.poiSearchInCity("", e.target.value)
self.getInputtips(e.target.value,['', ''], '');
},
//移动获取中心点
selectMap(e) {
console.log('selectMap')
let self = this
if (!self.map) {
console.log('============== created ================')
this.newMap()
}
self.mapResult = []
self.searchNeary = 300
try {
self.map.getCurrentCenter(function(state, point) {
console.log('getCurrentCenter back')
if (0 == state) {
//给经纬度和中心点赋值
//self.longitude = point.getLng()
//self.latitude = point.getLat()
try {
console.log("point: " + JSON.stringify(point));
self.setPoint(point.getLng(), point.getLat(), true)
// setTimeout(function() {
// self.ab_.load(1)
// self.searchObj.poiSearchNearBy('', point, self.searchNeary, 0)
// }, 100)
// setTimeout(function() {
// // self.ab_.load(1)
// self.searchObj.poiSearchNearBy('', new plus.maps.Point(point.longitude, point.latitude), self.searchNeary,
// 0)
// }, 100)
} catch (e) {
console.error(e)
}
} else {
console.log("Failed!");
}
console.log('getCurrentCenter back done')
})
} catch (e) {
console.error(e)
}
},
//经纬度赋值方法 index == 0 赋值当前位置
latOrLon(lng, lat, index) {
let self = this;
if (index == 0) {
self.longitude = lng;
self.latitude = lat;
}
self.covers[0].longitude = lng;
self.covers[0].latitude = lat;
},
//确定选择位置
sureMap() {
console.log(11111111111111111)
console.log(this._select)
if (this.covers[0].address == '') {
uni.showModal({
// title: '提示',
content: '您尚未选择位置!',
showCancel: false,
success: function(res) {
if (res.confirm) {
console.log('用户点击确定');
} else if (res.cancel) {
console.log('用户点击取消');
}
}
});
} else {
console.log(this._select)
if(!this._select){
this.$emit('getMapSite', this.covers)
}else{
this.$center.$abActBack('choiceSite', [null, this.covers])
// #ifdef APP-PLUS
this.ab_.navBack()
// #endif
}
}
},
backClik() {
if(this._select){
this.ab_.navBack()
}
this.$emit('hideModal')
},
//清空按钮
clearInput: function(event) {
this.inputClearValue = event.target.value;
if (event.target.value.length > 0) {
this.showClearIcon = true;
} else {
this.showClearIcon = false;
this.mapHiden = false;
}
},
}
}
</script>
<style lang='scss' scoped>
.map_address {
width: 100%;
min-height: 100vh;
background: #fff;
position: fixed;
top: 0;
left: 0;
z-index: 10000;
overflow: hidden;
.mapLoading2 {
width: 80rpx;
height: 80rpx;
position: absolute;
top: 15%;
left: 50%;
margin-left: -40rpx;
/* margin-top: -40rpx; */
z-index: 99999;
image {
width: 100%;
height: 100%;
}
}
.mapBox {
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
text-align: center;
.mapTitBack {
margin-left: 30upx;
}
.mapSure {
font-size: 28upx;
font-weight: bold;
text-align: center;
text {
margin-right: 30upx;
}
}
.mapTitBack {
font-size: 44upx;
}
.mapTitNanem {
color: #000;
font-size: 32upx;
}
}
.serchCont {
width: 100%;
height: 80upx;
display: flex;
justify-content: center;
align-items: center;
.serchBtn {
width: 96%;
height: 60upx;
background-color: #eee;
border-radius: 12upx;
text-align: center;
.icon {
padding: 0 15upx;
&.icon-del {
font-size: 38upx;
&:before {
content: "\e644";
}
}
&.icon-serach:before {
content: "\e61c";
}
}
}
.serchBtn1 {
width: 80% !important;
}
.clearText {
width: 10%;
text-align: center;
color: #6767EA;
font-size: 32upx;
}
}
.tmapList1 {
height: calc(100vh - 80upx - 44upx) !important;
}
.tmapList {
width: 100%;
height: calc(100vh - 80upx - 600upx - 120upx - 44upx);
overflow-x: hidden;
overflow-y: scroll;
border-top: 2upx solid #ccc;
position: static;
-webkit-overflow-scrolling: touch;
.mapSing {
width: calc(100% - 20upx);
display: flex;
justify-content: space-between;
align-items: flex-start;
border-bottom: 2upx solid #ccc;
padding: 20upx 0;
margin-left: 20upx;
.mapleflt {
width: calc(100% - 80upx);
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
view {
width: 100%;
}
.weiz {
color: #333;
font-size: 28upx;
}
.adress {
color: gray;
font-size: 24upx;
margin-top: 10upx;
}
}
.mapright {
width: 80upx;
height: 80upx;
display: flex;
justify-content: center;
align-items: center;
image {
width: 32upx;
height: 32upx;
}
}
}
}
}
</style>