-1

below is code with 2 sidebars. The first sidebar appears when you enter an address and is a listing of title, address and get directions link sorted by actual mileage. When you click one of the get directions links, a second sidebar with directions appears and goes over top of the first sidebar so that it's not visible. An X button also appears with the second sidebar and when clicked, the 2nd sidebar disappears leaving just the first sidebar.

My question concerns the markers. When I click on a get directions link from the first sidebar, I would like to have the directions pop up on the second sidebar as they currently do. But on the map, I would like to have all the markers be removed except for the A and the B representing the to and from locations for the requested directions. Then when the X is clicked on the second sidebar, all the markers would reappear bringing back the first sidebar as it was.

Anyone know how to do this. Thanks

The Fiddle

<!DOCTYPE html>
<html>
<head>
    <style>
        html,
body,
#map_canvas {
  margin: 0;
  padding: 0;
  height: 100%;
}
table,
tr,
td {
  height: 100%;
}
.text {
  width: 300px;
  height: 600px;
  background-color: white;
  overflow: scroll;
  overflow-x: hidden;
}
#side_bar {
  z-index: 100;
  position: absolute;
  top: 0px;
  left: 400px;
}
#panel {
  z-index: -100;
  display: block;
  position: absolute;
  top: 25px;
  left: 400px;
}
#mdiv {
  z-index: 500;
  width: 25px;
  height: 25px;
  display: none;
  background-color: red;
  border: 1px solid black;
  position: absolute;
  left: 400px;
  top: 0px;
}
.mdiv {
  height: 25px;
  width: 2px;
  margin-left: 12px;
  background-color: black;
  transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  /* IE 9 */
  -webkit-transform: rotate(45deg);
  /* Safari and Chrome */
  z-index: 1;
}
.md {
  height: 25px;
  width: 2px;
  background-color: black;
  transform: rotate(90deg);
  -ms-transform: rotate(90deg);
  /* IE 9 */
  -webkit-transform: rotate(90deg);
  /* Safari and Chrome */
  z-index: 2;
}
    </style>
</head>
<body>
    <script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="0">
  <tr>
    <td>
      <div id="map" style="height: 100%; width:400px;"></div>
    </td>
    <td>
      <div id="side_bar" class='text'></div>
      <div id="panel" class='text'></div>
    </td>
  </tr>
</table>

<input id="address" type="text" value="Paramus, NJ" />
<input type="button" value="Search" onclick="codeAddress();" />
<div id="info"></div>
<div id="mdiv">
  <div class="mdiv">
    <div class="md">
    </div>
  </div>
</div>
    <script type="text/javascript">
        var locations = [
  ["John Doe", "145 Rock Ridge Road, Chester, NY ", "41.314926,-74.270134", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
  ["Jim Smith", "12 Williams Rd, Montvale, NJ ", "41.041599,-74.019554", "http://maps.google.com/mapfiles/ms/icons/green.png"],
  ["John Jones", "689 Fern St Township of Washington, NJ ", "40.997704,-74.050598", "http://maps.google.com/mapfiles/ms/icons/yellow.png"],

];
// alert(locations.length);

var geocoder = null;
var map = null;
var customerMarker = null;
var gmarkers = [];
var closest = [];
var directionsDisplay = new google.maps.DirectionsRenderer();;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
  // alert("init");
  geocoder = new google.maps.Geocoder();
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 9,
    center: new google.maps.LatLng(52.6699927, -0.7274620),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  var infowindow = new google.maps.InfoWindow();
  var marker, i;
  var bounds = new google.maps.LatLngBounds();
  document.getElementById('info').innerHTML = "found " + locations.length + " locations<br>";
  for (i = 0; i < locations.length; i++) {
    var coordStr = locations[i][2];
    var coords = coordStr.split(",");
    var pt = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
    bounds.extend(pt);
    marker = new google.maps.Marker({
      position: pt,
      map: map,
      icon: locations[i][3],
      address: locations[i][1],
      title: locations[i][0],
      html: locations[i][0] + "<br>" + locations[i][1] + "<br><br><a href='javascript:getDirections(customerMarker.getPosition(),&quot;" + locations[i][1] + "&quot;);'>Get Directions</a>"
    });
    gmarkers.push(marker);
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(marker.html);
          infowindow.open(map, marker);
        }
      })
      (marker, i));
  }
  map.fitBounds(bounds);

  $("#mdiv").click(function() {
    $("#side_bar").css({
      "z-index": 100,
      "top": "0px"
    });
    $("#panel").css("z-index", -100);
    $("#mdiv").css("display", "none");
  })

}

