为了使自定义叠加层在 Google Maps API v3 中可点击,您需要创建一个自定义点击事件监听器。以下是一个完整的示例,说明了如何实现这一目标:
function CustomOverlay(position, imgUrl, map) {
this.position = position;
this.imgUrl = imgUrl;
this.map = map;
this.div = null;
}
CustomOverlay.prototype = new google.maps.OverlayView();
CustomOverlay.prototype.draw = function () {
var self = this;
var div = document.createElement('div');
div.style.borderStyle = 'none';
div.style.borderWidth = '0px';
div.style.position = 'absolute';
var img = new Image();
img.src = this.imgUrl;
img.onload = function () {
div.style.width = img.width + 'px';
div.style.height = img.height + 'px';
self.div = div;
self.setMap(self.map);
self.update();
};
google.maps.event.addDomListener(div, 'click', function () {
google.maps.event.trigger(self, 'click');
});
};
CustomOverlay.prototype.onAdd = function () {
this.getPanes().overlayLayer.appendChild(this.div);
};
CustomOverlay.prototype.onRemove = function () {
this.div.parentNode.removeChild(this.div);
this.div = null;
};
CustomOverlay.prototype.update = function () {
var overlayProjection = this.getProjection();
var point = overlayProjection.fromLatLngToDivPixel(this.position);
if (point) {
this.div.style.left = point.x + 'px';
this.div.style.top = point.y + 'px';
}
};
var customOverlay = new CustomOverlay(
new google.maps.LatLng(40.7128, -74.0060),
'https://example.com/path/to/your/image.png',
map
);
google.maps.event.addListener(customOverlay, 'click', function () {
alert('Custom overlay clicked!');
});
在这个示例中,我们创建了一个自定义叠加层类,并实现了 draw()、onAdd()、onRemove() 和 update() 方法。我们还为自定义叠加层添加了一个点击事件监听器,当用户点击自定义叠加层时,会弹出一个提示框。
请注意,这个示例仅用于演示目的。在实际应用中,您可能需要根据您的需求对其进行调整。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云