谈到 javascript,我几乎是个菜鸟,但我想在我的网站上放置我所在位置的谷歌地图,并有一个简单的表单,访问者可以在其中输入他们的地址并显示路线。我的工作正常,但有人提到脚本创建的全局变量太多。全局变量如下:
calcRoute
, directionsDisplay
, directionsService
, google
, initialize
,map
如果我尝试将这些全局变量中的任何一个改为本地,它会破坏脚本,并且地图不会显示。这是我写的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;
据我所知,我提到的全局变量是 Google Maps API 所必需的,它们必须是全局变量。非常感谢您对此提出任何建议。