有人可以向我解释为什么当我尝试在函数外部访问它时,即使它是对象的一部分,为什么'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);
因为当您
尝试记录它时initialize
尚未调用/完成。
您需要将其或您实际要执行的任何操作(或对填充后将访问currentPos
的其他函数的调用(移动到回调内部/分配它之后。