I’m pretty much a noob when it comes to javascript, but I wanted to place a Google Map of my location on my website, and to have a simple form where visitors can enter their address and the directions would be shown. I’ve got it working OK, but it’s been mentioned that there are too many global variables created by the script. The globals are as follows:
calcRoute, directionsDisplay, directionsService, google, initialize, map
If I try to make any of these globals local instead, it breaks the script, and the map doesn’t display. Here’s the js I have written:
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;
As far as I can see, the globals I mentioned are required by the Google Maps API and they have to be globals. Any advice on this would be very gratefully welcomed.
Your code is OK!
But, if you don’t want that this variable be global, insert your code at a function, like:
Using this, the variables will be at a scope, but in your case, it dosen’t make difference…