如何从Google自动填充API的下拉列表中了解点击的地址?

问题描述

我有一个React App,它使用Google Autocomplete API:

  function initAutocomplete() {
    autocomplete = new google.maps.places.Autocomplete(
      document.getElementById("autocomplete"),{ types: ["geocode"] }
    )

    autocomplete.setFields(["address_component","formatted_address","adr_address","name"])
    autocomplete.addListener("place_changed",fillInAddress)
  }

  useEffect(() => {
    initAutocomplete()
  },[])

  function fillInAddress() {
    const place = autocomplete.getPlace()
    setDropOff(place.formatted_address) 
    console.log('fillInAddress place',place)
  }

问题是,当用户单击下拉菜单的选项时,例如:

Calle Viladomat,123,Barcelona,España

此结果出现在输入中。我需要将此结果设置为状态变量,我想从api中获得此点击的值,但我不能。

我到目前为止已经尝试过:

autocomplete.setFields("formatted_address")

但是formatted_address在下面:

Carrer de Viladomat,08015 Barcelona,España

它的格式与用户单击的格式不同。

如何获取输入中当前的值?我可以使用useRef,但我想避免这种情况。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)