Kakadela Horosho Kakadela Horosho - 4 months ago 17
Javascript Question

Google map API and map with routes

I have google map with routes on my website

<iframe src="https://www.google.com/maps/embed?pb=!1m46!1m12!1m3!1d204152.56634698433!2d174.4756264675282!3d-36.9170414111374!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!4m31!3e0!4m5!1s0x6d0d47f01acf61c9%3A0x1300ef6107147fb1!2s82+Federal+Street%2C+Auckland!3m2!1d-36.848918!2d174.762316!4m5!1s0x6d0d6f84ac9df8e1%3A0x2a00ef6165df7dd0!2sKarekare+Stream%2C+Karekare%2C+Auckland!3m2!1d-36.986930799999996!2d174.4746851!4m5!1s0x6d0d6f035335b4e1%3A0x500ef6143a2f790!2sPiha!3m2!1d-36.9530211!2d174.46880919999998!4m5!1s0x6d0d6aeadce234bf%3A0x500ef6143a306f0!2sSwanson%2C+Auckland!3m2!1d-36.8656784!2d174.57980329999998!4m5!1s0x6d0d47f01acf61c9%3A0x1300ef6107147fb1!2s82+Federal+St%2C+Auckland%2C+Auckland!3m2!1d-36.848918!2d174.762316!5e0!3m2!1sen!2snz!4v1468509676781" width="1200" height="400" frameborder="0" style="border:0" allowfullscreen></iframe>


But I want to disable default UI, so I'm going to use something like :

<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -33, lng: 151},
disableDefaultUI: true
});


But is it possible to add my current map (with roures) to "initMap" function? Or how to add routes to "initMap" function?

Answer

Adding code from this example in the documentation, modifying it to take your origin, destination and waypoints:

proof of concept fiddle

enter image description here

code snippet:

function calculateAndDisplayRoute(start, end, waypoints, directionsService, directionsDisplay) {
  directionsService.route({
    origin: start,
    destination: end,
    waypoints: waypoints,
    travelMode: 'DRIVING'
  }, function(response, status) {
    if (status === 'OK') {
      directionsDisplay.setDirections(response);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
}

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {
      lat: -33,
      lng: 151
    },
    disableDefaultUI: true
  });
  var directionsService = new google.maps.DirectionsService;
  var directionsDisplay = new google.maps.DirectionsRenderer({
    map: map
  });
  var waypoints = [{
    location: "Karekare Stream",
    stopover: false
  }, {
    location: "Piha, New Zealand",
    stopover: false
  }, {
    location: "Swanson, Auckland, New Zealand",
    stopover: false
  }];
  calculateAndDisplayRoute("82 Federal Street, Auckland, 1010, New Zealand", "82 Federal Street, Auckland, 1010, New Zealand", waypoints, directionsService, directionsDisplay);
}
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
<div id="map"></div>