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
});
'navigator.geolocation.getCurrentPosition(的getLocation);'的第一个参数getCurrentPosition方法成功接收坐标时运行的回调函数,将位置作为第一个参数传递。请参阅https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition。我猜你希望这一行实际上是'navigator.geolocation.getCurrentPosition(showPosition);',但这仍然行不通,因为getCurrentPosition是异步的 - 不能保证它在你定义地图变量之前完成。 –