更新 2
var map, marker, overlay, latlng, zoom = 20;
function initialize() {
latlng = new google.maps.LatLng(33.501472920248354, -82.01948559679795);
var myOptions = {
zoom : zoom,
center : latlng,
tilt : 0,
mapTypeId : google.maps.MapTypeId.SATELLITE
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
overlay = new google.maps.OverlayView();
overlay.draw = function() {
};
overlay.onRemove = function() {
};
overlay.setMap(map);
marker = new google.maps.Marker({
position : latlng,
map : map,
draggable : true,
title : "Hello World!"
});
google.maps.event.addListener(map, 'zoom_changed', function() {
zoom = map.getZoom();
});
google.maps.event.addListener(map, 'dragend', function() {
overlay.setMap(map);
});
google.maps.event.addListener(marker, 'dragend', function(evt) {
var tilt = map.getTilt();
latlng = new google.maps.LatLng(evt.latLng.lat(), evt.latLng.lng());
if(tilt === 45) {
var projection = overlay.getProjection();
var latlng2pixel = projection.fromLatLngToContainerPixel(marker.getPosition());
var delta = 0;
switch(zoom) {
case 20:
delta = 45;
break;
case 19:
delta = 12;
break;
case 18:
delta = 4;
break;
}
latlng = projection.fromContainerPixelToLatLng(new google.maps.Point(latlng2pixel.x, (latlng2pixel.y + delta )));
}
});
google.maps.event.addListener(map, 'tilt_changed', function() {
var tilt = map.getTilt();
if(tilt === 45) {
var delta = 0;
switch(zoom) {
case 20:
delta = 65;
break;
case 19:
delta = 32;
break;
case 18:
delta = 16;
break;
}
var projection = overlay.getProjection();
var latlng2pixel = projection.fromLatLngToContainerPixel(marker.getPosition());
var pixel2latlng = projection.fromContainerPixelToLatLng(new google.maps.Point(latlng2pixel.x, (latlng2pixel.y - delta )));
marker.setPosition(pixel2latlng);
} else {
marker.setPosition(latlng);
}
});
}
注意:
上面的代码工作如下:
- 应用自定义叠加层以使用;
google.maps.MapCanvasProjection object
文档
- 找到标记的像素位置;
- 添加到
y
(top = lng) 的 45 度(缩放 20 时为 45 像素)加上20
标记图标高度的像素(x 始终保持不变,因为度数的变化是一种简单的视错觉;));
- 将这些像素位置转换为有效的 latlng 位置;
- 观察
tilt
方法是否从0
到45
,反之亦然,并通过设置新坐标采取相应的行动。