javascript - Google Maps JS 自定义标记图像
问题描述
所以我目前正在使用 hack-a-round 在谷歌地图中旋转自定义图像标记。
我面临的问题是尺寸。基本上,如果我的 png 图像是 400px 宽和 200px 高。
当您旋转宽度垂直的图像时,它会切断图像。
我想如何将图像放入边界内。我最初认为的伪代码是这样的,但无法让它工作。
const image = currentImage;
if(image.width > image.height){
//make bounding box of marker image.width squared
} else{
//make bounding box of marker image.height squared
}
仅供参考,这是我的旋转功能:
function rotate() {
const images = $("#map").find("img").get();
for (let i = 0; i < images.length; i++) {
if ($(images[i]).attr("src").replaceAll(window.location.origin, "") === currentMarker.itemSrc) {
$(images[i]).css({
'transform': 'rotate(' + currentDeg + 'deg)',
});
break;
}
}
}
这就是我添加标记的方式:(不要介意我添加到标记对象的自定义字段)
const markerIcon = {
url: currentImage.src + "#" + allMarkers.length,
// size: new google.maps.Size(?, ?),
// origin: new google.maps.Point(?, ?),
// anchor: new google.maps.Point(?, ?)
};
const marker = new google.maps.Marker({
position: mapsMouseEvent.latLng,
map: map,
draggable: true,
icon: markerIcon,
itemSrc: currentImage.src.replaceAll(window.location.origin, "") + "#" + allMarkers.length,
id: lat + "," + lng,
optimized: false
});
解决方案
我终于找到了解决方案。此代码将增加您的标记 DIV 容器并使图像居中。
不用担心自定义字段rotation
。自定义图像标记不存在该字段。我创建它是为了跟踪和更新图像的旋转。
const currentImage = whateverYourImageIs;
let markerSize;
let origin;
if(currentImage.naturalWidth > currentImage.naturalHeight){
markerSize = currentImage.naturalWidth;
origin = new google.maps.Point(0 , -(markerSize - currentImage.naturalHeight) / 2);
}else{
markerSize = currentImage.naturalHeight;
origin = new google.maps.Point(-(markerSize - currentImage.naturalWidth) / 2 , 0);
}
function createMarker(position, iconImage, label, rotation, markerSize, origin) {
const markerIcon = {
url: iconImage,
labelOrigin: new google.maps.Point(20, 20),
size: new google.maps.Size(markerSize, markerSize),
origin: origin,
anchor: new google.maps.Point(0,0)
};
return new google.maps.Marker({
position: position,
map: map,
draggable: true,
icon: markerIcon,
optimized: false,
label: label,
rotation: rotation
});
}
推荐阅读
- python - AttributeError:模块“tensorflow”没有属性“compat”
- python - 将 JSON 解析为不带前缀的 Pandas
- ruby-on-rails - 葡萄添加新端点
- mongodb - Spring Boot Mongo DB中无法解析的日期错误格式
- sas - 用于内核密度 SAS 的默认值
- node.js - UnhandledPromiseRejectionWarning: 错误: 禁止 SendGrid WebAPI 错误
- docker - 如何在 ecs2 fargate 中通过 docker-compose up 运行 docker
- java - 在 Android 中运行 SQLite 查询
- c++ - 如何移动 QListWidgetItem?
- google-sheets - 由于 googlesheets 更改为 V8 运行时,我的脚本都不起作用。如何打开表到今天的日期并备份表?