function codeAddress() {
  var address = document.getElementById('address').value;
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      if (customerMarker) customerMarker.setMap(null);
      customerMarker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
      });
      closest = findClosestN(results[0].geometry.location, 12);
      // get driving distance
      closest = closest.splice(0, 12);
      calculateDistances(results[0].geometry.location, closest, 12);
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

function findClosestN(pt, numberOfResults) {
  var closest = [];
  document.getElementById('info').innerHTML += "processing " + gmarkers.length + "<br>";
  for (var i = 0; i < gmarkers.length; i++) {
    gmarkers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt, gmarkers[i].getPosition());
    document.getElementById('info').innerHTML += "process " + i + ":" + gmarkers[i].getPosition().toUrlValue(6) + ":" + gmarkers[i].distance.toFixed(2) + "<br>";
    gmarkers[i].setMap(null);
    closest.push(gmarkers[i]);
    closest.sort(sortByDist);
  }

  return closest;
}

function sortByDist(a, b) {
  return (a.distance - b.distance)

}

function calculateDistances(pt, closest, numberOfResults) {
  var service = new google.maps.DistanceMatrixService();
  var request = {
    origins: [pt],
    destinations: [],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.IMPERIAL,
    avoidHighways: false,
    avoidTolls: false
  };
  for (var i = 0; i < closest.length; i++) {
    request.destinations.push(closest[i].getPosition());
  }
  service.getDistanceMatrix(request, function(response, status) {
    if (status != google.maps.DistanceMatrixStatus.OK) {
      alert('Error was: ' + status);
    } else {
      var origins = response.originAddresses;
      var destinations = response.destinationAddresses;
      var outputDiv = document.getElementById('side_bar');
      outputDiv.innerHTML = '';

      var results = response.rows[0].elements;
      // save title and address in record for sorting
      for (var i = 0; i < closest.length; i++) {
        results[i].title = closest[i].title;
        results[i].address = closest[i].address;
        results[i].idx_closestMark = i;
      }
      results.sort(sortByDistDM);
      for (var i = 0;
        ((i < numberOfResults) && (i < closest.length)); i++) {
        closest[i].setMap(map);

        outputDiv.innerHTML += "<a href='javascript:google.maps.event.trigger(closest[" + results[i].idx_closestMark + "],\"click\");'>" + results[i].title + '</a><br>' + results[i].address + "<br>" + results[i].distance.text + ' approximately ' + results[i].duration.text + "<br><a href='javascript:getDirections(customerMarker.getPosition(),&quot;" + results[i].address + "&quot;);'>Get Directions</a><br><hr>"

      }
    }
  });
}

function getDirections(origin, destination) {
  var request = {
    origin: origin,
    destination: destination,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setMap(map);
      directionsDisplay.setDirections(response);
      $("#side_bar").css({
        "z-index": -100,
        "top": "25px"
      });
      $("#panel").css("z-index", 100);
      $("#mdiv").css("display", "block");

      directionsDisplay.setPanel(document.getElementById('panel'));


    }
  });
}

function sortByDistDM(a, b) {
  return (a.distance.value - b.distance.value)
}

google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</body>
</html>
Nick is tired
  • 6,860
  • 20
  • 39
  • 51
Vince GOGO
  • 31
  • 1
  • 9
  • Maybe this one? "How to remove all markers" http://stackoverflow.com/questions/1544739/google-maps-api-v3-how-to-remove-all-markers?answertab=votes#tab-top – wf9a5m75 Feb 29 '16 at 19:31
  • What have you tried that didn't work? There are references to the markers in the array `gmarkers`. – geocodezip Feb 29 '16 at 19:35

