有人向我解释为什么当我尝试在函数外部访问它时,'currentPos.LatLng'是未定义的,即使它是对象的一部分?基本上我试图能够获取当前位置的值,以便我可以在另一个函数中再次使用它们。对这些东西很新......提前谢谢。
var map;
var infowindow;
var currentPos = {
};
var city = new google.maps.LatLng(60, -105);
function initialize() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: city,
zoom: 13
});
if(navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(
function(position) {
pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(pos);
currentPos.LatLng = pos;
console.log(currentPos.LatLng);
},
function() {
handleNoGeolocation(true);
}
);
} else {
handleNoGeolocation(false);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
}
var request = {
location: city,
radius: 2500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.search(request, callback);
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
console.log(currentPos.LatLng);
答案 0 :(得分:2)
因为在您尝试登录时尚未调用/完成initialize
。
你想要移动它,或者你想要做的任何事情(或者在填充后访问currentPos
的其他函数),在回调内/在你指定它之后