如何一次只显示一种类型的谷歌地图标记

问题描述 投票:-2回答:1

在下面的代码中,我有两个功能,学校和餐馆。我在地图上有两个按钮,点击学校显示学校的标记,并删除餐馆的标记,点击餐厅显示餐馆和学校标记应删除。我在调用places服务之前将标记设置为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);

            }
          }
            //  }

        });
      });

    }
  }
}
google-maps google-maps-api-3 types google-maps-markers markers
1个回答
0
投票

这是因为你在每个函数中声明了var markers = [];数组,这导致数组仅在函数范围内可用(markers中定义的getRestaurants()数组仅在那里可用,并且getSchools()中定义的数组也是如此)。

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

© www.soinside.com 2019 - 2024. All rights reserved.