uniapp地图基本使用及解决添加markers不生效问题?
uniapp地图使用
App端 通过 nvue 页面实现地图
文章目录
- uniapp地图使用
- 效果图
- template
- js
- 添加 marker
- 使用地图查看位置
- 移到到当前位置
效果图
template
<template>
<view class="mapWrap">
<!-- #ifdef APP-NVUE -->
<map class="map-container" id="map" :longitude="location.lng" :latitude="location.lat"
:show-location="true" :enable-3D="enable3D" :markers="markers" :include-points="includePoints" @callouttap="oncallouttap">
</map>
<!-- 定位当前位置 -->
<cover-view class="myLocation fcc">
<cover-image class="img" src="@/static/image/icon/currnet_location.png" @click="moveToMyLocation"></cover-image>
</cover-view>
<!-- #endif -->
</view>
</template>
js
添加 marker
使用地图查看位置
移到到当前位置
<script>
export default {
data() {
return {
location: {
lng: 114.058279,
lat: 22.505375
},
markers: [],
includePoints: []
}
},
onLoad() {
let tmpLocation = this.$store.state.location;
if (tmpLocation.lng) {
this.location = tmpLocation;
}
},
onReady() {
this.map = uni.createMapContext("map", this);
},
methods: {
getData() {
// ....
// 测试数据
this.dataList = [
{
name: "长安街",
location: {
lat: 39.907145,
lng: 116.396651
}
},
{
name: "天安门",
location: {
lat: 39.908823,
lng: 116.39747
}
}
]
// 添加 marker
this.addMarkers();
},
/**
* 添加marker
*/
addMarkers() {
let markerList = [];
this.batteryList.forEach((item, index) => {
let location = item.location;
if (location) {
// 直接使用 this.markers.push()方式,无法添加 marker
markerList.push({
id: Number(index + 1),
latitude: Number(location.lat),
longitude: Number(location.lng),
title: item.name,
zIndex: '1',
rotate: 0,
width: 30,
height: 30,
anchor: {
x: 0.5,
y: 1
},
callout: {
content: item.name,
color: '#fff',
fontSize: 10,
borderRadius: 4,
borderWidth: 1,
borderColor: '#fb6620',
bgColor: '#f7b733',
padding: '5',
display: 'ALWAYS'
},
iconPath: '/static/image/icon/location01.png'
})
}
this.markers = markerList;
})
},
/**
* 气泡事件
*/
oncallouttap(e) {
const { markerId } = e.detail;
const marker = this.markers.find((item) => item.id === markerId);
// 使用地图查看位置
uni.openLocation({
latitude: marker.latitude,
longitude: marker.longitude,
name: marker.title,
success: (res) => {
console.log('success');
}
});
},
/**
* 移到到当前位置
*/
moveToMyLocation() {
let latitude = this.location.lat;
let longitude = this.location.lng;
this.map.moveToLocation({
latitude,
longitude,
success: (res) => {
this.includePoints = [{
latitude,
longitude
}];
}
});
}
}
}
</script>