首页 > 解决方案 > 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
    });

汽车垂直旋转

汽车默认原产地

标签: javascriptgoogle-maps-markers

解决方案


我终于找到了解决方案。此代码将增加您的标记 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
});
}

推荐阅读