如何从自动完成和Dragend中获取国家名称

如何从自动完成和Dragend中获取国家名称

我尝试了以下

  google.maps.event.addListener(marker, 'dragend', function(marker) {
    var latLng = marker.latLng;
    currentLatitude = latLng.lat();
    currentLongitude = latLng.lng();
    var latlng = {
      lat: currentLatitude,
      lng: currentLongitude
    };
    var geocoder = new google.maps.Geocoder;
    geocoder.geocode({
      'location': latlng
    }, function(results, status) {
      if (status === 'OK') {
        if (results[0]) {
          input.value = results[0].formatted_address;
          var arrAddress = results[0].address_components;
          $.each(arrAddress, function (i, address_component) {
            if(arrAddress.types.includes('country')) {
              console.log(address_component.long_name);
            }
          });
        } else {
          window.alert('No results found');
        }
      } else {
        window.alert('Geocoder failed due to: ' + status);
      }
    });
  });

  autocomplete.addListener('place_changed', function() {
    var place = autocomplete.getPlace();
    if (!place.geometry) {
      return;
    }
    if (place.geometry.viewport) {
      map.fitBounds(place.geometry.viewport);
    } else {
      map.setCenter(place.geometry.location);
    }
    marker.setPosition(place.geometry.location);
    currentLatitude = place.geometry.location.lat();
    currentLongitude = place.geometry.location.lng();
    var arrAddress = place.address_components;
    $.each(arrAddress, function (i, address_component) {
      if(arrAddress.types.includes('country')) {
        console.log(address_component.long_name);
      }
    });
  });
};


但是我明白了


  未捕获的TypeError:无法读取未定义的属性“ includes”

最佳答案

可以使用过滤器代替$.each

results[0].address_components.filter(x => x.types.includes("country"))[0].long_name


这是Geoccoding响应javascript - 如何从自动完成和Dragend中获取国家名称?-LMLPHP

关于javascript - 如何从自动完成和Dragend中获取国家名称?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53147437/

10-12 14:05