2013-09-25 22 views
1

如何檢查自定義工具提示的左上角是否適合地圖邊界? 我正在使用下面的代碼,但有些東西不對,因爲'myLatLng'永遠不會在地圖範圍內。提前謝謝你的幫助。檢查自定義工具提示的左上角是否在邊界內

var scale = Math.pow(2, map.getZoom()); 
var nw = new google.maps.LatLng(
    map.getBounds().getNorthEast().lat(), 
    map.getBounds().getSouthWest().lng() 
); 
var worldCoordinateNW = map.getProjection().fromLatLngToPoint(nw); 
var worldCoordinate = map.getProjection().fromLatLngToPoint(marker.getPosition()); 
var pixelOffset = new google.maps.Point(
    Math.floor((worldCoordinate.x - worldCoordinateNW.x) * scale), 
    Math.floor((worldCoordinate.y - worldCoordinateNW.y) * scale) 
); 

var myLatLng = map.getProjection().fromPointToLatLng(pixelOffset); 

if (map.getBounds().contains(myLatLng)) { 
// it's within bounds 
} 
+0

當然,「標記錨點的位置」是標記的位置,即'marker.getPosition()'? –

+0

我需要計算標記定位點的像素位置 – Chris

+0

爲什麼要將其轉換爲px座標,然後返回latLng來計算標記是否在邊界內? '.contains()'方法最終會直接在標記位置上運行; 'if(map.getBounds()。contains(marker.getPosition())){/ *它在範圍內* /}' –

回答

0

我的工作了,這是我使用的解決方案。

var proj = map.getProjection(); 
var bounds = map.getBounds(); 
var scale = Math.pow(2, map.getZoom());    

var anchorPoint = proj.fromLatLngToPoint(marker.getPosition()); 
// tlc == top left corner (of tooltip) 
var tlcPoint = new google.maps.Point(
    (anchorPoint.x * scale)/scale, 
    ((anchorPoint.y * scale) - marker.getIcon().size.height - tooltip.getHeight())/scale 
); 
var tlcLatLng = proj.fromPointToLatLng(tlcPoint); 

if (! bounds.contains(tlcLatLng)) { 
bounds.extend(tlcLatLng); 
map.fitBounds(bounds); 
} 
1

你有一個語法錯誤和錯別字在代碼:

if (map.getBounds().countains(myLatLng) { 
// it's within bounds 
} 

應該

if (map.getBounds().contains(myLatLng)) { 
// it's within bounds 
} 
+0

謝謝你發現。在本網站上添加我的問題時出現拼寫錯誤,但這不是我的代碼無法正常工作的原因。 – Chris

+0

您更新的問題仍然缺少關閉''' - 這也只是一個錯誤,當你添加你的問題,或在你的代碼真正的錯誤?通過類似JSLint的方式運行您的實際JS;谷歌地圖是非常unforgiving的JS錯誤 – duncan

+0

是的結束)也是一個錯誤,而加入我的問題 – Chris

相關問題