2015-11-24 32 views
2

我使用基本地理位置來抓取用戶long/lat,然後將座標對添加到全局變量(global.usr),然後生成一個新的具有global.usr的地圖元素作爲我的地圖的中心。Google Maps API/JavaScript居中變量

看起來很直接,帶有灰色的空白Google地圖元素。

var x = document.getElementById("alert"); 

function getLocation() { 
    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(getLocation); 
    } else { 
     alert("You don't support this"); 
    } 
} 
getLocation(); 


var global = {}; 

    function showPosition(position) 
    { 
    global.coords = new google.maps.LatLng(
     position.coords.latitude, 
     position.coords.longitude 
    ); 
    } 



var mapElement = document.getElementById("map-canvas"); 

var map = new google.maps.Map(mapElement, { 
    center: global.coords, 
    zoom: 4 
}); 
+0

'navigator.geolocation.getCurrentPosition(的getLocation);'的第一個參數getCurrentPosition方法成功接收座標時運行的回調函數,將位置作爲第一個參數傳遞。請參閱https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition。我猜你希望這一行實際上是'navigator.geolocation.getCurrentPosition(showPosition);',但這仍然行不通,因爲getCurrentPosition是異步的 - 不能保證它在你定義地圖變量之前完成。 –

回答

0

按我的評論,它看起來像你的意思是提供showPosition,不getLocation作爲參數去getCurrentPosition。您還需要考慮到getCurrentPosition方法是非阻塞的 - 所以getLocation將立即返回,並且您將在實際擁有座標之前繼續定義地圖元素。我想到你居然想是這樣的:

var x = document.getElementById("alert"), 
    mapElement = document.getElementById("map-canvas"), 
    map; 

function getLocation() { 
    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(getLocation); 
    } else { 
     alert("You don't support this"); 
    } 
} 
getLocation(); 


var global = {}; 

function showPosition(position) 
{ 
    global.coords = new google.maps.LatLng(
     position.coords.latitude, 
     position.coords.longitude 
    ); 
    defineMap(); 
} 

function defineMap() { 
    map = new google.maps.Map(mapElement, { 
     center: global.coords, 
     zoom: 4 
    }); 
} 

您可以獲取有關getCurrentPosition方法這裏的更多信息:https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition