首页 > 解决方案 > 显示方向

问题描述

我在 HTML 页面中使用 JavaScript 来显示带有标记的 GPS 位置,并且所有这些 GPS 位置都已连接

我正在尝试使用 Google maps V3 API 实现基于地图/方向的应用程序。到目前为止,我已经能够显示地图并显示所选两个位置的方向。第一个是我当前的位置,第二个是客户的位置(他/她的信息存在于我的数据库中)。所有标记都正确显示在输出中。

标签: html

解决方案


要获取到由坐标指定的位置的路线,请将其设为google.maps.LatLng对象。要从选择中的数据中获取它,请将坐标保存为值中的字符串,然后解析出纬度和经度以创建LatLng对象。

  1. 将坐标保存在选项值中:
for (var i = 0; i < data.length; i++) {
  displayLocation(data[i]);
  addOption(selectBox, data[i]['CodeClient'], data[i].Latitude + "," + data[i].Longitude);
}
  1. google.maps.LatLng解析这些坐标并在方向请求中创建一个对象:
function calculateRoute() {

  var start = document.getElementById('start').value;
  var destination = document.getElementById('destination').value;
  console.log("selected option value=" + destination);
  var destPt = destination.split(",");
  var destination = new google.maps.LatLng(destPt[0], destPt[1]);
  if (start == '') {
    start = center;
  }
  // ....

概念证明小提琴

代码片段:

var map;
var directionsService;
var directionsDisplay;
var geocoder;
var infowindow;

function init() {
  directionsService = new google.maps.DirectionsService();
  directionsDisplay = new google.maps.DirectionsRenderer();
  geocoder = new google.maps.Geocoder();
  infowindow = new google.maps.InfoWindow();
  var mapOptions = {
    zoom: 6,
    center: center = new google.maps.LatLng(32, -6),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }

  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

  directionsDisplay.setMap(map);
  directionsDisplay.setPanel(document.getElementById('directions_panel'));

  // Detect user location
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {

      var userLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

      geocoder.geocode({
        'latLng': userLocation
      }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          document.getElementById('start').value = results[0].formatted_address
        }
      });

    }, function() {
      alert('Geolocation is supported, but it failed');
    });
  }

  makeRequest('https://gist.githubusercontent.com/abdelhakimsalama/358669eda44d8d221bf58c629402c40b/raw/eca59a21899fe19b1f556ff033a33dff2a6bdd0c/get_data_google_api', function(data) {

    var data = JSON.parse(data.responseText);
    var selectBox = document.getElementById('destination');

    for (var i = 0; i < data.length; i++) {
      displayLocation(data[i]);
      addOption(selectBox, data[i]['CodeClient'], data[i].Latitude + "," + data[i].Longitude);
    }
  });

}

function addOption(selectBox, text, value) {
  var option = document.createElement("OPTION");
  option.text = text;
  option.value = value;
  selectBox.options.add(option);
}

function calculateRoute() {
  var start = document.getElementById('start').value;
  var destination = document.getElementById('destination').value;
  console.log("selected option value=" + destination);
  var destPt = destination.split(",");
  var destination = new google.maps.LatLng(destPt[0], destPt[1]);
  if (start == '') {
    start = center;
  }

  var request = {
    origin: start,
    destination: destination,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  console.log("origin:" + start);
  console.log("dest:" + destination.toUrlValue(12));
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
  });
}

function makeRequest(url, callback) {
  var request;
  if (window.XMLHttpRequest) {
    request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
  } else {
    request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
  }
  request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200) {
      callback(request);
    }
  }
  request.open("GET", url, true);
  request.send();
}


function displayLocation(rythmstu_innotec) {
  var content = '<div class="infoWindow"><strong> Code Client : ' + rythmstu_innotec.CodeClient + '</strong>' +
    '<br />Latitude : ' + rythmstu_innotec.Latitude +
    '<br />Longitude : ' + rythmstu_innotec.Longitude +
    '<br />Route : ' + rythmstu_innotec.Route +
    '<br />Secteur : ' + rythmstu_innotec.Secteur +
    '<br />Agence : ' + rythmstu_innotec.Agence +
    '<br />prenom de Client : ' + rythmstu_innotec.PrenomClient +
    '<br />Num Adresse : ' + rythmstu_innotec.NumAdresse +
    '<br />GeoAdresse : ' + rythmstu_innotec.GeoAdresse +
    '<br />Téléphone : ' + rythmstu_innotec.Tel +
    '<br />Whatsapp : ' + rythmstu_innotec.Whatsapp +
    '<br />Nbr Frigos : ' + rythmstu_innotec.NbrFrigo +
    '<br />Ouverture Matin : ' + rythmstu_innotec.OpenAm +
    '<br />Fermeture Matin : ' + rythmstu_innotec.CloseAm +
    '<br />Ouverture après-midi : ' + rythmstu_innotec.OpenPm +
    '<br />Fermeture Après-midi : ' + rythmstu_innotec.ClosePm + '</div>';

  if (parseInt(rythmstu_innotec.Latitude) == 0) {
    geocoder.geocode({
      'GeoAdresse': rythmstu_innotec.GeoAdresse
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.rythmstu_innotec,
          title: rythmstu_innotec.name
        });

        google.maps.event.addListener(marker, 'click', function() {
          infowindow.setContent(content);
          infowindow.open(map, marker);
        });
      }
    });
  } else {
    var position = new google.maps.LatLng(parseFloat(rythmstu_innotec.Latitude), parseFloat(rythmstu_innotec.Longitude));
    var marker = new google.maps.Marker({
      map: map,
      position: position,
      title: rythmstu_innotec.name
    });

    google.maps.event.addListener(marker, 'click', function() {
      infowindow.setContent(content);
      infowindow.open(map, marker);
    });
  }
}
body {
  font: normal 14px Verdana;
}

h1 {
  font-size: 24px;
}

h2 {
  font-size: 18px;
}

#sidebar {
  float: right;
  width: 30%;
}

#main {
  padding-right: 15px;
}

.infoWindow {
  width: 220px;
}
<title>MAP itinéraire </title>
<meta charset="utf-8">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>

<body onload="init();">



  <form id="services">
    Location: <input type="text" id="start" value="Midar" /> Destination:
    <select id="destination" onchange="calculateRoute();"></select>
    <input type="button" value="afficher la direction" onclick="calculateRoute();" />
  </form>

  <section id="sidebar">
    <div id="directions_panel"></div>
  </section>

  <section id="main">
    <div id="map_canvas" style="width: 70%; height: 750px;"></div>
  </section>

</body>


推荐阅读