1

How can I remove the var locations markers after the route is calculated (CalcRoute function)? So only the starting and ending addresses markers are present. Thanks in advance :-)

var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    var locations = [
      ['<strong>Scuola dell\'Infanzia e Primaria</strong><br>Via Asmara 32<br><small>Tel.: 0686219772</small>', 41.926979,12.517385, 3],
      ['<strong>Scuola Primaria Statale</strong><br>Via Novara 22<br><small>Tel./Fax: 068557507</small>', 41.914873,12.506486, 2],
      ['<strong>Scuola Secondaria di I Grado</strong><br>Via Sebenico 1<br><small>Tel./Fax: 068549282</small>', 41.918574,12.507201, 1]
    ];

    var infowindow = new google.maps.InfoWindow();
    var myOptions = {
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        styles: [{
            featureType: "poi.business",
            elementType: "labels",
            stylers: [{
                visibility: "off"
            }]
        }]
    }
    map = new google.maps.Map(document.getElementById("map"),
    myOptions);
    var bounds = new google.maps.LatLngBounds();

    for (i = 0; i < locations.length; i++) {
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map
        });

        bounds.extend(marker.position);

        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                infowindow.setContent(locations[i][0]);
                infowindow.open(map, marker);
            }
        })(marker, i));
    }

    map.fitBounds(bounds);

    var listener = google.maps.event.addListener(map, "idle", function () {
        map.setZoom(15);
        google.maps.event.removeListener(listener);
    });

    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById('directions-panel'));
}

function calcRoute() {
    var start = document.getElementById('start').value;
    var end = document.getElementById('end').value;
    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.DirectionsTravelMode.TRANSIT
    };
    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}

google.maps.event.addDomListener(window, 'load', initialize);
MultiformeIngegno
  • 6,959
  • 15
  • 60
  • 119
  • possible duplicate of [Google Maps API v3: How to remove all markers?](http://stackoverflow.com/questions/1544739/google-maps-api-v3-how-to-remove-all-markers) – geocodezip Apr 30 '13 at 02:22
  • Seems different IMHO. I have also other markers added at some point (which should remain). – MultiformeIngegno Apr 30 '13 at 02:31
  • The principle is the same. You need to keep references to the markers you want to hide, the simplest way to do that is an array. Give them ids or properties to allow you do control which ones stay and which ones get removed (a [categories example of doing that](http://www.geocodezip.com/v3_MW_example_categories.html)) – geocodezip Apr 30 '13 at 02:41

2 Answers2

1

At creation time save your markers in an array, like (adding this in your creation loop):

marker = new google.maps.Marker({
...
});
mkArray.push(marker);  // <------

Then:

var i, j=mkArray.length-1;
// Keeping the first and last one
for(i=1;i<j;i++) {
  mk=mkArray[i];
  mk.setMap(null);
}
dda
  • 6,030
  • 2
  • 25
  • 34
  • Uhm, there isn't a way to call markers of "var locations" and "hide 'em"? Seems a bit dirty this way :) – MultiformeIngegno Apr 30 '13 at 02:30
  • There isn't such a way. Which is why I've built my own little lib that makes such things easier. – dda Apr 30 '13 at 02:32
  • Oh, okay! :) so how should I proceed? Something like mkArray.push(var locations = blah blah ) ? – MultiformeIngegno Apr 30 '13 at 02:35
  • Oh, ok! BTW it should not keep first and last one. The map works like this: initially I have 3 markers. Then I have a function that calculates a route between 2 addresses (not related to the previous markers). After the route is calculated only the route markers should remain (start and end points). – MultiformeIngegno Apr 30 '13 at 02:37
  • Uhm, check this out: http://ffio.it/test2.html The markers are still there... try the map typing "Ostia" in input box. – MultiformeIngegno May 01 '13 at 15:09
  • That's because you're doing it wrong. The markers removal code is inside a function (why?) and inside the initialization code (instead of at the end of calcRoute); The mkArray is not initialized. etc etc... – dda May 01 '13 at 16:13
  • `mkArray.push(marker);` is again in the wrong place -- it should be in the initialize loop. And that line only. You obviously don't understand the concept. I'll try some pseudo-code tomorrow. – dda May 01 '13 at 18:12
  • You're close now though... And you still need to declare a global `mkArray`. – dda May 01 '13 at 18:13
  • Problem is: I tried to put mkArray.push(marker); inside the initialize loop but the map couldn't load anymore... http://ffio.it/test2.html I tried to add var mkArray; to declare the global.. correct? – MultiformeIngegno May 01 '13 at 18:24
  • Because you have to declare mkArray at the top of the code, `var mkArray=[];` – dda May 02 '13 at 03:26
  • Ok, now the map is loaded but markers are still there after route is calculated. – MultiformeIngegno May 02 '13 at 13:41
  • Have you had a chance to look at the page? :) – MultiformeIngegno May 05 '13 at 13:38
  • This code worked: `for (var i = 0, j = mkArray.length - 0; i < j; i++) mkArray[i].setMap(null);` – MultiformeIngegno May 06 '13 at 17:08
0

Replace your calcRoute() function with the below code and then add in var waypts a location of your choice. The stopover:false will remove additional markers automatically.

function calcRoute() 
{

var start = document.getElementById('start').value;

var waypts = [{Location:AddAnyLocationThatIsInYourRoute,stopover:false}];

var end = document.getElementById('end').value;

var request = {

    origin: start,

    destination: end,

    waypoints:waypts,

    travelMode: google.maps.DirectionsTravelMode.TRANSIT
};