使用Google Maps Api在点击事件中的2点之间显示路线 [英] Show Directions between 2 points on click event with Google Maps Api

查看:95
本文介绍了使用Google Maps Api在点击事件中的2点之间显示路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need help with the Google Maps API and the direction Services

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

My Goal: To create a map centred on my primary address. The create 3x overlay buttons to represent nearby towns. Once a user clicks on either of the buttons, the directions/route between the selected town and my primary address will display. A fourth button will enable a user to reset the map, centre it and remove the directions.

到目前为止已实现

  • 创建地图并将其居中于我的主要位置
  • 为3x城镇创建叠加按钮,尽管单击事件不起作用
  • 创建第四个按钮以使地图居中
  • 在其中一个城镇和我的主要地址之间创建溃败

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

Need help with To only show the route when the button is clicked. At the moment the route display from the get go. To make the rout disappear when the reset button is clicked. To change the route if another town button is clicked.

资源

  • Image:
  • Link my dev site: (map at the bottom)
  • Link to my fiddle, which is working.

代码段:

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>

推荐答案

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

To prevent the directions from appearing on page load, remove the line of code that creates them (in the initMap function):

calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointC);

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

To create directions on click of your various controls, call that function there instead:

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

这篇关于使用Google Maps Api在点击事件中的2点之间显示路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