如何在谷歌地图上显示方向后隐藏其他标记

时间:2018-06-11 01:44:16

标签: javascript php google-maps google-maps-api-3 xmlhttprequest

此谷歌地图用于获取指向客户坐标指定位置的路线。

要从select中的数据中获取,我将其设为use std::ops::Rem; trait EvenOdd { fn is_even(&self) -> bool; } impl<T> EvenOdd for T where T: Copy + From<u16> + PartialEq + Rem<Output=T> { fn is_even(&self) -> bool { *self % From::from(2u16) == From::from(0u16) } } fn main() { let x: u16 = 11; let y: u32 = 44; println!("x = {}, y = {}", x.is_even(), y.is_even()); } 对象,并将坐标保存为值中的字符串,然后我解析出纬度和经度以创建{{1}对象。

步骤是:

1 - 保存选项值中的坐标:

google.maps.LatLng

2解析这些坐标并在路线请求中创建LatLng对象:

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

** 2 - ***并且我添加此功能以隐藏其他标记*

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;
  }
  // ....

这个问题我已经面临好几天似乎无法解决,即使我已尝试在此处查看各种代码块以及Google Maps API文档,但STILL仍然无法解决弄清楚如何隐藏其他标记。

任何建议,想法和帮助都将非常感谢!

这是截图:

enter image description here

-------------------------------------------- -------------------------------------------------- ------------------------------------

这是我更新后的代码

在您的建议之后,这是我的代码的更新。

它工作正常,点击按钮(清除标记)后,所有标记都将删除。

现在我想知道如何使函数 toggleMarkers(),删除所有标记,但它会将标记与我选择的代码客户端保持一致,

&#13;
&#13;
    makeRequest('https://gist.githubusercontent.com/abdelhakimsalama/3cce25789f00c1b84ccb5b231ec455b7/raw/393220f08a02b962e3e764d2b497b318353828db/gistfile1.txt', function(data) {

    for (var i = 0; i < data.length; i++) {

      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(data[i].Latitude, data[i].Longitude),
        title: data[i].CodeClient,
        map: map
        });

        gmarkers.push(marker);
    }

  }); 
&#13;
 function toggleMarkers() {
  for (i = 0; i < gmarkers.length; i++) {
    if (gmarkers[i].getMap() != null) gmarkers[i].setMap(null);
    else gmarkers[i].setMap(map);
  }
}
&#13;
var gmarkers = [];

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/3cce25789f00c1b84ccb5b231ec455b7/raw/393220f08a02b962e3e764d2b497b318353828db/gistfile1.txt', 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 toggleMarkers() {
  for (i = 0; i < gmarkers.length; i++) {
    if (gmarkers[i].getMap() != null) gmarkers[i].setMap(null);
    else gmarkers[i].setMap(map);
  }
}	
						/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

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;
  var hakim = document.getElementById('destination');
  console.log("selected option value=" + destination);
  console.log(" value=" + hakim);
  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);
    }
  });
  alert("???");
  displayLocation(hakim);
}

						/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

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
    });
	gmarkers.push(marker);

    google.maps.event.addListener(marker, 'click', function() {
      infowindow.setContent(content);
      infowindow.open(map, marker);
    });
  }
}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您永远不会调用toggleMarkers函数。

  1. 将其修改为hideMarkers
  2. function hideMarkers() {
      for (i = 0; i < gmarkers.length; i++) {
        gmarkers[i].setMap(null);
      }
    }
    
    1. 然后在成功的方向服务回调函数中调用它:
    2. function calculateRoute() {
        var start = document.getElementById('start').value;
        var destination = document.getElementById('destination').value;
        var hakim = document.getElementById('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
        };
        directionsService.route(request, function(response, status) {
          if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            hideMarkers();  // <========================= call it here
          }
        });
        displayLocation(hakim);
      }
      

      代码段

      var gmarkers = [];
      
      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/3cce25789f00c1b84ccb5b231ec455b7/raw/393220f08a02b962e3e764d2b497b318353828db/gistfile1.txt', 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 hideMarkers() {
        console.log("gmarkers.length=" + gmarkers.length);
        for (i = 0; i < gmarkers.length; i++) {
          gmarkers[i].setMap(null);
        }
      }
      /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
      
      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;
        var hakim = document.getElementById('destination');
        console.log("selected option value=" + destination);
        console.log(" value=" + hakim);
        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);
            hideMarkers();
          }
        });
        displayLocation(hakim);
      }
      
      /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
      
      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
          });
          gmarkers.push(marker);
      
          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="clear map" onclick="toggleMarkers();" />
        </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>

答案 1 :(得分:0)

您无需使用var marker = new google.maps.Marker作为 Directions API 。它们会自动添加到那里,并且一旦您请求新路线,它们也会自动消失。

这是一个示例应用,可在下拉菜单更改后呈现路线。您可以看到它没有调用markerinfowindow对象的任何内容的Javascript代码,但它们都存在于地图中。 marker会自动添加到起点和终点上。如果您点击这些标记,infowindow会自动显示!

function initMap() {
   var directionsService = new google.maps.DirectionsService();
   var chicago = new google.maps.LatLng(41.85, -87.65);
   var directionsDisplay = new google.maps.DirectionsRenderer();
   var map = new google.maps.Map(document.getElementById('distance-map'), {
      zoom: 5.2,
      center: chicago
   });
   directionsDisplay.setMap(map);

   var onChangeHandler = function() {
      calculateAndDisplayRoute(directionsService, directionsDisplay);
   };
   document.getElementById('start').addEventListener('change', onChangeHandler);
   document.getElementById('end').addEventListener('change', onChangeHandler);
}

function calculateAndDisplayRoute(directionsService, directionsDisplay) {
   directionsService.route({
      origin: document.getElementById('start').value,
      destination: document.getElementById('end').value,
      travelMode: 'DRIVING'
   }, function(response, status) {
      if (status === 'OK') {
         directionsDisplay.setDirections(response);
      } else {
         window.alert('Directions request failed due to ' + status);
      }
   });
}
#distance-map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#floating-panel {
  position: absolute;
  top: 10px;
  left: 25%;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
  text-align: center;
  font-family: 'Roboto','sans-serif';
  line-height: 30px;
  padding-left: 10px;
}
#warnings-panel {
  width: 100%;
  height:10%;
  text-align: center;
}
<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
   </head>
   <body>
   <br />
      <div id="distance-panel">
         Start:
         <select id="start">
            <option value='41.878114,-87.629798'>Chicago</option>
            <option value='42.331427,-83.045754'>Detroit</option>
            <option value='39.099727,-94.578567'>Kansas City</option>
            <option value='41.600545,-93.609106'>Des Molines</option>
         </select>
         End:
         <select id="end">
            <option value='38.833882,-104.821363'>Colorado Springs</option>
            <option value='36.162664,-86.781602'>Nashville</option>
            <option value='39.768403,-86.158068'>Indianapolis</option>
            <option value='36.162664,-86.781602'>Nashville</option>
         </select>
      </div>
      <br />
      <div id="distance-map"></div>
      <script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDLHKWYAEE2PDjvt6BaBH1SIs4Q93PMpQs&callback=initMap">
</script>
   </body>
</html>

  

您也可以查看jsbin版本   here

希望这能回答你的问题。

相关问题