首页 > 解决方案 > 使用 Google Maps Api 在点击事件上显示 2 点之间的方向

问题描述

我需要有关 Google Maps API 和方向服务的帮助

我的目标: 创建以我的主要地址为中心的地图。创建 3x 叠加按钮来代表附近的城镇。一旦用户单击任一按钮,将显示所选城镇和我的主要地址之间的方向/路线。第四个按钮将使用户能够重置地图、将其居中并删除方向。

迄今已实现

需要帮助 仅在单击按钮时显示路线。此刻的路线显示从一开始就走。单击重置按钮时使路线消失。如果单击另一个城镇按钮,则更改路线。

资源

代码片段:

const paarl = {
  lat: -33.727494,
  lng: 18.9261117
}

function PaarlControl(controlDiv, map) {
  const controlUI = document.createElement("div");
  controlUI.style.backgroundColor = "rgba(237,24,72,0.6)";
  controlUI.style.border = "2px solid #ed1848";
  controlUI.style.borderRadius = "3px 3px 0 0";
  controlUI.style.boxShadow = "0 2px 6px rgba(0,0,0,.3)";
  controlUI.style.cursor = "pointer";
  controlUI.style.marginBottom = "22px";
  controlUI.style.textAlign = "center";
  controlUI.title = "Click for directions from Paarl";
  controlDiv.appendChild(controlUI);

  const controlText = document.createElement("div");
  controlText.style.color = "#fff";
  controlText.style.fontFamily = "Roboto,Arial,sans-serif";
  controlText.style.fontSize = "16px";
  controlText.style.lineHeight = "24px";
  controlText.style.paddingLeft = "5px";
  controlText.style.paddingRight = "5px";
  controlText.innerHTML = "Paarl<br>42km<br><small>click for directions to Pink Valley</small>";
  controlUI.appendChild(controlText);

  controlUI.addEventListener("click", () => {
    map.setCenter(paarl);
  });
}

// ==================
// LABEL CAPE TOWN
// ==================
const capetownint = {
  lat: -33.971463,
  lng: 18.5998911
}

function CapetownintControl(controlDiv, map) {
  const controlUI = document.createElement("div");
  controlUI.style.backgroundColor = "rgba(237,24,72,0.6)";
  controlUI.style.border = "2px solid #ed1848";
  controlUI.style.borderRadius = "3px 3px 0 0";
  controlUI.style.boxShadow = "0 2px 6px rgba(0,0,0,.3)";
  controlUI.style.cursor = "pointer";
  controlUI.style.marginBottom = "22px";
  controlUI.style.textAlign = "center";
  controlUI.title = "Click for directions from Cape Town International";
  controlDiv.appendChild(controlUI);

  const controlText = document.createElement("div");
  controlText.style.color = "#fff";
  controlText.style.fontFamily = "Roboto,Arial,sans-serif";
  controlText.style.fontSize = "16px";
  controlText.style.lineHeight = "24px";
  controlText.style.paddingLeft = "5px";
  controlText.style.paddingRight = "5px";
  controlText.innerHTML = "Cape Town International<br>32km<br><small>click for directions to Pink Valley</small>";
  controlUI.appendChild(controlText);

  controlUI.addEventListener("click", () => {
    map.setCenter(capetownint);
  });
}

// ==================
// LABEL STELLENBOSCH
// ==================
const stellenbosch = {
  lat: -33.9466715,
  lng: 18.774375
}

function StellenboschControl(controlDiv, map) {
  const controlUI = document.createElement("div");
  controlUI.style.backgroundColor = "rgba(237,24,72,0.6)";
  controlUI.style.border = "2px solid #ed1848";
  controlUI.style.borderRadius = "3px 3px 0 0";
  controlUI.style.boxShadow = "0 2px 6px rgba(0,0,0,.3)";
  controlUI.style.cursor = "pointer";
  controlUI.style.marginBottom = "22px";
  controlUI.style.textAlign = "center";
  controlUI.title = "Click for directions from Stellenbosch";
  controlDiv.appendChild(controlUI);

  const controlText = document.createElement("div");
  controlText.style.color = "#fff";
  controlText.style.fontFamily = "Roboto,Arial,sans-serif";
  controlText.style.fontSize = "16px";
  controlText.style.lineHeight = "24px";
  controlText.style.paddingLeft = "5px";
  controlText.style.paddingRight = "5px";
  controlText.innerHTML = "STELLENBOSCH<br>13km<br><small>click for directions to Pink Valley</small>";
  controlUI.appendChild(controlText);
  controlUI.addEventListener("click", () => {});
}