2 Answers2

0

One option would be to create a hideMarkers and a showMarkers function.

function hideMarkers() {
  for (var i=0; i<gmarkers.length; i++) {
    gmarkers[i].setMap(null);
  }
  customerMarker.setMap(null);
}

function showMarkers() {
  for (var i=0; i<gmarkers.length; i++) {
    gmarkers[i].setMap(map);
  }
  customerMarker.setMap(map);
  directionsDisplay.setMap(null);
}

Call the hideMarkers function when you display the directions, call the showMarkers function when the directions panel on the sidebar is removed.

proof of concept fiddle

code snippet:

var geocoder = null;
var map = null;
var customerMarker = null;
var gmarkers = [];
var closest = [];
var directionsDisplay = new google.maps.DirectionsRenderer();;
var directionsService = new google.maps.DirectionsService();
var map;

function hideMarkers() {
  for (var i = 0; i < gmarkers.length; i++) {
    gmarkers[i].setMap(null);
  }
  customerMarker.setMap(null);
}

function showMarkers() {
  for (var i = 0; i < gmarkers.length; i++) {
    gmarkers[i].setMap(map);
  }
  customerMarker.setMap(map);
  directionsDisplay.setMap(null);
}

function initialize() {
  // alert("init");
  geocoder = new google.maps.Geocoder();
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 9,
    center: new google.maps.LatLng(52.6699927, -0.7274620),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  var infowindow = new google.maps.InfoWindow();
  var marker, i;
  var bounds = new google.maps.LatLngBounds();
  document.getElementById('info').innerHTML = "found " + locations.length + " locations<br>";
  for (i = 0; i < locations.length; i++) {
    var coordStr = locations[i][2];
    var coords = coordStr.split(",");
    var pt = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
    bounds.extend(pt);
    marker = new google.maps.Marker({
      position: pt,
      map: map,
      icon: locations[i][3],
      address: locations[i][1],
      title: locations[i][0],
      html: locations[i][0] + "<br>" + locations[i][1] + "<br><br><a href='javascript:getDirections(customerMarker.getPosition(),&quot;" + locations[i][1] + "&quot;);'>Get Directions</a>"
    });
    gmarkers.push(marker);
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(marker.html);
          infowindow.open(map, marker);
        }
      })
      (marker, i));
  }
  map.fitBounds(bounds);

  $("#mdiv").click(function() {
    $("#side_bar").css({
      "z-index": 100,
      "top": "0px"
    });
    $("#panel").css("z-index", -100);
    $("#mdiv").css("display", "none");
    showMarkers();
  });
}

function codeAddress() {
  var address = document.getElementById('address').value;
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      if (customerMarker) customerMarker.setMap(null);
      customerMarker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
      });
      closest = findClosestN(results[0].geometry.location, 12);
      // get driving distance
      closest = closest.splice(0, 12);
      calculateDistances(results[0].geometry.location, closest, 12);
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

function findClosestN(pt, numberOfResults) {
  var closest = [];
  document.getElementById('info').innerHTML += "processing " + gmarkers.length + "<br>";
  for (var i = 0; i < gmarkers.length; i++) {
    gmarkers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt, gmarkers[i].getPosition());
    document.getElementById('info').innerHTML += "process " + i + ":" + gmarkers[i].getPosition().toUrlValue(6) + ":" + gmarkers[i].distance.toFixed(2) + "<br>";
    gmarkers[i].setMap(null);
    closest.push(gmarkers[i]);
    closest.sort(sortByDist);
  }
  return closest;
}

function sortByDist(a, b) {
  return (a.distance - b.distance);
}

