为什么我无法保留谷歌地图返回的地址



我能够从google map那里获得address,但无法将address保留在我的page

这是我的代码:

  title:string;
  informationWindowTitle:string;
  address:string;        
  @ViewChild('map') mapElement: ElementRef;
  map: any;
  geocodeLatLng(lat, lng) {
    var geocoder = new google.maps.Geocoder;

         var latlng = {
            lat: lat,
            lng: lng
          };
          geocoder.geocode({
            'location': latlng
          }, function(results, status) {
            if (status === 'OK') { 
              if (results[0]) {
                //This is yout formatted address
                //window.alert(results[0].formatted_address);
                console.log(results[0].formatted_address);
                this.title = results[0].formatted_address;
                this.informationWindowTitle = results[0].formatted_address;  
                console.log(this.informationWindowTitle); 
                return  results[0].formatted_address;        
              } else {
                window.alert('No results found');
              }
            } else {
              window.alert('Geocoder failed due to: ' + status);
            }
          });

        }
  loadMap(){

    this.geolocation.getCurrentPosition().then((position) => {
      let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);


      let mapOptions = {
        center: latLng,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
     this.geocodeLatLng(position.coords.latitude,position.coords.longitude); 
     //  console.log(this.address);    
     this.addMarker(); 
     // this.title = this.address;//results[0].formatted_address;
     // this.informationWindowTitle = this.address;//results[0].formatted_address;        
    }, (err) => {
      console.log(err);    
    });
  }
 addInfoWindow(marker, content){
  let infoWindow = new google.maps.InfoWindow({
    content: content
  });
  google.maps.event.addListener(marker, 'click', () => {
    infoWindow.open(this.map, marker);
  });
}
 addMarker(){     
          let marker = new google.maps.Marker({
            map: this.map,
            animation: google.maps.Animation.DROP,
            position: this.map.getCenter()
          });
          let content = '<h4>Your Current Location!</h4><p>'+this.address+'</p>';                     
          this.addInfoWindow(marker, content);                                               
  }

我想做的是摘录

  geocodeLatLng(lat, lng) {
       // this function returns address
    }

初始化 1. 加载地图() 2. 地理编码LatLng()

      loadMap(){

        this.geolocation.getCurrentPosition().then((position) => {
         this.geocodeLatLng(position.coords.latitude,position.coords.longitude); // sending co-ordinates to above function which returns the address 

         this.addMarker();  // then adding marker

        }, (err) => {
          console.log(err);    
        });
      }

please refer this for getting地址:如何使用谷歌地图API获取当前职位名称

当我分配这些属性时,我没有获得它的值

        this.title = results[0].formatted_address;
        this.informationWindowTitle = results[0].formatted_address; 

问为什么?但我能够进入function geocodeLatLng()

你的问题是function(results, status) {...}里面的this.title不是你声明的title

你必须做的是使用箭头函数

this.geocoder.geocode({
  'location': latlng
}, (results, status) => {
  if (status === 'OK') {
    if (results[0]) {
      //This is yout formatted address
      //window.alert(results[0].formatted_address);
      console.log('result[0]', results[0].formatted_address);
      this.title = results[0].formatted_address;
      this.informationWindowTitle = results[0].formatted_address;
      console.log(this.informationWindowTitle); 
      // add this to force Angular detect Changes
      this.changeDetectorRef.detectChanges();
      return results[0].formatted_address;
    } else {
      window.alert('No results found');
    }
  } else {
    window.alert('Geocoder failed due to: ' + status);
  }
});

当我测试你的代码时,Angular 不会检测到标题何时更新,所以我必须强制 Angular 这样做。这是使用 ChangeDetectorRef 的方法。

Import { ChangeDetectorRef } from '@angular/core';
constructor(..,public changeDetectorRef: ChangeDetectorRef){..}

希望这能有所帮助!

尝试添加回调并使用箭头函数来保留以下内容:

geocoder.geocode({'location': latlng}, (results, status) => {
 if (results[0]) {
   this.doSomething(results[0].formatted_address);
 } 
 else {
   window.alert('No results found');
 }...

和回调函数:

doSomething(formatted_address){
  this.title = formatted_address;
  this.informationWindowTitle = formatted_address;  
}

最新更新