如何一次仅显示一种类型的Google地图标记

时间:2019-02-28 11:38:18

标签: google-maps google-maps-api-3 types google-maps-markers markers

在下面的代码中,我有两个功能,学校和餐厅。我在地图上有两个按钮,单击“学校”将显示学校的标记,并删除餐厅的标记,而在单击“餐厅”的显示会显示餐厅和学校的标记,则应删除。我在致电场所服务之前将标记设置为null,但仍然无法正常工作。非常感谢您的帮助。

export class MortmapComponent implements OnInit {
  @ViewChild('map') mapElement: ElementRef;
  getlocation: { origin: { latitude: any; longitude: any; }; };
  srcOriginLatitude: any;
  srcOriginLongitude: any;
  mapArrayList: any = [];
  zoom: number;
  markers : any = [];

  constructor(private zone: NgZone, private mapsAPILoader: MapsAPILoader) {

    mapsAPILoader.load().then(() => {
      this.initMap();
    }, (error) => {
      console.log(error);
    });
  }

  ngOnInit() {
    let originLat, originLng;
    if ('geolocation' in navigator) {
      navigator.geolocation.getCurrentPosition((position) => {
        originLat = position.coords.latitude;
        originLng = position.coords.longitude;
        this.getlocation = {
          origin: { latitude: originLat, longitude: originLng }
        };
        this.srcOriginLatitude = this.getlocation.origin.latitude;
        this.srcOriginLongitude = this.getlocation.origin.longitude;
      });
    }
    this.zoom = 14;
  }


  initMap() {

    var myLatLng = { lat: parseFloat(this.srcOriginLatitude), lng: parseFloat(this.srcOriginLongitude) };
    var myStyles = [
      {
        featureType: "poi",
        elementType: "labels",
        stylers: [
          { visibility: "off" }
        ]
      }
    ];
    map = new google.maps.Map(this.mapElement.nativeElement, {
      center: myLatLng,
      zoom: 15,
      gestureHandling: 'none',
      styles: myStyles,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
    });

    // Create a div to hold the control.
    var controlDiv = document.createElement('div');

    //### Add a button on Google Maps ...
    var controlMarkerUI = document.createElement('div');
    controlMarkerUI.style.cursor = 'pointer';
    controlMarkerUI.style.backgroundColor = 'blue';
    controlMarkerUI.style.height = '28px';
    controlMarkerUI.style.width = '25px';
    controlMarkerUI.style.marginLeft = '10px';
    controlMarkerUI.style.marginTop = '10px';
    controlMarkerUI.title = 'Click to set the map to Home';
    // controlMarkerUI.id = "schoolsTag";
    controlDiv.appendChild(controlMarkerUI);
    controlMarkerUI.addEventListener('click', this.getRestaurantList);


    //### Add a button on Google Maps ...
    var controlTrashUI = document.createElement('div');
    controlTrashUI.style.cursor = 'pointer';
    controlTrashUI.style.backgroundColor = 'black';
    controlTrashUI.style.height = '28px';
    controlTrashUI.style.width = '25px';
    controlTrashUI.style.marginLeft = '60px';
    controlTrashUI.title = 'Click to set the map to Home';
    controlTrashUI.id = "mosqueTag";
    controlDiv.appendChild(controlTrashUI);

    controlTrashUI.addEventListener('click', this.getSchoolsList);
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(controlDiv);
  }

  getRestaurantList() {
  //   var markers = [];
    let service = new google.maps.places.PlacesService(map);
    let originLat, originLng;

    if ('geolocation' in navigator) {
      navigator.geolocation.getCurrentPosition((position) => {
        originLat = position.coords.latitude;
        originLng = position.coords.longitude;
        this.getlocation = {
          origin: { latitude: originLat, longitude: originLng }
        };
        this.srcOriginLatitude = this.getlocation.origin.latitude;
        this.srcOriginLongitude = this.getlocation.origin.longitude;
        service.nearbySearch({
          location: { lat: this.srcOriginLatitude, lng: this.srcOriginLongitude },
          radius: 10000,
          type: ['restaurant']
        }, (results, status) => {
          if (status === google.maps.places.PlacesServiceStatus.OK) {

               for (var i = 0; i < this.markers.length; i++) {
                this.markers[i].setMap(null);

              }

              // markers = [];

              for (var i = 0; i < results.length; i++) {
                var place = results[i];
                console.log(" Places ", place);
                var placeLoc = place.geometry.location;
                var marker = new google.maps.Marker({
                  map: map,
                  position: place.geometry.location,
                  icon: './assets/images/marker_inactive.png',
                });
                marker.setMap(map);
                this.markers.push(marker);

              }

            }
          });
      });


    }
  }

  getSchoolsList() {
    //  var markers = [];
    let service = new google.maps.places.PlacesService(map);
    let originLat, originLng;
    if ('geolocation' in navigator) {
      navigator.geolocation.getCurrentPosition((position) => {
        originLat = position.coords.latitude;
        originLng = position.coords.longitude;
        this.getlocation = {
          origin: { latitude: originLat, longitude: originLng }
        };
        this.srcOriginLatitude = this.getlocation.origin.latitude;
        this.srcOriginLongitude = this.getlocation.origin.longitude;
        service.nearbySearch({
          location: { lat: this.srcOriginLatitude, lng: this.srcOriginLongitude },
          radius: 10000,
          type: ['school']
        }, (results, status) => {
          if (status === google.maps.places.PlacesServiceStatus.OK) {

               for (var i = 0; i < this.markers.length; i++) {
                 this.markers[i].setMap(null);

               }

           //    this.markers = [];


            for (var i = 0; i < results.length; i++) {
              var place = results[i];
              console.log(" Places... ", place);
              var placeLoc = place.geometry.location;
              var marker = new google.maps.Marker({
                map: map,
                position: place.geometry.location,
                icon: './assets/images/marker_active.png',
              });
              marker.setMap(map);


             this.markers.push(marker);

            }
          }
            //  }

        });
      });

    }
  }
}

1 个答案:

答案 0 :(得分:0)

这是因为您在每个函数中声明了var markers = [];数组,这导致该数组仅在函数作用域中可用(markers中定义的getRestaurants()数组仅在此处可用,并且getSchools()中定义的数组也是如此。

全局范围中定义var markers = [];(并删除2个函数中的声明)。这样,变量将在两个函数中均可用,并且您的代码应运行良好。