【问题标题】:use global variable inside on google.maps.Geocoder().geocode() in typescript/javascript在 typescript/javascript 的 google.maps.Geocoder().geocode() 上使用全局变量
【发布时间】:2020-08-16 08:08:07
【问题描述】:

我想在 google.maps.Geocoder().geocode() 中访问和修改我的全局变量,看起来我无法在其中修改以在函数中返回它 全局变量

  public address: any;

这是我的功能

getCoordsCityName(latlng): any {

new google.maps.Geocoder().geocode({ 'latLng': latlng }, function (results, status) {

  if (status == google.maps.GeocoderStatus.OK) {

    if (results[1]) {
      let country = null, countryCode = null, city = null, cityAlt = null, administrativArea = null;
      let c, lc, component;

      for (let r = 0, rl = results.length; r < rl; r += 1) {
        let result = results[r];
        if (!city && result.types[0] === 'locality') {
          for (c = 0, lc = result.address_components.length; c < lc; c += 1) {
            component = result.address_components[c];
            if (component.types[0] === 'locality') {
              city = component.long_name;
              break;
            }
          }
        } else if (!city && !cityAlt && result.types[0] === 'administrative_area_level_1') {
          for (c = 0, lc = result.address_components.length; c < lc; c += 1) {
            component = result.address_components[c];
            if (component.types[0] === 'administrative_area_level_1') {
              cityAlt = component.long_name;
              break;
            }
          }
        } else if (!country && result.types[0] === 'country') {
          country = result.address_components[0].long_name;
          administrativArea = result.address_components[0].administrative_area_level_1;
          countryCode = result.address_components[0].short_name;
        }
        if (city && country) {
          break;
        }
      }

      this.address = 'Location: ' + country + ', ' + city + ', ' + countryCode;
      console.log('ADDRESS Details: ' + this.address);

    }
  }
});
return this.address;

}

它已经在 console.log 上显示了位置,但我不能在页面上使用它

【问题讨论】:

    标签: javascript typescript google-maps ionic-framework geolocation


    【解决方案1】:

    Arrow Functions

    new google.maps.Geocoder().geocode({ 'latLng': latlng }, function (results, status) {})
    

    改成

    new google.maps.Geocoder().geocode({ 'latLng': latlng }, (results, status) => {})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      • 2020-02-10
      • 2017-07-25
      相关资源
      最近更新 更多