Using closures in event listeners
by hongyang1033
HTML
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
CSS
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
JavaScript
function initMap() {
var jsonString = '{"trip1":{"guide":"jason","date":"12 Jan 2015","description":"AAAAAAAAAAAAAAAAAAAAAAAAAAAA","stops":"0","places":[{"lat":"-33.890542","lng":"151.274856"},{"lat":"-32.8426736319543","lng":"148.24951171875"}]},"trip2":{"guide":"asshole","date":"12 Jan 2015","description":"AAAAAAAAAAAAAAAAAAAAAAAAAAAA","stops":"1","places":[{"lat":"-31.428663117358596","lng":"152.90771484375"},{"lat":"-35.29943548054544","lng":"149.1064453125"},{"lat":"-36.08462129606931","lng":"146.953125"}]}}';
var myData = JSON.parse(jsonString);
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: new google.maps.LatLng(-33.890542, 151.274856),
disableDefaultUI: true
});
directionsDisplay.setMap(map);
/*
for(var x in myData)
{
var position = new google.maps.LatLng(myData[x].places[0].lat,myData[x].places[0].lng);
var marker = new google.maps.Marker({
position: position,
map: map
});
google.maps.event.addListener(marker, 'mouseover', function(){
calculateAndDisplayRoute(directionsService, directionsDisplay, myData[x]);
});
google.maps.event.addListener(marker, 'mouseout', function(){
directionsDisplay.setDirections({routes: []});
console.log("Mouseout Working");
});
}*/
var marker;
for (var x in myData) {
var position = new google.maps.LatLng(myData[x].places[0].lat, myData[x].places[0].lng);
marker = new google.maps.Marker({
position: position,
map: map
});
calculateAndDisplayRoute(marker, directionsService, directionsDisplay, myData[x]);
}
}
function...