尽管原始发布者找到了解决方案,但仍基于现有 SO 问题代码添加替代解决方案。
Based on this answer 我们可以找到 Google Maps API v3 进行转换的必要部分。它侧重于重新定位地图的中心。修改为从屏幕读取位置需要计算屏幕坐标与屏幕中心的差值。
为了这个示例,我将函数重命名为 pixelOffsetToLatLng 并将其更改为返回位置(除此之外,与上面答案中的代码没有太大区别):
function pixelOffsetToLatLng(offsetx,offsety) {
var latlng = map.getCenter();
var scale = Math.pow(2, map.getZoom());
var nw = new google.maps.LatLng(
map.getBounds().getNorthEast().lat(),
map.getBounds().getSouthWest().lng()
);
var worldCoordinateCenter = map.getProjection().fromLatLngToPoint(latlng);
var pixelOffset = new google.maps.Point((offsetx/scale) || 0,(offsety/scale) ||0);
var worldCoordinateNewCenter = new google.maps.Point(
worldCoordinateCenter.x - pixelOffset.x,
worldCoordinateCenter.y + pixelOffset.y
);
var latLngPosition = map.getProjection().fromPointToLatLng(worldCoordinateNewCenter);
return latLngPosition;
}
要调用它,您需要传递网页元素上的 X 和 Y 坐标:
var x = mapElement.offsetWidth / 2 - screenPositionX;
var y = screenPositionY - mapElement.offsetHeight / 2;
pixelOffsetToLatLng(x,y);
对于leap.js 方面,您只需将leap.js 坐标映射到网页,可以通过试验或使用类似这样工作的屏幕位置插件:
var $handCursor = $('#hand-cursor'); // using jQuery here, not mandatory though
Leap.loop(function(frame) {
if (frame.hands.length > 0) {
var hand = frame.hands[0];
$handCursor.css({
left: hand.screenPosition()[0] + 'px',
top: hand.screenPosition()[1] + 'px'
});
if ((hand.grabStrength >= 0.6 && lastGrabStrength < 0.6)) {
var x = mapElement.offsetWidth / 2 - hand.screenPosition()[0];
var y = hand.screenPosition()[1] - mapElement.offsetHeight / 2;
map.setCenter(pixelOffsetToLatLng(x, y));
}
}
}).use('screenPosition', {
scale: 0.5
});
这是一个关于如何在 2D 环境中使用 Leap.js 读取坐标的 Codepen 示例:
http://codepen.io/raimo/pen/pKIko
您可以使用鼠标或将手放在 Leap Motion 控制器上来使 Google 地图视图居中(请参阅红色“光标”以获得视觉提示)。