如何格式化Google Maps API自动填充的输出结果

时间:2017-10-07 15:28:15

标签: 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

1 个答案:

答案 0 :(得分:1)

Your use-case is actually better suited for using the Places Autocomplete feature instead of the Places SearchBox. What you'll do is filter through the selected place's address_components array and only get the likes of route or premise etc, which are what the "address" is made of. Ex:

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

Then simply replace the value of the input field to the combination of your chosen components. inputField.value = addressString;

I recommend to read more about it here:

  • Google sample Be sure to pay attention to the warning in the doc about

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

I also want to mention the code you provided is very incomplete and I tried to create a minimal, verifiable, complete example out of it to show you the basics of how to use the Autocomplete and address components.

Working jsfiddle link: https://jsfiddle.net/yy3p7hh9/1/

Attached code snippet below:

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>