2

我在我的地圖中有折線。我想知道像素(屏幕)xy座標,當用戶點擊折線時。點擊事件只返回LatLng對象,所以有人有線索如何從latLng獲取像素座標?如何從谷歌地圖(V3)LatLng獲取屏幕XY?

如果有人能幫助我,我將非常感激!

+0

當你說像素座標,你的意思是X,Y座標的鼠標? – kjy112 2011-03-29 13:39:57

+0

是的,正好和容器格的xy – SuperCell 2011-03-29 18:49:51

回答

4

好的,我找到了解決方案。你必須使用google.maps.OverlayView,它是如此愚蠢的實現。我發現的模型是:http://www.william-map.com/20100416/1/map.htm

希望這可以幫助別人。

+2

注意:(這讓我難倒了半小時) - 確保在創建地圖時創建疊加層,而不是在需要座標時(通過fromLatLngToDivPixel) 。如果你這樣做,你會得到'Uncaught TypeError:不能調用方法'fromLatLngToDivPixel'undefined'。 它看起來像谷歌異步做這些東西。 – AlexeyMK 2011-08-11 22:34:58

+2

單挑:該鏈接重定向到垃圾郵件頁面。 – 2015-06-01 14:29:07

0

如果有經緯度的對象,你可以使用谷歌地圖投影對象將其改造成磚座標,然後轉換爲像素座標:

有關投影類文檔: https://developers.google.com/maps/documentation/javascript/reference#Projection

谷歌的示例說明如何將LatLng轉換爲像素座標: https://developers.google.com/maps/documentation/javascript/examples/map-coordinates?csw=1

有一個問題。以上將給你在谷歌的地圖div內的像素座標(你可能需要根據你的需要)。如果你想要相對於屏幕左上角的像素,還有一步。您需要在視口的左上角執行相同的投影並將兩者相減。這會給你LatLng點的像素座標。

我最後使用的代碼看起來像這樣(請注意「的latLng」是輸入):

var numTiles = 1 << map.getZoom(); 
var projection = map.getProjection(); 
var worldCoordinate = projection.fromLatLngToPoint(latLng); 
var pixelCoordinate = new google.maps.Point(
     worldCoordinate.x * numTiles, 
     worldCoordinate.y * numTiles); 

var topLeft = new google.maps.LatLng(
    map.getBounds().getNorthEast().lat(), 
    map.getBounds().getSouthWest().lng() 
); 

var topLeftWorldCoordinate = projection.fromLatLngToPoint(topLeft); 
var topLeftPixelCoordinate = new google.maps.Point(
     topLeftWorldCoordinate.x * numTiles, 
     topLeftWorldCoordinate.y * numTiles); 

return new google.maps.Point(
     pixelCoordinate.x - topLeftPixelCoordinate.x, 
     pixelCoordinate.y - topLeftPixelCoordinate.y 
)