Skip to content

Instantly share code, notes, and snippets.

@theJasonJones
Created December 1, 2016 16:45
Show Gist options
  • Save theJasonJones/804cd8a9a133786fe34f35f54759c871 to your computer and use it in GitHub Desktop.
Save theJasonJones/804cd8a9a133786fe34f35f54759c871 to your computer and use it in GitHub Desktop.
Google Maps Direction API with Custom Map
<div>
<div id="map-canvas"></div>
</div>
<script>
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers: true});
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 10,
center: {lat: 42.974181, lng: -89.534077}
});
directionsDisplay.setMap(map);
var icons = {
end: new google.maps.MarkerImage(
// URL
'<?php echo get_stylesheet_directory_uri() ?>/images/map-marker-small.png',
// (width,height)
new google.maps.Size(85, 33),
// The origin point (x,y)
new google.maps.Point( 0, 0 ),
// The anchor point (x,y)
new google.maps.Point( 44, 28 )
)
};
directionsService.route({
origin: '<?php echo $formatted_address_for_url ?>',
destination: '<?php echo $destination ?>',
provideRouteAlternatives: true,
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.IMPERIAL
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
var leg = response.routes[ 0 ].legs[ 0 ];
makeMarker( leg.end_location, icons.end, 'title' );
} else {
console.log('Directions request failed due to ' + status);
}
});
function makeMarker( position, icon, title ) {
new google.maps.Marker({
position: position,
map: map,
icon: icon,
title: title
});
}
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=<?php echo GOOGLE_MAP_KEY ?>&callback=initMap"></script>
<style>
#map-canvas { width: 70%; height: 500px; margin: 0 auto; }
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment