Google地图API和带路线的地图

时间:2016-08-07 11:18:59

标签: javascript google-maps

我的谷歌地图上有我网站上的路线

<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>

但我想禁用默认用户界面,因此我将使用以下内容:

   <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
  });

但是可以将我当前的地图(带路线)添加到&#34; initMap&#34;功能?或者如何将路由添加到&#34; initMap&#34;功能

1 个答案:

答案 0 :(得分:1)

this example in the documentation添加代码,将其修改为your origin, destination and waypoints

proof of concept fiddle

enter image description here

代码段

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>