2013-02-04 82 views
0

當談到javascript時,我幾乎是一個noob,但我想在我的網站上放置我的位置的Google Map,並且有一個簡單的表單,訪問者可以輸入他們的地址並會顯示方向。我已經可以正常工作了,但已經提到腳本創建的全局變量太多了。在全局如下:谷歌地圖API v3,全局變量

calcRoutedirectionsDisplaydirectionsServicegoogleinitializemap

如果我儘量讓這些全局的而不是局部的,它打破了腳本,並在地圖不顯示。下面是我寫的JS:

var initialize = function strict() { 
    directionsDisplay = new google.maps.DirectionsRenderer(); 
    mapCenter = new google.maps.LatLng(53.503716, -1.12975); 
    mapOptions = { 
     zoom: 14, 
     mapTypeId: google.maps.MapTypeId.ROADMAP, 
    center: mapCenter 
    }; 
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); 
    directionsDisplay.setMap(map); 
    directionsDisplay.setPanel(document.getElementById("directionsPanel")); 
    locationPin = "images/location_pin.png"; 
    newMarker = new google.maps.Marker({ position: mapCenter,map: map,icon: locationPin}); 
    }; 

var calcRoute = function strict() { 
    routeStart = document.getElementById("start").value; 
    calculatedRoute = {origin: routeStart, destination: mapCenter, travelMode: google.maps.TravelMode.DRIVING}; 
    directionsService.route(calculatedRoute, function (routeStart, mapCenter) { 
    directionsDisplay.setDirections(routeStart); 
    calculatedRoute = routeStart.routes[0].legs[0]; 
    }); 
}; 
var directionsDisplay; 
var directionsService = new google.maps.DirectionsService(); 
var map; 

據我所看到的,是由谷歌地圖API需要我提到的全局變量,它們必須是全局。任何意見,將非常感激的歡迎。

+0

告訴我們確切的錯誤:D –

+0

沒有錯誤,腳本做它應該的。我向另一個社區展示了這個代碼,他們說全球變量太多了。我通過JSLint運行代碼,並顯示了我列出的變量。我所問的是這是否是一個問題,如果代碼可以寫得更好? –

+1

從問題我真的不知道你需要什麼。你能解釋一下嗎? – daremachine

回答

0

您的代碼是OK!

但是,如果你不希望這個變量是全球性的,在功能,插入你的代碼,如:

(function() { 
    //your code 
}()); 

利用這一點,變量將是在範圍內,但在你的情況下,它不會造成差異...

+1

非常感謝。我仍然在處理Javascript,所以當有些人說代碼不好時,因爲它產生了太多的全局變量,我很擔心。 –