javascript - 如何格式化 Google Maps API 自动完成的输出结果

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

您好,我正在尝试更改输出结果,例如社区、城市和国家。我的意图是,当用户输入他的地址时,他只返回街道。

我要删除的数据示例。 enter image description here

这是我的 Google Maps API 脚本。

 <script>
    function initAutocomplete() {
      var map = new google.maps.Map(document.getElementById('map'), {
        center: {
          lat: -23.69389,
          lng: -46.565
        },
        zoom: 7,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });

      var marker = new google.maps.Marker({
        position: {
          lat: 34.3630003,
          lng: -84.332207
        },
        map: map,
        animation: google.maps.Animation.DROP,
        draggable: true
      });

      var searchBox = new google.maps.places.SearchBox(document.getElementById('pac-input'));

      google.maps.event.addListener(searchBox, 'places_changed', function () {
        var places = searchBox.getPlaces();
        var bounds = new google.maps.LatLngBounds();
        var i, place;

        for (i = 0; place = places[i]; i++) {
          bounds.extend(place.geometry.location);
          marker.setPosition(place.geometry.location);
        }

        map.fitBounds(bounds);
        map.setZoom(14);
      });
    }

    var map = document.getElementById("map");
    google.maps.event.trigger(map, 'resize');

    google.maps.event.addDomListener(window, 'load', initAutocomplete);
  </script>

这是我的搜索框。

    <div class="input-field col s6">
      <i class="material-icons prefix">home</i>
      <input placeholder="Defina um endereço para seu fornecedor" id="pac-input" name="addressRouteTransporter" type="text" class="validate">
      <label for="addressRouteTransporter">Endereço:</label>
    </div>

谢谢你的帮助xD

最佳答案

您的用例实际上更适合使用地点自动完成功能,而不是地点搜索框。您要做的就是过滤所选地点的 address_components 数组,并仅获取 routepremise 等内容,这些是“地址”是由. 例如:

componentForm = {
  street_number: 'short_name',
  route: 'long_name',
  sublocality_level_1: 'long_name',
  premise: 'long_name'
};

然后只需将输入字段的值替换为您选择的组件的组合即可。 inputField.value = addressString;

我建议在这里阅读更多相关内容:

"You may need to select different components to align with the postal address formats of different countries."

我还想提一下,您提供的代码非常不完整,我尝试创建一个最小的、可验证的、完整的示例,以向您展示如何使用自动完成和地址组件的基础知识。

工作 jsfiddle 链接:https://jsfiddle.net/yy3p7hh9/1/

下面附有代码片段:

var autocomplete, 
marker, 
map,
inputField = document.getElementById('pac-input'),
// this is the type of address components you would like to get. You will filter through this object and
// check if the place result has any 1 of these address components. 
// Notice how type 'locality' will not be retrieved so big, general places without these properties will not
// show
componentForm = {
  street_number: 'short_name',
  route: 'long_name',
  sublocality_level_1: 'long_name',
  premise: 'long_name'
};

function initAutocomplete() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: -23.69389,
      lng: -46.565
    },
    zoom: 7,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  marker = new google.maps.Marker({
    position: {
      lat: 34.3630003,
      lng: -84.332207
    },
    map: map,
    animation: google.maps.Animation.DROP,
    draggable: true
  });

  // Create the autocomplete object, restricting the search to geographical
  // location types.
  autocomplete = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */
    (inputField), {
      types: ['geocode']
    });

  // When the user selects an address from the dropdown, populate the address
  // fields in the form.
  autocomplete.addListener('place_changed', fillInAddress);
}

function fillInAddress() {
  var place = autocomplete.getPlace();
  var bounds = new google.maps.LatLngBounds();
  var addressString = '';

  if (place.geometry) {
    bounds.extend(place.geometry.location);
    marker.setPosition(place.geometry.location);
  }

  // Get each component of the address from the place details
  // and fill the corresponding field on the form.
  for (var i = 0; i < place.address_components.length; i++) {
  // warning this only gets the first type of the component. E.g. 'sublocality_level_1'
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {
      var val = place.address_components[i][componentForm[addressType]];
      addressString += ' ' + val + ',';
    }
  }
  // just remove the last comma
  addressString = addressString.replace(/,\s*$/, "");
  inputField.value = addressString;
  console.log(addressString);
  map.fitBounds(bounds);
  map.setZoom(14);
}
#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div class="input-field col s6">
  <i class="material-icons prefix">home</i>
  <input placeholder="Defina um endereço para seu fornecedor" id="pac-input" name="addressRouteTransporter" type="text" class="validate">
  <label for="addressRouteTransporter">Endereço:</label>
</div>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCD0rWgXRVBa7PgaTWXVp_gU51pgHGviYY&libraries=places&callback=initAutocomplete" async defer></script>

关于javascript - 如何格式化 Google Maps API 自动完成的输出结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46621928/

相关文章:

javascript - 如何将jQuery中的输入类型传递给ajax

jQuery:如何知道表格行何时失去焦点?

jquery - 使用 jquery gmap3 和 autoFit 设置最大缩放级别

google-maps - 谷歌地图折线和标记在一起

android自定义 map 标记边界

javascript - 如何在生成动态html时在Jquery Clone中设置值

javascript - 如何使用 javascript 获取 firebase 3 的 accessToken

javascript - 如何将变量设为私有(private)?

javascript - 创建具有设置约束的网格

jquery - jqGrid - 根据日期值有条件地格式化单元格