duanguanye4124 2018-06-11 01:44
浏览 254
已采纳

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

this google map is to get directions to a location specified by coordinates of the customer as the destination.

To get that from data in the select, i make it a google.maps.LatLng object, and i save the coordinates as a string in the value, then i parse out the latitude and longitude to create the LatLng object.

the steps is :

1-save the coordinates in the option value:

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

2-parse those coordinates and create a google.maps.LatLng object in the directions request:

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

(all the above works fine)

-----This is where i am stuck:-----

Even the direction to a specified marker is displayed, the problem is that all markers still in the map, for me I try to make my function display just two things the direction and the marker with the code-client whom I choose, and all other markers will hide.

Here is my Notes about what i add in my code,

**1--***Once I added this function to push all markers in one variable*

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

  }); 

**2--***and i add this function to hide other markers*

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

This problem I have been facing for days and can't seem to resolve , even I've tried looking at a large variety of code blocks here and on the Google Maps API documentation but STILL have not been able to figure out how to hide other markers.

Any suggestions, ideas and help will much appreciated!

this is a screenshot :

enter image description here

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

Here is my code after i updated it

after your advises ,this the update of my code .

it work good , after i click on the button (clear markers) all markers will remove.

Now i wanna know how to make the function toggleMarkers() , remove all markers but it will keep the marker with the code-client whom I choose,

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

</div>
  • 写回答

2条回答 默认 最新

  • drh78568 2018-06-12 16:06
    关注

    You never call the toggleMarkers function.

    1. Modified it to be hideMarkers:
    function hideMarkers() {
      for (i = 0; i < gmarkers.length; i++) {
        gmarkers[i].setMap(null);
      }
    }
    
    1. Then call it in the directions service callback function on success:
    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);
    }
    

    code snippet:

    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>

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图