function calculateDistances(pt, closest, numberOfResults) {
  var service = new google.maps.DistanceMatrixService();
  var request = {
    origins: [pt],
    destinations: [],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.IMPERIAL,
    avoidHighways: false,
    avoidTolls: false
  };
  for (var i = 0; i < closest.length; i++) {
    request.destinations.push(closest[i].getPosition());
  }
  service.getDistanceMatrix(request, function(response, status) {
    if (status != google.maps.DistanceMatrixStatus.OK) {
      alert('Error was: ' + status);
    } else {
      var origins = response.originAddresses;
      var destinations = response.destinationAddresses;
      var outputDiv = document.getElementById('side_bar');
      outputDiv.innerHTML = '';

      var results = response.rows[0].elements;
      // save title and address in record for sorting
      for (var i = 0; i < closest.length; i++) {
        results[i].title = closest[i].title;
        results[i].address = closest[i].address;
        results[i].idx_closestMark = i;
      }
      results.sort(sortByDistDM);
      for (var i = 0;
        ((i < numberOfResults) && (i < closest.length)); i++) {
        closest[i].setMap(map);

        outputDiv.innerHTML += "<a href='javascript:google.maps.event.trigger(closest[" + results[i].idx_closestMark + "],\"click\");'>" + results[i].title + '</a><br>' + results[i].address + "<br>" + results[i].distance.text + ' approximately ' + results[i].duration.text + "<br><a href='javascript:getDirections(customerMarker.getPosition(),&quot;" + results[i].address + "&quot;);'>Get Directions</a><br><hr>"
      }
    }
  });
}

function getDirections(origin, destination) {
  var request = {
    origin: origin,
    destination: destination,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setMap(map);
      directionsDisplay.setDirections(response);
      $("#side_bar").css({
        "z-index": -100,
        "top": "25px"
      });
      $("#panel").css("z-index", 100);
      $("#mdiv").css("display", "block");
      hideMarkers();
      directionsDisplay.setPanel(document.getElementById('panel'));
    }
  });
}

function sortByDistDM(a, b) {
  return (a.distance.value - b.distance.value)
}

google.maps.event.addDomListener(window, 'load', initialize);
var locations = [
  ["John Doe", "145 Rock Ridge Road, Chester, NY ", "41.314926,-74.270134", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
  ["Jim Smith", "12 Williams Rd, Montvale, NJ ", "41.041599,-74.019554", "http://maps.google.com/mapfiles/ms/icons/green.png"],
  ["John Jones", "689 Fern St Township of Washington, NJ ", "40.997704,-74.050598", "http://maps.google.com/mapfiles/ms/icons/yellow.png"],

];
html,
body,
#map_canvas {
  margin: 0;
  padding: 0;
  height: 100%;
}
table,
tr,
td {
  height: 100%;
}
.text {
  width: 300px;
  height: 600px;
  background-color: white;
  overflow: scroll;
  overflow-x: hidden;
}
#side_bar {
  z-index: 100;
  position: absolute;
  top: 0px;
  left: 400px;
}
#panel {
  z-index: -100;
  display: block;
  position: absolute;
  top: 25px;
  left: 400px;
}
#mdiv {
  z-index: 500;
  width: 25px;
  height: 25px;
  display: none;
  background-color: red;
  border: 1px solid black;
  position: absolute;
  left: 400px;
  top: 0px;
}
.mdiv {
  height: 25px;
  width: 2px;
  margin-left: 12px;
  background-color: black;
  transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  /* IE 9 */
  -webkit-transform: rotate(45deg);
  /* Safari and Chrome */
  z-index: 1;
}
.md {
  height: 25px;
  width: 2px;
  background-color: black;
  transform: rotate(90deg);
  -ms-transform: rotate(90deg);
  /* IE 9 */
  -webkit-transform: rotate(90deg);
  /* Safari and Chrome */
  z-index: 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<table border="0">
  <tr>
    <td>
      <div id="map" style="height: 100%; width:400px;"></div>
    </td>
    <td>
      <div id="side_bar" class='text'></div>
      <div id="panel" class='text'></div>
    </td>
  </tr>
</table>

<input id="address" type="text" value="Paramus, NJ" />
<input type="button" value="Search" onclick="codeAddress();" />
<div id="info"></div>
<div id="mdiv">
  <div class="mdiv">
    <div class="md">
    </div>
  </div>
</div>
geocodezip
  • 158,664
  • 13
  • 220
  • 245
0

tested the toggle function code from the working example link below with my code. It removes the markers and then puts them back so it would work perfectly for what I'm trying to do.

working example

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