Maps API v3 Directions with custom markers
Directions service with custom markers and InfoWindow
by Alex Azuero
HTML
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="map-canvas"></div>
CSS
#map-canvas {
height:400px;
}
JavaScript
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var infowindow = new google.maps.InfoWindow();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
var mapOptions = {
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var start = new google.maps.LatLng(43.786161, 11.250510);
var end = new google.maps.LatLng(43.776030, 11.274929);
createMarker(start, 'start');
createMarker(end, 'end');
var request = {
origin: start,
destination: end,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
}
});
}
function createMarker(latlng, title) {
var marker = new google.maps.Marker({
position: latlng,
title: title,
map: map
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(title);
infowindow.open(map, marker);
});
}
initialize();