2015-11-24 38 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