I am implementing an application using Google Maps and Leap Motion and what I want right now, and I am a bit stuck, is a way to convert (x, y) screen coordinates into a Goog
Adding an alternate solution based on an existing SO question code, despite the original poster found a solution.
Based on this answer we can find the necessary part for Google Maps API v3 to do the conversion. It focuses on repositioning the center of the map. Modifying it to read the position from the screen requires calculating the difference of the screen coordinates from the screen center.
I renamed the function for the sake of this example to pixelOffsetToLatLng and changed it to return the position (other than that, not too different from the code in the answer above):
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;
}
To call it, you need to pass the X and Y coordinates that you have on the web page element:
var x = mapElement.offsetWidth / 2 - screenPositionX;
var y = screenPositionY - mapElement.offsetHeight / 2;
pixelOffsetToLatLng(x,y);
For the leap.js side, you just need to map the leap.js coordinates to the web page, either by experimenting or by using the screen-position plugin that works like this:
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
});
Here's a Codepen example on how to read the coordinates using Leap.js in 2D environment: http://codepen.io/raimo/pen/pKIko
You can center the Google Maps view using your mouse or by grabbing your hand over the Leap Motion Controller (see the red "cursor" for visual cue).