2013-04-08 59 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

相关问题