简体   繁体   中英

Google Maps API get location and id using JavaScript

Hi I got this code from Google Maps developer website. In this code it will auto fill the address by using the Google API and will complete the address form. Now I want get 'location' value and 'placeId' from the address. How can I get it?

  <head>
   <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
    <script>
var placeSearch, autocomplete;
var 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 initialize() {
autocomplete = new google.maps.places.Autocomplete(
      (document.getElementById('autocomplete')),
      { types: ['geocode'] });
  google.maps.event.addListener(autocomplete, 'place_changed', function() {
    fillInAddress();
  });
}
function fillInAddress() {
  var place = autocomplete.getPlace();
 for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }
for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;
    } } }
function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = new google.maps.LatLng(
          position.coords.latitude, position.coords.longitude);
var circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}
    </script>


  </head>

  <body onload="initialize()">
    <div id="locationField">
      <input id="autocomplete" placeholder="Enter your address"
             onFocus="geolocate()" type="text"></input>
    </div>

    <table id="address">
      <tr>
        <td class="label">Street address</td>
        <td class="slimField"><input class="field" id="street_number"
              disabled="true"></input></td>
       .......
        <td class="label">Country</td>
        <td class="wideField" colspan="3"><input class="field"
              id="country" disabled="true"></input></td>
      </tr>
    </table>
  </body>
</html>

Look at line 27.

Also look at line 33 and 42: if(document.getElementById(component)) ... Otherwise the script will throw errors if components are missing (You didn't post the all; I presume you have all components, but it's still a good idea).

<html>
  <head>
   <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
    <script>
      var placeSearch, autocomplete;
      var 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 initialize() {
        autocomplete = new google.maps.places.Autocomplete(
          document.getElementById('autocomplete'),
          { types: ['geocode']}
        );
        google.maps.event.addListener(autocomplete, 'place_changed', function() {
          fillInAddress();
        });
      }
      function fillInAddress() {
        var place = autocomplete.getPlace();

        // location & place_id
        var location = place.geometry.location;
        var place_id = place.place_id;
        document.getElementById('log').innerHTML += 'location: ' + location.lat() + ',' + location.lng() + ' - place ID: ' + place_id + '<br>';

        for (var component in componentForm) {
          if(document.getElementById(component)) {
            document.getElementById(component).value = '';
            document.getElementById(component).disabled = false;
          }
        }
        for (var i = 0; i < place.address_components.length; i++) {
          var addressType = place.address_components[i].types[0];
          if (componentForm[addressType]) {
            var val = place.address_components[i][componentForm[addressType]];
            if(document.getElementById(addressType)) {
              document.getElementById(addressType).value = val;
            }
          }
        }
      }
      function geolocate() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var geolocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            var circle = new google.maps.Circle({
              center: geolocation,
              radius: position.coords.accuracy
            });
            autocomplete.setBounds(circle.getBounds());
          });
        }
      }
    </script>
  </head>
  <body onload="initialize()">
    <div id="locationField">
      <input id="autocomplete" placeholder="Enter your address" onFocus="geolocate()" type="text"></input>
    </div>
    <table id="address">
      <tr>
        <td class="label">Street address</td>
        <td class="slimField"><input class="field" id="street_number" disabled="true"></input></td>
        <td class="label">Country</td>
        <td class="wideField" colspan="3"><input class="field" id="country" disabled="true"></input></td>
      </tr>
    </table>
    <div id="log"></div>
  </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM