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

时间:2018-11-05 02:09:19

标签: javascript jquery google-maps

我尝试了以下

  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”

1 个答案:

答案 0 :(得分:2)

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

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

以下是地理编码响应