可能重复:
JavaScript 变量范围
我的脚本有问题,我想从 pos 函数中获取值 lat, lng,但是当我在控制台中检查元素时,我得到了这个错误:
“未捕获的 ReferenceError:lat 未定义 TEST.html:30(匿名函数)”
第 30 行是:var latlng = new google.maps.LatLng (lat, lng); 这是我的完整代码:
<script type="text/javascript">
navigator.geolocation.getCurrentPosition (function (pos){
lat = pos.coords.latitude;
lng = pos.coords.longitude;
});
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var latlng = new google.maps.LatLng (lat, lng);
var oceanBeach = new google.maps.LatLng(-6.2501199999999999,106.75937);
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlng
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var selectedMode = document.getElementById("mode").value;
var request = {
origin: latlng,
destination: oceanBeach,
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
travelMode: google.maps.TravelMode[selectedMode]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
</script>