-1

I got marker calling marker on a place Search along with grabbing its getDetails on google map v3. Inside of Place Search:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>

      html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px;
        width: 1500px;
        margin-left: auto;
        margin-right: auto;
      }

    </style>
    <title>Places search box</title> 

    <script type='text/javascript' src='sortable/ext/jquery-1.9.1.js'></script>
    <script type="text/javascript" src="sortable/ext/jquery-ui.js"></script>


    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>

    <script>
    var markers = [];

    var map;

    var marker;

function initialize() {

    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    //CAN REVIEW FOR CURRENT LOCATION
    var mapOptions = {
        zoom: 8,
        mapTypeId: 'roadmap'
    };

    var defaultBounds = new google.maps.LatLngBounds(
        new google.maps.LatLng(0, 0));
    map.fitBounds(defaultBounds);

    // Create the search box and link it to the UI element.
    var input = /** @type {HTMLInputElement} */(
        document.getElementById('pac-input'));
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    var searchBox = new google.maps.places.SearchBox(
    /** @type {HTMLInputElement} */(input));

    // [START region_getplaces]
    // Listen for the event fired when the user selects an item from the
    // pick list. Retrieve the matching places for that item.
    google.maps.event.addListener(searchBox, 'places_changed', function() {
        var places = searchBox.getPlaces();

        //Taking input into array
        var item = document.getElementById("pac-input");

    if (places.length == 0) {
        return;
    }

    //for (var i = 0, marker; marker = markers[i]; i++) {
    google.maps.Map.prototype.clearMarkers = function() {
    for (var i = 0; i < this.markers.length; i++) {
        this.markers[i].setMap(null);

        map.setZoom(8);

    }
    this.markers = new Array();
    markers.length = 0;
    }
    // For each place, get the icon, place name, and location.
    markers = [];

    var bounds = new google.maps.LatLngBounds();
    for (var i = 0, place; place = places[i]; i++) {

      // Create a marker for each place.

        var marker = new google.maps.Marker({
            place_id: place.place_id
        });


        //Infowindow
        var infowindow = new google.maps.InfoWindow({
              //content: content
          });

        //Details Services
        var request = {
            placeId: marker.place_id
        };

        service = new google.maps.places.PlacesService(map);

        service.getDetails(request, function(place, status) {
            if (status == google.maps.places.PlacesServiceStatus.OK) {
              var marker = new google.maps.Marker({
                map: map,
                position: place.geometry.location
              });
              google.maps.event.addListener(marker, 'click', function() {

                infowindow.setContent(place.name);

                infowindow.open(map, this);
              });
            }
          });

        markers.push(marker);
        //searchmarkers.push(marker);

        bounds.extend(place.geometry.location);
    }

    map.fitBounds(bounds);
    //map.fitBounds(places[0].geometry.viewport);
    map.setZoom(12);
  });
// [END region_getplaces]
}


google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
        <input id="pac-input" class="controls" type="text" placeholder="Search Box">

    <div id="map-canvas" class="dropit" style="float:left;width:70%;height:100%;"></div>

  </body>
</html>

I didn't copy all the code so it looks a bit distorted. My issue is that everytime I do a place search, it'll work fine. BUT if I do additional place searches.. it'll stack. I can't seem to get rid of the existing markers from getDetails..

I removed markers.push(marker); and it is still somehow adding marker and cannot be removed.

Suggestions?

EDIT:

Updated the code. Please note that getDetails also shows a set of markers, and I cannot remove those. I removed markers thats originally from searchbox... but I needed the place_Id, so I kept it to use on getDetails.

Please help to remove all markers...

EDIT 2:

Thanks geocodezip. Please use the fiddle he created to debug... still can't seem to get it working. http://jsfiddle.net/dw7moor5/

Notice how search two different things, and leftovers will still appear.

