google-maps - 转换 google.maps.Point 中的 (x, y) 像素坐标

标签 google-maps math google-maps-api-3

我试图根据我的 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/

相关文章:

html - 我可以重新设计 google maps infowindows 的样式以使其看起来不那么令人毛骨悚然吗?

javascript - Google map 使用 php 和 jquery 动态显示许多标记

javascript - javascript中的浮点值提取

javascript - Google map fitbounds 错误(无法读取属性 e3)

javascript - Google Maps API V3 - KML 图层与 JS 创建的多边形

javascript - 如何将地址与 Google Map 动态集成?

javascript - 谷歌地图 iframe 无法在 bootstrap3 模式中正确加载

php - 给定 MySQL 的返回数量,如何找到平均 AGI?

algorithm - 这种重复可以有多少个子问题,同时仍然比初始重复更快?

ruby-on-rails - 使用Google Maps时, capybara 测试在第一个测试中失败并显示Timeout::Error