【问题标题】:Google maps getPlace().geometry always undefined [duplicate]谷歌地图 getPlace().geometry 总是未定义 [重复]
【发布时间】:2021-04-01 01:17:53
【问题描述】:

我的自动完成功能很好,我已经包含了库几何,

<script defer src="https://maps.googleapis.com/maps/api/js?libraries=places,geometry&key=xxaSyxxxxxxxx9xx&callback=initAutocomplete"></script>

这里是html+js:

<input class="forminput" id="autocomplete" maxlength="30" type=text placeholder="Ex: street.."></input>  

let placeSearch;
let autocomplete;
const componentForm = {
  street_number: "short_name",
  route: "long_name",
  locality: "long_name",
  administrative_area_level_1: "short_name",
  country: "long_name",
  postal_code: "short_name",
};


function initAutocomplete() {

  autocomplete = new google.maps.places.Autocomplete(
    document.getElementById("autocomplete"),
    { types: ["geocode"] }
  );
  //address only
  autocomplete.setFields(["address_component"]);
  //populate
  autocomplete.addListener("place_changed", fillInAddress);
}

当我阅读结果时,places 没有 geometry 属性:

function fillInAddress() {

  const place = autocomplete.getPlace();

  console.log(place); // is good
  console.log(place.geometry); // is undefined all the time

  for (const component of place.address_components) {
  const addressType = component.types[0];
  const val = component[componentForm[addressType]];
   alert(addressType + " " + val);   //  ****** this is good !!!
  }

如何使几何图形工作?我需要纬度/日志。

【问题讨论】:

标签: javascript google-maps google-maps-api-3


【解决方案1】:

对于任何挣扎的人来说,这很简单,

  autocomplete.setFields(["address_component","geometry"]);

由于某种原因,Google 的文档几乎将其隐藏在他们的教程中,但您必须在此处添加 ALSO 以使其正常工作。

这也适用于不包括 geometry 库的情况。

【讨论】:

  • 几何库与与地点一起返回的几何对象无关。
猜你喜欢
  • 2017-05-12
  • 1970-01-01
  • 2018-05-13
  • 2020-09-20
  • 2016-07-25
  • 2023-03-06
  • 1970-01-01
  • 2018-12-15
  • 1970-01-01
相关资源
最近更新 更多