-
Notifications
You must be signed in to change notification settings - Fork 1
/
vue-leaflet-custom-marker.vue
113 lines (111 loc) · 2.4 KB
/
vue-leaflet-custom-marker.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<template>
<div class="marker-wrapper">
<slot />
</div>
</template>
<script>
import L from 'leaflet'
import { Icon } from 'leaflet/src/layer/marker/Icon'
import { findRealParent } from 'vue2-leaflet/src/utils/utils.js'
export default {
props: {
marker: {
type: Object,
default: undefined
},
alignment: {
type: String,
default: 'center'
},
offsetX: {
type: Number,
default: 0
},
offsetY: {
type: Number,
default: 0
}
},
data () {
return {
leafMarker: undefined
}
},
mounted () {
this.leafMarker = L.marker([this.marker.lat, this.marker.lng], {
icon: new CustomMarker({ html: this.$el })
})
this.leafMarker.addTo(findRealParent(this.$parent).mapObject)
this.computeAlignment(this.alignment)
},
watch: {
alignment (alignment) {
this.computeAlignment(alignment)
},
marker (marker) {
this.leafMarker.setLatLng(marker)
}
},
methods: {
computeAlignment (alignment) {
const div = this.$el
let x = 0
let y = 0
switch (alignment) {
case 'top':
y -= div.offsetHeight
x -= div.offsetHeight / 2
break
case 'bottom':
x = x - div.offsetWidth / 2
break
case 'left':
x = x - div.offsetWidth
y = y - div.offsetHeight / 2
break
case 'right':
y = y - div.offsetHeight / 2
break
case 'center':
x -= div.offsetWidth / 2
y -= div.offsetHeight / 2
break
case 'topleft':
x = -div.offsetWidth
y = -div.offsetHeight
break
case 'topright':
y = y - div.offsetHeight
break
case 'bottomleft':
x = x - div.offsetWidth
break
case 'bottomright':
break
default:
throw new Error('Invalid alignment type of custom marker!')
}
div.style.left = x + this.offsetX + 'px'
div.style.top = y + this.offsetY + 'px'
}
},
beforeDestroy () {
if (this.leafMarker) {
this.leafMarker.remove()
}
}
}
export var CustomMarker = Icon.extend({
options: {},
createIcon: function () {
const div = document.createElement('div')
div.appendChild(this.options.html)
return div
}
})
</script>
<style scoped>
.marker-wrapper {
position: absolute;
}
</style>