我正在尝试创建一个叠加视图,您可以通过拖动调整大小来创建该视图。特别需要它,因此它位于标记之上,因此 google.maps.Rectangle 将不起作用。
问题是它仅在您从地图的左下角拖放到右上角时才有效。 IE。单击并按住地图左下角附近,按住的同时拖动到右上角并松开。你会得到一个红色的矩形。不错!
但是,所有其他方向都不起作用。我不知道如何确保无论你画哪个方向都会出现一个矩形。
我在此处使用 Google 提供的示例代码,但删除了我不需要的部分并添加了 mousedown 和 up 处理程序:https://developers.google.com/maps/documentation/javascript/examples/overlay-simple
我已将示例代码简化为 https://jsfiddle.net/jd2ox7u4/
标记只是视觉/证明,lat/lng 是您单击和释放的位置。
来自 JS Fiddle 的代码
function initMap() {
const myLatLng = { lat: -25.363,lng: 131.044 };
const map = new google.maps.Map(document.getElementById("map"),{
zoom: 4,center: myLatLng,draggable: false
});
new google.maps.Marker({
position: myLatLng,map,title: "Hello World!",});
class USGSOverlay extends google.maps.OverlayView {
bounds;
div;
constructor(bounds,image) {
super();
this.bounds = bounds;
}
onAdd() {
this.div = document.createElement("div");
this.div.style.position = "absolute";
this.div.style.background = 'red';
const panes = this.getPanes();
panes.overlayImage.appendChild(this.div);
}
draw() {
// We use the south-west and north-east
// coordinates of the overlay to peg it to the correct position and size.
// To do this,we need to retrieve the projection from the overlay.
const overlayProjection = this.getProjection();
// Retrieve the south-west and north-east coordinates of this overlay
// in LatLngs and convert them to pixel coordinates.
// We'll use these coordinates to resize the div.
const sw = overlayProjection.fromLatLngToDivPixel(
this.bounds.getsouthWest()
);
const ne = overlayProjection.fromLatLngToDivPixel(
this.bounds.getNorthEast()
);
// Resize the image's div to fit the indicated dimensions.
if (this.div) {
this.div.style.left = sw.x + "px";
this.div.style.top = ne.y + "px";
this.div.style.width = ne.x - sw.x + "px";
this.div.style.height = sw.y - ne.y + "px";
}
}
onRemove() {
if (this.div) {
this.div.parentNode.removeChild(this.div);
delete this.div;
}
}
}
let isDragging = false;
let startPosition = null;
let stopPosition = null;
google.maps.event.addListener(map,'mousedown',function (event) {
console.log('Mouse Down At',event.latLng.lat(),event.latLng.lng())
isDragging = true;
startPosition = event.latLng;
new google.maps.Marker({
map,position: {lat: startPosition.lat(),lng: startPosition.lng()}
})
})
google.maps.event.addListener(map,'mouseup',function (event) {
if (isDragging) {
console.log('Mouse Up At',event.latLng.lng())
isDragging = false;
stopPosition = event.latLng;
new google.maps.Marker({
map,position: {lat: stopPosition.lat(),lng: stopPosition.lng()}
})
var overlay = new USGSOverlay(new google.maps.LatLngBounds(
new google.maps.LatLng(startPosition.lat(),startPosition.lng()),new google.maps.LatLng(stopPosition.lat(),stopPosition.lng())
),'https://developers.google.com/maps/documentation/javascript/examples/full/images/talkeetna.png')
overlay.setMap(map);
}
})
}