MilkACow
  • 67
  • 8
  • Please provide a [Minimal, Complete, Tested and Readable example](http://stackoverflow.com/help/mcve) that demonstrates the issue. The code you have posted looks like it _should_ work, but it depends on how you are using it whether it does or not. – geocodezip Feb 27 '15 at 21:05
  • 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 Feb 27 '15 at 21:06
  • I can remove marker that is generated by placesearch, but I cannot remove markers generated by getDetails – MilkACow Feb 27 '15 at 21:07
  • I updated the code to reflected the whole placesearch I have – MilkACow Feb 27 '15 at 21:12
  • This is not a duplicate of remove all markers.. since that method doesn't work on getDetails.. I don't know why – MilkACow Feb 27 '15 at 21:30
  • Sure it will. You just have to keep references to the markers. (second request) Please provide a [Minimal, Complete, Tested and Readable example](http://stackoverflow.com/help/mcve) that demonstrates the issue. There is no map in the posted code. – geocodezip Feb 27 '15 at 21:31
  • Updated and tested. readable example.. reflecting the issue. Its a cutdown, so may have some leftover comments.. but you can see I was trying to edit the markers reset.. but not working – MilkACow Feb 27 '15 at 21:51
  • So you want to remove the one marker that was created by the last search (or move it to the new location)? [fiddle with the provided code](http://jsfiddle.net/dw7moor5/) – geocodezip Feb 27 '15 at 21:56
  • Let's say I search McDonalds -> It'll bring up McDonalds.. Then I search Taco Bell -> It'll bring up Taco Bell... but it also adds leftover (McDonalds).. I can't seem to have a clear search. On side of that.. Infowindows gets jacked up, since its essentially a new set of markers array... – MilkACow Feb 27 '15 at 21:57

1 Answers1

0

There were syntax errors in your code. Working version in code snippet below. Added the markers and bounds to the map object, you don't have to do that, but you need to be consistent.

var map;

google.maps.Map.prototype.clearMarkers = function() {
  if (this.markers && this.markers.length > 0) {
    for (var i = 0; i < this.markers.length; i++) {
      this.markers[i].setMap(null);

      if (!!map) map.setZoom(8);

    }
  }
  this.markers = [];
  this.markers.length = 0;

}

function initialize() {

  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  //CAN REVIEW FOR CURRENT LOCATION
  var mapOptions = {
    zoom: 8,
    mapTypeId: 'roadmap'
  };

  var defaultBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(0, 0));
  map.fitBounds(defaultBounds);

  // Create the search box and link it to the UI element.
  var input = /** @type {HTMLInputElement} */
    (
      document.getElementById('pac-input'));
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

  var searchBox = new google.maps.places.SearchBox(
    /** @type {HTMLInputElement} */
    (input));

  // [START region_getplaces]
  // Listen for the event fired when the user selects an item from the
  // pick list. Retrieve the matching places for that item.
  google.maps.event.addListener(searchBox, 'places_changed', function() {
    map.clearMarkers();
    var places = searchBox.getPlaces();

    //Taking input into array
    var item = document.getElementById("pac-input");

    if (places.length == 0) {
      return;
    }


    map._bounds = new google.maps.LatLngBounds();
    for (var i = 0, place; place = places[i]; i++) {


      //Infowindow
      var infowindow = new google.maps.InfoWindow({
        //content: content
      });

      //Details Services
      var request = {
        placeId: place.place_id
      };

      service = new google.maps.places.PlacesService(map);

      service.getDetails(request, function(place, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {

          var marker = new google.maps.Marker({
            map: map,
            position: place.geometry.location
          });
          google.maps.event.addListener(marker, 'click', function() {

            infowindow.setContent(place.name);

            infowindow.open(map, this);
          });
          map.markers.push(marker);
          map._bounds.extend(marker.getPosition());
          map.fitBounds(map._bounds);
        }
      });


      //searchmarkers.push(marker);

      map._bounds.extend(place.geometry.location);
    }

    map.fitBounds(map._bounds);
    //map.fitBounds(places[0].geometry.viewport);
    // map.setZoom(12);
  });
  // [END region_getplaces]
}


google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
  height: 100%;
  margin: 0px;
  padding: 0px;
  width: 100%;
  margin-left: auto;
  margin-right: auto;
}
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map-canvas" class="dropit" ></div>
geocodezip
  • 158,664
  • 13
  • 220
  • 245
  • I got another question.. regarding this. Let's say I add 'id: i' to the marker, and attempt to use onclick to delete the marker, but it actually doesn't do it. Since this.id shows the last id of marker. id actually doesn't get added to the associated marker? – MilkACow Feb 27 '15 at 23:01
  • That is another question. this.id should contain the id property of the marker for that click listener (the 'clicked' marker). Hard to say what is going on without a complete example. – geocodezip Feb 27 '15 at 23:05