简体   繁体   中英

Angular - Can't access other functions or variables

I've been at this a while and I've looked up Angular scope but I still seem to be struggling with it in some regard. Basically, I am setting up a google maps object on screen. Adding markers and stuff needs to be done through this setup function at the minute which is okay for now, but when I get directions to a marker I want to call my showLocationInfo() method. No amount of this.showLocationInfo() or any other attempt to reference the showLocationDetails boolean are working and I can't seem to find out where I'm going wrong.

import {Geolocation} from "@ionic-native/geolocation/ngx";
import {error} from "util";
let directionsService = new google.maps.DirectionsService();
let directionsRenderer = new google.maps.DirectionsRenderer({suppressMarkers: true});
let selectedMarker;

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
  map;
  @ViewChild('mapElement', {static: true}) mapElement;

  globalScope: any = this;
  latitude: any;
  longitude: any;
  showLocationDetails: boolean = false;

  constructor(private geolocation: Geolocation) {}

  ngOnInit(): void {}

  ngAfterViewInit(): void {
      this.setupMap();
  }

  setupMap(): void {
      this.geolocation.getCurrentPosition().then((resp) => {
          this.latitude = resp.coords.latitude;
          this.longitude = resp.coords.longitude;
          // This is creating our default map if there is no geolocation
          const map = new google.maps.Map(
              this.mapElement.nativeElement,
              {
                  center: {
                      lat: 53.418813,
                      lng: -7.903869
                  },
                  zoom: 15,
                  disableDefaultUI: true,
                  streetViewControl: true,
                  zoomControl: true
              });
          directionsRenderer.setMap(this.map);
          // This is creating our info window and setting the location to our geolocation
          const infoWindow = new google.maps.InfoWindow();
          const pos = {
                  lat: this.latitude,
                  lng: this.longitude
              };
          infoWindow.setPosition(pos);
          infoWindow.setContent('Location found.');
          infoWindow.open(map);
          map.setCenter(pos);

          // This recognises the user's click and places a marker at that location
          map.addListener('click', function(e) {
              let marker = new google.maps.Marker({
                  position: e.latLng,
                  animation: google.maps.Animation.DROP,
                  map: map
              });
              // This adds clickable events to each of the placed markers
                      marker.addListener('click', function(e) {
                          selectedMarker = marker;
                          map.setCenter(marker.getPosition());
                          map.panTo(e.latLng);
                          let request : google.maps.DirectionsRequest = {
                              origin : pos,
                              destination : e.latLng,
                              travelMode: google.maps.TravelMode.WALKING
                          };
                          directionsService.route(request, function(result, status) {
                              if (status == 'OK') {
                                  directionsRenderer.setDirections(result);
                                  directionsRenderer.setOptions({
                                       suppressPolylines: false
                                  });
                                  directionsRenderer.setMap(map);
                                  this.showLocationInfo();
                              }
                          });
                      });
          });

      }).catch((error) => {
          console.log('Error getting location', error);

          this.map = new google.maps.Map(
              this.mapElement.nativeElement,
              {
                  center: {
                      lat: 53.418813,
                      lng: -7.903869
                  },
                  zoom: 15,
                  disableDefaultUI: true,
                  streetViewControl: true,
                  zoomControl: true,
                  rotateControl: true
              });
      });
  }

  showLocationInfo(): void {
      this.showLocationDetails = true;
  }

  hideLocationInfo(): void {
      this.showLocationDetails = false;
  }
}```

You have to use arrow function for addListener to refer correct this context

Try this:

 // This recognises the user's click and places a marker at that location
          map.addListener('click', (e)=> {
              let marker = new google.maps.Marker({
                  position: e.latLng,
                  animation: google.maps.Animation.DROP,
                  map: map
              });
              // This adds clickable events to each of the placed markers
                      marker.addListener('click', function(e) {
                          selectedMarker = marker;
                          map.setCenter(marker.getPosition());
                          map.panTo(e.latLng);
                          let request : google.maps.DirectionsRequest = {
                              origin : pos,
                              destination : e.latLng,
                              travelMode: google.maps.TravelMode.WALKING
                          };
                          directionsService.route(request, function(result, status) {
                              if (status == 'OK') {
                                  directionsRenderer.setDirections(result);
                                  directionsRenderer.setOptions({
                                       suppressPolylines: false
                                  });
                                  directionsRenderer.setMap(map);
                                  this.showLocationInfo();
                              }
                          });
                      });
          });

      }).catch((error) => {
          console.log('Error getting location', error);

          this.map = new google.maps.Map(
              this.mapElement.nativeElement,
              {
                  center: {
                      lat: 53.418813,
                      lng: -7.903869
                  },
                  zoom: 15,
                  disableDefaultUI: true,
                  streetViewControl: true,
                  zoomControl: true,
                  rotateControl: true
              });
      });

When using this to reference outside the scope of the function, you need to use arrow functions.

marker.addListener('click', (e) => {
  selectedMarker = marker;
  map.setCenter(marker.getPosition());
  map.panTo(e.latLng);
  let request : google.maps.DirectionsRequest = {
      origin : pos,
      destination : e.latLng,
      travelMode: google.maps.TravelMode.WALKING
  };
  directionsService.route(request, (result, status) => {
      if (status == 'OK') {
          directionsRenderer.setDirections(result);
          directionsRenderer.setOptions({
               suppressPolylines: false
          });
          directionsRenderer.setMap(map);
          this.showLocationInfo();
      }
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM