Mar*_*anu 17 javascript google-maps google-maps-api-3
我正在使用谷歌地图和Leap Motion实现一个应用程序和我现在想要的,我有点卡住,是一种将(x,y)屏幕坐标转换为Google Maps LatLng对象的方法.
我想实现这一目标,例如,在用户使用Leap Motion指向的位置开始全景(街景视图).
我知道fromPointToLatLng函数的存在,但我不知道使用它的正确方法是什么,以及如何将我的x和y坐标转换为lat lng变量.
你能帮我解决这个问题吗?
小智 31
function latLng2Point(latLng, map) {
var topRight = map.getProjection().fromLatLngToPoint(map.getBounds().getNorthEast());
var bottomLeft = map.getProjection().fromLatLngToPoint(map.getBounds().getSouthWest());
var scale = Math.pow(2, map.getZoom());
var worldPoint = map.getProjection().fromLatLngToPoint(latLng);
return new google.maps.Point((worldPoint.x - bottomLeft.x) * scale, (worldPoint.y - topRight.y) * scale);
}
function point2LatLng(point, map) {
var topRight = map.getProjection().fromLatLngToPoint(map.getBounds().getNorthEast());
var bottomLeft = map.getProjection().fromLatLngToPoint(map.getBounds().getSouthWest());
var scale = Math.pow(2, map.getZoom());
var worldPoint = new google.maps.Point(point.x / scale + bottomLeft.x, point.y / scale + topRight.y);
return map.getProjection().fromPointToLatLng(worldPoint);
}
Run Code Online (Sandbox Code Playgroud)
经过一些研究和一些失败,我想出了一个解决方案.根据此链接的文档,我发现谷歌点的计算范围是x:[0-256],y:[0-256](一个图块为256x256像素)和(0,0)点是地图的最左侧点(查看链接以获取更多信息).
但是,我的方法如下:
有x和y坐标(它是屏幕上的坐标 - 在地图上)我计算了放置x和y坐标的百分比,以响应包含地图的div(在我的例子中,是洞窗口)
计算(可见)地图的NortEast和SouthWest LatLng边界
转换了谷歌点数的界限
在边界和x和y的百分比的帮助下,在谷歌点计算新的lat和lng
转换回lat lng
// retrieve the lat lng for the far extremities of the (visible) map
var latLngBounds = map.getBounds();
var neBound = latLngBounds.getNorthEast();
var swBound = latLngBounds.getSouthWest();
// convert the bounds in pixels
var neBoundInPx = map.getProjection().fromLatLngToPoint(neBound);
var swBoundInPx = map.getProjection().fromLatLngToPoint(swBound);
// compute the percent of x and y coordinates related to the div containing the map; in my case the screen
var procX = x/window.innerWidth;
var procY = y/window.innerHeight;
// compute new coordinates in pixels for lat and lng;
// for lng : subtract from the right edge of the container the left edge,
// multiply it by the percentage where the x coordinate was on the screen
// related to the container in which the map is placed and add back the left boundary
// you should now have the Lng coordinate in pixels
// do the same for lat
var newLngInPx = (neBoundInPx.x - swBoundInPx.x) * procX + swBoundInPx.x;
var newLatInPx = (swBoundInPx.y - neBoundInPx.y) * procY + neBoundInPx.y;
// convert from google point in lat lng and have fun :)
var newLatLng = map.getProjection().fromPointToLatLng(new google.maps.Point(newLngInPx, newLatInPx));
Run Code Online (Sandbox Code Playgroud)希望这个解决方案也可以帮助别人!:)
小智 6
查看简单的解决方案(v3):
map.getProjection().fromLatLngToPoint(marker.position);
Run Code Online (Sandbox Code Playgroud)
https://developers.google.com/maps/documentation/javascript/3.exp/reference#Projection
| 归档时间: |
|
| 查看次数: |
27500 次 |
| 最近记录: |