2013-04-08 88 views
3

我正在嘗試將我當前的位置放在Google地圖中。這將使具有特定緯度和經度變量的位置居中。如何居中當前位置? (谷歌地圖)

var coords = new google.maps.LatLng(62.39081100, 17.30692700); 

但我試圖用這個功能來獲取用戶的位置:

function grabMyPosition() { 
    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(centerMe); 
    } else { 
     alert("You don't support this"); 
    } 
} 
function centerMe(center) { 
    var me_location = { 
     lat: position.coords.latitude, 
     lon: position.coords.longitude 
    }; 
} 

然後做到這一點:

var coords = new google.maps.LatLng(me_location.lat, me_location.lon); 

但後來我得到這個:

Uncaught TypeError: Cannot read property 'lat' of undefined 

這是因爲我正在儲存和填充th是函數中的「me_location」變量。我怎樣才能使它成爲「全球」,以便它可以在我的功能之外使用?

+1

'me_location'是不能從外部'CenterMe'功能來訪問返回的任何值.. – fernandosavio 2013-04-08 18:17:44

+0

我是這麼認爲的,但是如何「繞過」這個問題呢? – Jack 2013-04-08 18:18:32

+0

您在函數結尾處返回對象,並調用'navigator.geolocation.getCurrentPosition(centerMe());'來代替。 – Blazemonger 2013-04-08 18:19:31

回答

7
function grabMyPosition() { 
    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(centerMe); 
    } else { 
     alert("You don't support this"); 
    } 
} 
function centerMe(position) { 
    var coords = new google.maps.LatLng(
     position.coords.latitude, 
     position.coords.longitude 
    ); 

    map.setCenter(coords); 
    // or 
    map.panTo(coords); 
} 

假設你map變量是全球..

+0

Thanks man,lifesaver! – Jack 2013-04-08 18:31:57

2

你是不是從功能centerMe