我在Vue组件中创建了一个Google Map自定义标记。我已经设置了draggable="true",但标记不可拖动。如何使标记可拖动并在拖动后获得坐标?
/////////////////////////////////////////////////////////////
// basemap
<template>
<div>
<GmapMap :style="'height:500px'" :center="center" :zoom="zoom">
<Location :location="location1"/>
</GmapMap>
</div>
</template>
////////////////////////////////////////////////////////
// Location
<template>
<div>
<GmapCustomMarker
ref="editMarker"
:marker="location.pos"
:draggable="true"
class="g_marker"
alignment="center"
:z-index="999"
>
<div style="background-color: red; width: 50px; height: 50px; border: 2px solid black;"></div>
</GmapCustomMarker>
</div>
</template>
<script>
import GmapCustomMarker from "vue2-gmap-custom-marker";
我猜您正在使用vue2-gmap-custom-marker
包,对吧?如果是这样,它似乎不支持拖动选项。但以下示例演示了如何将可拖动标记实现为Vue组件(基于此示例(:
<template>
<div :draggable="true" :style="{'position': 'absolute'}">
<slot />
</div>
</template>
<script>
import * as VueGoogleMaps from "vue2-google-maps";
/* global google */
export default {
mixins: [VueGoogleMaps.MapElementMixin],
props: {
position: {
type: Object,
default: undefined
}
},
methods: {},
data() {
return {
current: null,
origin: null
};
},
provide() {
const self = this;
return this.$mapPromise.then(map => {
class Overlay extends google.maps.OverlayView {
constructor(map) {
super();
this.setMap(map);
self.current = new google.maps.LatLng(
self.position.lat,
self.position.lng
);
}
draw() {
const container = self.$el;
let pos = this.getProjection().fromLatLngToDivPixel(self.current);
container.style.left = pos.x + "px";
container.style.top = pos.y + "px";
}
onAdd() {
const container = self.$el;
const panes = this.getPanes();
panes.floatPane.appendChild(container);
google.maps.event.addDomListener(
self.$map.getDiv(),
"mouseleave",
() => {
google.maps.event.trigger(container, "mouseup");
}
);
google.maps.event.addDomListener(container, "mousedown", e => {
container.style.cursor = "move";
self.$map.set("draggable", false);
self.origin = e;
const mouseMoveHandler = google.maps.event.addDomListener(
self.$map.getDiv(),
"mousemove",
e => {
let left = self.origin.clientX - e.clientX;
let top = self.origin.clientY - e.clientY;
let pos = self.$overlay
.getProjection()
.fromLatLngToDivPixel(self.current);
let latLng = self.$overlay
.getProjection()
.fromDivPixelToLatLng(
new google.maps.Point(pos.x - left, pos.y - top)
);
self.origin = e;
self.current = latLng;
this.draw();
}
);
google.maps.event.addDomListener(container, "mouseup", () => {
self.$map.set("draggable", true);
container.style.cursor = "default";
google.maps.event.removeListener(mouseMoveHandler);
});
});
}
onRemove() {
self.$el.remove();
}
}
this.$overlay = new Overlay(map);
});
},
destroyed() {
this.$overlay.setMap(null);
this.$overlay = undefined;
}
};
</script>
这是演示