// ==================
// CENTER
// ==================
// let map;
const pinkvalley = {
  lat: -34.030553,
  lng: 18.829326
}

function CenterControl(controlDiv, map) {
  const controlUI = document.createElement("div");
  controlUI.style.backgroundColor = "rgba(237,24,72,0.6)";
  controlUI.style.border = "2px solid #ed1848";
  controlUI.style.borderRadius = "3px 3px 0 0";
  controlUI.style.boxShadow = "0 2px 6px rgba(0,0,0,.3)";
  controlUI.style.cursor = "pointer";
  controlUI.style.marginBottom = "22px";
  controlUI.style.textAlign = "center";
  controlUI.title = "Click to recenter the map";
  controlDiv.appendChild(controlUI);

  const controlText = document.createElement("div");
  controlText.style.color = "#fff";
  controlText.style.fontFamily = "Roboto,Arial,sans-serif";
  controlText.style.fontSize = "16px";
  controlText.style.lineHeight = "38px";
  controlText.style.paddingLeft = "5px";
  controlText.style.paddingRight = "5px";
  controlText.innerHTML = "Center Map on Pink Valley";
  controlUI.appendChild(controlText);

  controlUI.addEventListener("click", () => {
    map.setCenter(pinkvalley);
  });
}


function initMap() {

  var pinkvalley = {
    lat: -34.030553,
    lng: 18.829326
  }; // already set above
  var pointA = pinkvalley,
    pointB = stellenbosch,
    pointC = paarl,
    pointD = capetownint,

    myOptions = {
      zoom: 16,
      center: pinkvalley,
      mapTypeId: 'hybrid', // roadmap, sattelite, terrain, hybrid
      disableDefaultUI: true, // Disable all Controls
      zoomControl: false,
      mapTypeControl: false,
      caleControl: false,
      streetViewControl: false,
      rotateControl: false,
      fullscreenControl: true,
      fullscreenControlOptions: {
        position: google.maps.ControlPosition.BOTTOM_LEFT
      }
    }



  var map = new google.maps.Map(
      document.getElementById('map'), myOptions),

    directionsService = new google.maps.DirectionsService,
    directionsDisplay = new google.maps.DirectionsRenderer({
      map: map
    }),
    markerA = new google.maps.Marker({
      position: pointA,
      title: "point A",
      label: "A",
      map: map
    }),
    markerB = new google.maps.Marker({
      position: pointB,
      title: "point B",
      label: "B",
      map: map
    }),

  markerC = new google.maps.Marker({
    position: pointC,
    title: "Paarl",
    label: "PAARL",
    map: map
  });


  calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointC);



  // DIR ENS


  const image =
    "http://pink-valley.local/wp-content/themes/storefront-child/assets/img/icon-90.png";
  var marker = new google.maps.Marker({
    position: pinkvalley,
    map: map,
    icon: image,

  });


  const centerControlDiv = document.createElement("div");
  CenterControl(centerControlDiv, map);
  map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(centerControlDiv);

  const stellenboschControlDiv = document.createElement("div");
  StellenboschControl(stellenboschControlDiv, map);
  map.controls[google.maps.ControlPosition.TOP_CENTER].push(stellenboschControlDiv);

  const capetownintControlDiv = document.createElement("div");
  CapetownintControl(capetownintControlDiv, map);
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(capetownintControlDiv);

  const paarlControlDiv = document.createElement("div");
  PaarlControl(paarlControlDiv, map);
  map.controls[google.maps.ControlPosition.TOP_RIGHT].push(paarlControlDiv);


  // stellenboschControlDiv.addEventListener("click", () => {
  //   overlay.toggleDOM(map);
  // });



}



function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB) {
  directionsService.route({
    origin: pointA,
    destination: pointB,
    avoidTolls: true,
    avoidHighways: false,
    travelMode: google.maps.TravelMode.DRIVING
  }, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
}

initMap();
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#map {
  height: 100%;
  width: 100%;
}
<div id="map"></div>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>

标签: wordpressgoogle-mapsgoogle-maps-api-3

解决方案


