谷歌地图,无法清除/隐藏标记

时间:2017-04-08 15:48:46

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

我一直有尝试在地图上隐藏/清除标记的问题。我看了谷歌的文档,我有正确的代码,我也在这里看了几个答案,但似乎没有什么似乎对我有用,我添加了一个清晰的地图按钮,并创建了一个功能,但这没有工作。

另外,我已经尝试添加地理定位方面,但这根本不起作用,但是当我使用代码google的api已经让它工作时,当我用我的代码实现它时

我不知道我是否将代码放在错误的地方或者什么不是,任何帮助都将不胜感激。

 var map;
  var infoWindow;
  var service;


  function initMap() {

      map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 51.545213, lng: -0.0307699},
          zoom: 15,
          styles: [{
              stylers: [{visibility: 'simplified'}]
          }, {
              elementType: 'labels',
              stylers: [{visibility: 'on'}]
          }]
      });

      var input = /** @type {!HTMLInputElement} */(
              document.getElementById('pac-input'));

      var types = document.getElementById('type-selector');
      map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
      map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);

      var autocomplete = new google.maps.places.Autocomplete(input);
      autocomplete.bindTo('bounds', map);

      var infowindow = new google.maps.InfoWindow();
      var marker = new google.maps.Marker({
          map: map,
          anchorPoint: new google.maps.Point(0, -29)
      });

   autocomplete.addListener('place_changed', function() {
      infowindow.close();
      marker.setVisible(false);
      var place = autocomplete.getPlace();
      if (!place.geometry) {
        // User entered the name of a Place that was not suggested and
        // pressed the Enter key, or the Place Details request failed.
        window.alert("No details available for input: '" + place.name + "'");
        return;
      }

      // If the place has a geometry, then present it on a map.
      if (place.geometry.viewport) {
        map.fitBounds(place.geometry.viewport);
      } else {
        map.setCenter(place.geometry.location);
        map.setZoom(17);  // Why 17? Because it looks good.
      }
      marker.setIcon(/** @type {google.maps.Icon} */({
        url: place.icon,
        size: new google.maps.Size(71, 71),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(17, 34),
        scaledSize: new google.maps.Size(35, 35)
      }));
      marker.setPosition(place.geometry.location);
      marker.setVisible(true);

      var address = '';
      if (place.address_components) {
        address = [
          (place.address_components[0] && place.address_components[0].short_name || ''),
          (place.address_components[1] && place.address_components[1].short_name || ''),
          (place.address_components[2] && place.address_components[2].short_name || '')
        ].join(' ');
      }

      infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
      infowindow.open(map, marker);
    });
    // Sets a listener on a radio button to change the filter type on Places
    // Autocomplete.
    function setupClickListener(id, types) {
      var radioButton = document.getElementById(id);
      radioButton.addEventListener('click', function() {
        autocomplete.setTypes(types);
      });
    }

    setupClickListener('changetype-all', []);
    setupClickListener('changetype-address', ['address']);
    setupClickListener('changetype-establishment', ['establishment']);
    setupClickListener('changetype-geocode', ['geocode']);

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

    // The idle event is a debounced event, so we can query & listen without
    // throwing too many requests at the server.
    map.addListener('idle', performSearch(places));
  }



  function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
                          'Error: The Geolocation service failed.' :
                          'Error: Your browser doesn\'t support geolocation.');
  }

  function performSearch(places) {

      var places = places;
    var request = {
      bounds: map.getBounds(),
      keyword: places
    };
    service.radarSearch(request, callback);

  }

  function callback(results, status) {
    if (status !== google.maps.places.PlacesServiceStatus.OK) {
      console.error(status);
      return;
    }
    for (var i = 0, result; result = results[i]; i++) {
      addMarker(result);
    }
  }
  function addMarker(place) {
    var marker = new google.maps.Marker({
      map: map,
      position: place.geometry.location,
     // icon: {
       // url: 'https://developers.google.com/maps/documentation/javascript/images/circle.png',
        //anchor: new google.maps.Point(10, 10),
        //scaledSize: new google.maps.Size(10, 17)
      //}

    });


    google.maps.event.addListener(marker, 'click', function() {
      service.getDetails(place, function(result, status) {
        if (status !== google.maps.places.PlacesServiceStatus.OK) {
          console.error(status);
          return;
        }
        infoWindow.setContent(result.name);
        infoWindow.open(map, marker);
      });
    });
  }
  function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
    center: { lat: -33.8688, lng: 151.2195 },
    zoom: 13,
    mapTypeId: 'roadmap'
});

// Create the search box and link it to the UI element.
var searchInput = document.getElementById('pac-input');
var searchBtn = document.getElementById('search-button');
var searchBox = new google.maps.places.SearchBox(searchInput);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(searchInput);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(searchBtn);

// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function () {
    searchBox.setBounds(map.getBounds());
});

var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function () {
    //displaySearchResults(map, searchBox, markers);
});


searchBtn.onclick = function () {
    displaySearchResults(map,searchBox,markers);
}
}






function displaySearchResults(map, searchBox, markers) {
var places = searchBox.getPlaces();

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

// Clear out the old markers.


// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function (place) {
    if (!place.geometry) {
        console.log("Returned place contains no geometry");
        return;
    }
    var icon = {
        url: place.icon,
        size: new google.maps.Size(71, 71),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(17, 34),
        scaledSize: new google.maps.Size(25, 25)
    };

    // Create a marker for each place.
    markers.push(new google.maps.Marker({
        map: map,
        icon: icon,
        title: place.name,
        position: place.geometry.location

    }));
    function clearMarkers() {
        for (var i = 0; i < markers.length; i++) {
            markers[i].setMap(map);
        }
    }
    if (place.geometry.viewport) {
        // Only geocodes have viewport.
        bounds.union(place.geometry.viewport);
    } else {
        bounds.extend(place.geometry.location);
    }
});
map.fitBounds(bounds);
}

2 个答案:

答案 0 :(得分:0)

没有大的测试:

在“function clearMarkers()”中,您必须使用:

  

标记物[I] .setMap(空);

代替markers [i] .setMap(map);这将再次设置标记

答案 1 :(得分:0)

其他:

宣告:

var marker;
var markers[];

作为代码顶部的全局。函数内部仅使用“marker ..”,而不是“var marker”。如果您之后要删除的标记已通过“marker = new google.maps.Marker({...”将其随后推入带有markers.push(marker)的markers数组中进行定义。

同样在“//为每个地方创建标记”部分。我会使用标准的方式进行定义和存储:

marker = new google.maps.Marker({
       ...});
markers.push(marker).