I'm looking to integrate a Google Maps direction feature onto my page. Currently, the JS element is hardcoded with the origin set as Miami, FL, destination as Buffalo, NY, and waypoints also static. However, I want to make these values dynamic by retrieving location strings from a JSON file on the backend using Angular's http.get.
How can I adjust the script to allow for dynamic origins, destinations, and waypoints?
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 41.85, lng: -87.65},
scrollwheel: false,
zoom: 7
});
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
// Set destination, origin and travel mode.
var request = {
destination: "Miami, FL",
origin: "Buffalo, NY",
travelMode: google.maps.TravelMode.DRIVING,
waypoints: [
{
location:"Richmond, VA",
stopover:true
},{
location:"Washington, DC",
stopover:true
}],
};
var directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
</script>