为了防止方向出现在页面加载中,请删除创建它们的代码行(在initMap函数中):

calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointC);

要在单击各种控件时创建方向,请在此处调用该函数:

// paarl
    controlUI.addEventListener("click", () => {
      map.setCenter(paarl);
      calculateAndDisplayRoute(directionsService, directionsDisplay, paarl, pinkvalley);
    });
// capetown
    controlUI.addEventListener("click", () => {
      map.setCenter(capetownint);
      calculateAndDisplayRoute(directionsService, directionsDisplay, capetownint, pinkvalley);
    });
// stellonbosch
    controlUI.addEventListener("click", () => {
    calculateAndDisplayRoute(directionsService, directionsDisplay, stellenbosch, pinkvalley);
   });

概念证明小提琴

代码片段:

var directionsService = new google.maps.DirectionsService(),
  directionsDisplay = new google.maps.DirectionsRenderer();
const paarl = {
  lat: -33.727494,
  lng: 18.9261117
}

function PaarlControl(controlDiv, map) {
  const controlUI = document.createElement("div");
  controlUI.style.backgroundColor = "rgba(237,24,72,0.6)";
  controlUI.style.border = "2px solid #ed1848";
  controlUI.style.borderRadius = "3px 3px 0 0";
  controlUI.style.boxShadow = "0 2px 6px rgba(0,0,0,.3)";
  controlUI.style.cursor = "pointer";
  controlUI.style.marginBottom = "22px";
  controlUI.style.textAlign = "center";
  controlUI.title = "Click for directions from Paarl";
  controlDiv.appendChild(controlUI);

  const controlText = document.createElement("div");
  controlText.style.color = "#fff";
  controlText.style.fontFamily = "Roboto,Arial,sans-serif";
  controlText.style.fontSize = "16px";
  controlText.style.lineHeight = "24px";
  controlText.style.paddingLeft = "5px";
  controlText.style.paddingRight = "5px";
  controlText.innerHTML = "Paarl<br>42km<br><small>click for directions to Pink Valley</small>";
  controlUI.appendChild(controlText);

  controlUI.addEventListener("click", () => {
    map.setCenter(paarl);
    calculateAndDisplayRoute(directionsService, directionsDisplay, paarl, pinkvalley);
  });
}

// ==================
// LABEL CAPE TOWN
// ==================
const capetownint = {
  lat: -33.971463,
  lng: 18.5998911
}

function CapetownintControl(controlDiv, map) {
  const controlUI = document.createElement("div");
  controlUI.style.backgroundColor = "rgba(237,24,72,0.6)";
  controlUI.style.border = "2px solid #ed1848";
  controlUI.style.borderRadius = "3px 3px 0 0";
  controlUI.style.boxShadow = "0 2px 6px rgba(0,0,0,.3)";
  controlUI.style.cursor = "pointer";
  controlUI.style.marginBottom = "22px";
  controlUI.style.textAlign = "center";
  controlUI.title = "Click for directions from Cape Town International";
  controlDiv.appendChild(controlUI);

  const controlText = document.createElement("div");
  controlText.style.color = "#fff";
  controlText.style.fontFamily = "Roboto,Arial,sans-serif";
  controlText.style.fontSize = "16px";
  controlText.style.lineHeight = "24px";
  controlText.style.paddingLeft = "5px";
  controlText.style.paddingRight = "5px";
  controlText.innerHTML = "Cape Town International<br>32km<br><small>click for directions to Pink Valley</small>";
  controlUI.appendChild(controlText);

  controlUI.addEventListener("click", () => {
    map.setCenter(capetownint);
    calculateAndDisplayRoute(directionsService, directionsDisplay, capetownint, pinkvalley);
  });
}

// ==================
// LABEL STELLENBOSCH
// ==================
const stellenbosch = {
  lat: -33.9466715,
  lng: 18.774375
}

