zhangxiao
2024-08-20 e47b788ff5f5c699c682999c95da17eb284ca21d
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
<template>
    <div style="display: none">
        <div ref="mapMarkerContainer">
            <slot></slot>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { cloneDeep, isEqual } from "lodash-es";
 
const props = withDefaults(
    defineProps<{
        options: AMap.MarkerOptions;
    }>(),
    {
        options: () => {
            return {
                content: ""
            };
        }
    }
);
const emits = defineEmits<{
    (e: "dbclick"): void;
    (e: "click"): void;
    (e: "mouseover"): void;
    (e: "mouseout"): void;
}>();
 
const slots = useSlots();
 
const map = inject<Ref<AMap.Map>>("map");
 
let marker: AMap.Marker;
 
const mapMarkerContainer = ref<HTMLElement>();
 
let privateOptions: AMap.MarkerOptions;
 
watchEffect(() => {
    if (!map || !map.value) return;
    if (isEqual(privateOptions, props.options)) return;
    if (marker) {
        map.value.remove(marker);
        map.value.setCenter(props.options.position || [0, 0]);
    }
    privateOptions = cloneDeep(props.options);
    if (slots?.default) {
        if (!privateOptions.label) {
            privateOptions.label = { content: "", direction: "right", offset: [5, -15] };
        }
        privateOptions.label.content = mapMarkerContainer.value?.innerHTML || "";
    }
    marker = new AMap.Marker(privateOptions);
    map.value.add(marker);
    marker.on("dblclick", () => {
        emits("dbclick");
    });
    marker.on("click", () => {
        emits("click");
    });
    marker.on("mouseover", () => {
        emits("mouseover");
    });
    marker.on("mouseout", () => {
        emits("mouseout");
    });
});
</script>
<style lang="scss" scoped></style>