谷歌地图v3:我如何可靠地检索图标大小和锚定位置?

时间:2013-01-17 14:29:40

标签: javascript google-maps-api-3

我正在将一个库从v2移植到v3。开发人员可以使用他们想要的任何自定义图标作为标记,但是,我需要能够获得图标的大小和图标的锚点位置。使用v2,gmaps库将计算所有这些并使其可用。使用v3,当您从标记中检索图标时,它可能是仅包含图像URL的字符串。或者,它可以是MarkerImage,其中只包含与构造函数中提供的开发人员一样多的信息。使用v3,我如何可靠地获取标记图标的图标大小和锚点位置?

// v2 way
var markerImage = new GIcon(G_DEFAULT_ICON);
markerImage.image = '/system/themes/asp/img/gmarkerA.png';

var marker = new GMarker(
    new GLatLng(35.908236, -79.024531),
    {'title':'NC',
    'icon': markerImage
    });

// get info here
var markerIcon = marker.getIcon();
var anchorX = markerIcon.iconAnchor.x
var anchorY = markerIcon.iconAnchor.y
var iconHeight = markerIcon.iconSize.height
var iconWidth = markerIcon.iconSize.width


// v3 way #1
var marker = new google.maps.Marker({
    'position': new google.maps.LatLng(35.908236, -79.024531),
    'title':'NC',
    'icon': new google.maps.MarkerImage('/system/themes/asp/img/markerA.jpg'));

// v3 way #2
var marker = new google.maps.Marker({
    'position': new google.maps.LatLng(35.908236, -79.024531),
    'title':'NC',
    'icon': '/system/themes/asp/img/markerA.jpg');

// v3 way #3
var marker = new google.maps.Marker({
    'position': new google.maps.LatLng(35.908236, -79.024531),
    'title':'NC',
    'icon': { url : '/system/themes/asp/img/markerA.jpg'}
});


var markerIcon = marker.getIcon();
// how to get anchor position and size?????

2 个答案:

答案 0 :(得分:2)

icon.anchoricon.size

e.g。

var markerIcon = marker.getIcon();
var size = markerIcon.size;

这可能需要您使用第一种方法,而不是仅指定URL字符串 注意:不推荐使用MarkerImage对象,而是使用Icon。

var marker = new google.maps.Marker({
    'position': new google.maps.LatLng(35.908236, -79.024531),
    'title':'NC',
    'icon': { url : '/system/themes/asp/img/markerA.jpg'}
});

答案 1 :(得分:0)

我不认为api v3允许您获取该信息,除非您最初将其作为属性提供。我想出了这个给我一些有用的信息。希望其他人发现它有用:

google.maps.Marker.prototype.getIconInfo = function() {
    var icon = this.getIcon();
    var size = null;
    var anchor = null;
    var image;
    var info;


    if (typeof icon == 'string')
    {
        image = new Image(); 
        image.src = icon;

        size = new google.maps.Size(image.width, image.height);
    }
    else
    {
        size = icon.size;   
        anchor = icon.anchor;   

        if (size == null)
        {
            image = new Image(); 
            image.src = icon.url;

            size = new google.maps.Size(image.width, image.height);

        }
    }

    if (anchor == null)
    {
        anchor = new google.maps.Point(Math.floor(size.width / 2 - 1), size.height);
    }

    var infoWindowAnchor = new google.maps.Point(anchor.x, 2);

    info =  {size:size, anchor:anchor, infoWindowAnchor:infoWindowAnchor};

    return info;
}