function StellenboschControl(controlDiv, map) {
  const controlUI = document.createElement("div");
  controlUI.style.backgroundColor = "rgba(237,24,72,0.6)";
  controlUI.style.border = "2px solid #ed1848";
  controlUI.style.borderRadius = "3px 3px 0 0";
  controlUI.style.boxShadow = "0 2px 6px rgba(0,0,0,.3)";
  controlUI.style.cursor = "pointer";
  controlUI.style.marginBottom = "22px";
  controlUI.style.textAlign = "center";
  controlUI.title = "Click for directions from Stellenbosch";
  controlDiv.appendChild(controlUI);

  const controlText = document.createElement("div");
  controlText.style.color = "#fff";
  controlText.style.fontFamily = "Roboto,Arial,sans-serif";
  controlText.style.fontSize = "16px";
  controlText.style.lineHeight = "24px";
  controlText.style.paddingLeft = "5px";
  controlText.style.paddingRight = "5px";
  controlText.innerHTML = "STELLENBOSCH<br>13km<br><small>click for directions to Pink Valley</small>";
  controlUI.appendChild(controlText);
  controlUI.addEventListener("click", () => {
    calculateAndDisplayRoute(directionsService, directionsDisplay, stellenbosch, pinkvalley);
  });
}

// ==================
// CENTER
// ==================
// let map;
const pinkvalley = {
  lat: -34.030553,
  lng: 18.829326
}

function CenterControl(controlDiv, map) {
  const controlUI = document.createElement("div");
  controlUI.style.backgroundColor = "rgba(237,24,72,0.6)";
  controlUI.style.border = "2px solid #ed1848";
  controlUI.style.borderRadius = "3px 3px 0 0";
  controlUI.style.boxShadow = "0 2px 6px rgba(0,0,0,.3)";
  controlUI.style.cursor = "pointer";
  controlUI.style.marginBottom = "22px";
  controlUI.style.textAlign = "center";
  controlUI.title = "Click to recenter the map";
  controlDiv.appendChild(controlUI);

  const controlText = document.createElement("div");
  controlText.style.color = "#fff";
  controlText.style.fontFamily = "Roboto,Arial,sans-serif";
  controlText.style.fontSize = "16px";
  controlText.style.lineHeight = "38px";
  controlText.style.paddingLeft = "5px";
  controlText.style.paddingRight = "5px";
  controlText.innerHTML = "Center Map on Pink Valley";
  controlUI.appendChild(controlText);

  controlUI.addEventListener("click", () => {
    map.setCenter(pinkvalley);
  });
}

function initMap() {
  var pinkvalley = {
    lat: -34.030553,
    lng: 18.829326
  }; // already set above
  var pointA = pinkvalley,
    pointB = stellenbosch,
    pointC = paarl,
    pointD = capetownint,

    myOptions = {
      zoom: 16,
      center: pinkvalley,
      mapTypeId: 'hybrid', // roadmap, sattelite, terrain, hybrid
      disableDefaultUI: true, // Disable all Controls
      zoomControl: false,
      mapTypeControl: false,
      caleControl: false,
      streetViewControl: false,
      rotateControl: false,
      fullscreenControl: true,
      fullscreenControlOptions: {
        position: google.maps.ControlPosition.BOTTOM_LEFT
      }
    }

  var map = new google.maps.Map(
      document.getElementById('map'), myOptions),
    markerA = new google.maps.Marker({
      position: pointA,
      title: "point A",
      label: "A",
      map: map
    }),
    markerB = new google.maps.Marker({
      position: pointB,
      title: "point B",
      label: "B",
      map: map
    }),

    markerC = new google.maps.Marker({
      position: pointC,
      title: "Paarl",
      label: "PAARL",
      map: map
    });

  directionsDisplay.setMap(map);

  // DIR ENS
  var marker = new google.maps.Marker({
    position: pinkvalley,
    map: map,
  });

  const centerControlDiv = document.createElement("div");
  CenterControl(centerControlDiv, map);
  map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(centerControlDiv);

  const stellenboschControlDiv = document.createElement("div");
  StellenboschControl(stellenboschControlDiv, map);
  map.controls[google.maps.ControlPosition.TOP_CENTER].push(stellenboschControlDiv);

  const capetownintControlDiv = document.createElement("div");
  CapetownintControl(capetownintControlDiv, map);
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(capetownintControlDiv);

  const paarlControlDiv = document.createElement("div");
  PaarlControl(paarlControlDiv, map);
  map.controls[google.maps.ControlPosition.TOP_RIGHT].push(paarlControlDiv);
}

function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB) {
  directionsService.route({
    origin: pointA,
    destination: pointB,
    avoidTolls: true,
    avoidHighways: false,
    travelMode: google.maps.TravelMode.DRIVING
  }, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
}

initMap();
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#map {
  height: 100%;
  width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>


推荐阅读