используйте глобальную переменную внутри в google.maps.Geocoder (). geocode () в typcript / javascript - PullRequest
0 голосов
/ 01 мая 2020

Я хотел бы получить доступ и изменить мою глобальную переменную внутри 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, но я не могу использовать его на странице

1 Ответ

0 голосов
/ 02 мая 2020

См. Функции стрелок

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

изменить на

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