私は JavaScript に関してはほとんど初心者ですが、自分の場所の Google マップを自分の Web サイトに配置し、訪問者が住所を入力して道順を表示できるシンプルなフォームを作成したいと考えていました。問題なく動作していますが、スクリプトによって作成されたグローバル変数が多すぎると指摘されています。グローバルは次のとおりです。
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 で必要であり、グローバルでなければなりません。これに関するアドバイスは大歓迎です。