我試圖設置一個從瀏覽器所在位置向拉斯維加斯提供路線的地圖。這裏是我的代碼示例:我如何重新使用Javascript變量函數
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API v3 Directions Example</title>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body style="font-family: Arial; font-size: 12px;">
<div style="width: 600px;">
<div id="map" style="width: 280px; height: 400px; float: left;"></div>
<div id="panel" style="width: 300px; float: right;"></div>
</div>
<script type="text/javascript">
navigator.geolocation.getCurrentPosition(GetLocation);
function GetLocation(location) {
var mylat = location.coords.latitude;
var mylong = location.coords.longitude;
}
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('map'), {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('panel'));
var request = {
origin: 'mylat,mylong',
destination: '35.580789,-105.210571',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
</script>
</body>
</html>
如果我在mylat
和mylong
硬代碼,那麼該頁面將加載就好了。我也用了以下驗證時位置共享這些值正確填充:
function GetLocation(location) {
var mylat = location.coords.latitude;
var mylong = location.coords.longitude;
document.write(mylat);
document.write(mylong);
}
我也試着寫功能之外這些變量,看看他們是突然空。我可以嘗試保留mylat
和mylong
變量並重新調用origin: 'mylat,mylong',
調用?謝謝你的建議。
這些是函數範圍內的私有變量。使它們成爲全局函數或返回函數。 –
這不起任何作用,同樣,警告mylat和mylong不起作用:http://jsfiddle.net/t7txk/ –