我试图根据我的 x,y 像素坐标(当然还有 map 选项,例如缩放和中心)找出 LatLng。
为此,我发布了另一个 question有人想出了这个解决方案,来自这个 post :
/**
* @param {google.maps.Map} map
* @param {google.maps.Point} point
* @param {int} z
* @return {google.maps.LatLng}
*/
var pointToLatlng = function(map, point, z){
var scale = Math.pow(2, z);
var normalizedPoint = new google.maps.Point(point.x / scale, point.y / scale);
var latlng = map.getProjection().fromPointToLatLng(normalizedPoint);
return latlng;
};
正如您从代码示例中注意到的,该函数使用 google.maps.Point 作为参数,因此我需要将屏幕像素坐标转换为 google.maps.Point,但我不知道如何转换,因为他们的文档API 的说明并不是很详细...
你能帮我一下吗?或者我在路上错过了什么?
最佳答案
经过一些研究和一些失败,我想出了一个解决方案。 遵循此 link 中的文档我发现 google 点的计算范围为 x:[0-256], y:[0-256] (图 block 为 256x256 像素),而 (0,0) 点是 map 的最左边点(查看链接以获取更多信息)。
但是,我的方法如下:
有了 x 和 y 坐标(屏幕上的坐标 - map 上的坐标),我计算了 x 和 y 坐标响应于包含 map 的 div 放置的百分比(在我的例子中,孔窗)
计算(可见) map 的东北和西南纬度边界
转换了 google Points 的边界
借助 x 和 y 的边界和百分比计算新的 lat 和 lng(以 google 点表示)
// 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; var finalResult = new google.maps.Point(newLngInPx, newLatInPx);
关于google-maps - 转换 google.maps.Point 中的 (x, y) 像素坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25250924/