【问题标题】:How can i get Autocomplete Address from drag event in Google Maps API?如何从 Google Maps API 中的拖动事件中获取自动完成地址?
【发布时间】:2018-05-28 11:14:51
【问题描述】:

我创建了一个 Google Geocoder ,我希望能够在拖动或单击标记时获取标记的自动完成地址。

这里的问题是在搜索地址时没有问题,它显示确切的位置并提供自动完整地址,如街道地址、城市、州、邮政编码、国家等。

问题是,将 pin 点从一个位置拖动到另一个位置时,整个地址会根据 google pin 位置发生变化,但它没有给出地址子部分,例如街道地址、城市、州、邮政编码、国家(不更新意味着旧搜索值只有在那里)

我的代码:

<head>
<title>Place Autocomplete Address Form</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
<style>
  /* Always set the map height explicitly to define the size of the div
   * element that contains the map. */
  #map {
    height: 100%;
  }
  /* Optional: Makes the sample page fill the window. */
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
  #locationField, #controls {
    position: relative;
    width: 480px;
  }
  #autocomplete {
    position: absolute;
    top: 0px;
    left: 0px;
    width: 99%;
  }
  .label {
    text-align: right;
    font-weight: bold;
    width: 100px;
    color: #303030;
  }
  #address {
    border: 1px solid #000090;
    background-color: #f0f0ff;
    width: 480px;
    padding-right: 2px;
  }
  #address td {
    font-size: 10pt;
  }
  .field {
    width: 99%;
  }
  .slimField {
    width: 80px;
  }
  .wideField {
    width: 200px;
  }
  #locationField {
    height: 20px;
    margin-bottom: 2px;
  }
</style>

   <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA1BvEkX8v91LRu43HQe0-GNaHTVnoTSQs&libraries=places&callback=initMap"
    async defer></script>
</head>

<body>
  <br><br>   
 <div id="locationField">
  <input id="autocomplete" placeholder="Enter your address" 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" name="streetnumber"></input></td>
    <td class="wideField" colspan="2"><input class="field" id="route"
          disabled="true" name="route"></input></td>
  </tr>
  <tr>
    <td class="label">City</td>
    <!-- Note: Selection of address components in this example is typical.
         You may need to adjust it for the locations relevant to your app. See
         https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
    -->
    <td class="wideField" colspan="3"><input class="field" id="locality"
          disabled="true" name="locality"></input></td>
  </tr>
  <tr>
    <td class="label">State</td>
    <td class="slimField"><input class="field"
          id="administrative_area_level_1" disabled="true"  name="state" ></input></td>
    <td class="label">Zip code</td>
    <td class="wideField"><input class="field" id="postal_code"
          disabled="true" name="postal_code"></input></td>
  </tr>
  <tr>
    <td class="label">Country</td>
    <td class="wideField" colspan="3"><input class="field"
          id="country" disabled="true" name="country"></input></td>
  </tr>
</table>
<div id="map" style="width: 50%; height: 250px;"></div>
<div id="infowindow-content">
  <img src="" width="16" height="16" id="place-icon">
  <span id="place-name"  class="title"></span><br>
  <span id="place-address"></span>
</div>
<script>
  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'
  };



   var input = document.getElementById('autocomplete');

  function initMap() {
    var geocoder;
    var autocomplete;

    geocoder = new google.maps.Geocoder();
    var map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: -33.8688, lng: 151.2195},
      zoom: 13
    });
    var card = document.getElementById('locationField');
    autocomplete = new google.maps.places.Autocomplete(input);

    // Bind the map's bounds (viewport) property to the autocomplete object,
    // so that the autocomplete requests use the current map bounds for the
    // bounds option in the request.
    autocomplete.bindTo('bounds', map);

    var infowindow = new google.maps.InfoWindow();
    var infowindowContent = document.getElementById('infowindow-content');
    infowindow.setContent(infowindowContent);
    var marker = new google.maps.Marker({
      map: map,
      anchorPoint: new google.maps.Point(0, -29),
      draggable: true
    });

    autocomplete.addListener('place_changed', function() {
      infowindow.close();
      marker.setVisible(false);
      var place = autocomplete.getPlace();
      console.log(place);

      if (!place.geometry) {
        // User entered the name of a Place that was not suggested and
        // pressed the Enter key, or the Place Details request failed.
        window.alert("No details available for input: '" + place.name + "'");
        return;
      }

      // If the place has a geometry, then present it on a map.
      if (place.geometry.viewport) {
        map.fitBounds(place.geometry.viewport);
      } else {
        map.setCenter(place.geometry.location);
        map.setZoom(17);  // Why 17? Because it looks good.
      }
      marker.setPosition(place.geometry.location);
      marker.setVisible(true);

      var address = '';
      if (place.address_components) {
        address = [
          (place.address_components[0] && place.address_components[0].short_name || ''),
          (place.address_components[1] && place.address_components[1].short_name || ''),
          (place.address_components[2] && place.address_components[2].short_name || '')
        ].join(' ');
      }

      infowindowContent.children['place-icon'].src = place.icon;
      infowindowContent.children['place-name'].textContent = place.name;
      infowindowContent.children['place-address'].textContent = address;
      infowindow.open(map, marker);
      fillInAddress();

    });
  function fillInAddress() {
    var place = autocomplete.getPlace(input);
    console.log(place);
    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;
      }
      }
    }
 google.maps.event.addListener(marker, 'dragend', function() {
 geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) 
{
  if (status == google.maps.GeocoderStatus.OK) {
    if (results[0]) {
      console.log(autocomplete);
  $('#autocomplete').val(results[0].formatted_address);
  google.maps.event.trigger(autocomplete, 'place_changed');
  $('#latitude').val(marker.getPosition().lat());
  $('#longitude').val(marker.getPosition().lng());
  infowindow.setContent(results[0].formatted_address);
  infowindow.open(map, marker);
                    }
                  }
              });       
            }
            );
         }
    </script>
 </body>
 </html>

我需要在这里根据拖动它应该更改自动完成地址的位置,帮助我任何人。提前谢谢...

【问题讨论】:

    标签: javascript jquery html google-maps


    【解决方案1】:

    是的,你的函数 fillInAddress()。我把它改成这样你就可以直接给它地址组件作为参数了。

    function fillInAddress(new_address) {  // optional parameter
      if(typeof new_address == 'undefined') {
        var place = autocomplete.getPlace(input);
      }
      else {
        place = new_address;
      }
      ...
    }
    

    所以……

    google.maps.event.addListener(marker, 'dragend', function() {
      ...
      // do not trigger place_changed.  Instead call this:
      fillInAddress(results[0]);
      ...
    })
    

    完整代码

    <html>
    <head>
    <title>Place Autocomplete Address Form</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
    <style>
        /* Always set the map height explicitly to define the size of the div
       element that contains the map. */
    
        #map {
            height: 100%;
        }
    
        /* Optional: Makes the sample page fill the window. */
    
        html,
        body {
            height: 100%;
            margin: 0;
            padding: 0;
        }
    
        #locationField,
        #controls {
            position: relative;
            width: 480px;
        }
    
        #autocomplete {
            position: absolute;
            top: 0px;
            left: 0px;
            width: 99%;
        }
    
        .label {
            text-align: right;
            font-weight: bold;
            width: 100px;
            color: #303030;
        }
    
        #address {
            border: 1px solid #000090;
            background-color: #f0f0ff;
            width: 480px;
            padding-right: 2px;
        }
    
        #address td {
            font-size: 10pt;
        }
    
        .field {
            width: 99%;
        }
    
        .slimField {
            width: 80px;
        }
    
        .wideField {
            width: 200px;
        }
    
        #locationField {
            height: 20px;
            margin-bottom: 2px;
        }
    </style>
    
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA1BvEkX8v91LRu43HQe0-GNaHTVnoTSQs&libraries=places&callback=initMap" async defer></script>
    </head>
    <body>
    <br><br>
    <div id="locationField">
        <input id="autocomplete" placeholder="Enter your address" 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" name="streetnumber"></input>
            </td>
            <td class="wideField" colspan="2"><input class="field" id="route" disabled="true" name="route"></input>
            </td>
        </tr>
        <tr>
            <td class="label">City</td>
            <!-- Note: Selection of address components in this example is typical.
         You may need to adjust it for the locations relevant to your app. See
         https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform    
         -->
            <td class="wideField" colspan="3"><input class="field" id="locality" disabled="true" name="locality"></input>
            </td>
        </tr>
        <tr>
            <td class="label">State</td>
            <td class="slimField"><input class="field" id="administrative_area_level_1" disabled="true" name="state"></input>
            </td>
            <td class="label">Zip code</td>
            <td class="wideField"><input class="field" id="postal_code" disabled="true" name="postal_code"></input>
            </td>
        </tr>
        <tr>
            <td class="label">Country</td>
            <td class="wideField" colspan="3"><input class="field" id="country" disabled="true" name="country"></input>
            </td>
        </tr>
    </table>
    <div id="map" style="width: 50%; height: 250px;"></div>
    <div id="infowindow-content">
        <img src="" width="16" height="16" id="place-icon">
        <span id="place-name" class="title"></span><br>
        <span id="place-address"></span>
    </div>
    <script>
        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'
        };
    
    
    
        var input = document.getElementById('autocomplete');
    
        function initMap() {
            var geocoder;
            var autocomplete;
    
            geocoder = new google.maps.Geocoder();
            var map = new google.maps.Map(document.getElementById('map'), {
                center: {
                    lat: -33.8688,
                    lng: 151.2195
                },
                zoom: 13
            });
            var card = document.getElementById('locationField');
            autocomplete = new google.maps.places.Autocomplete(input);
    
            // Bind the map's bounds (viewport) property to the autocomplete object,
            // so that the autocomplete requests use the current map bounds for the
            // bounds option in the request.
            autocomplete.bindTo('bounds', map);
    
            var infowindow = new google.maps.InfoWindow();
            var infowindowContent = document.getElementById('infowindow-content');
            infowindow.setContent(infowindowContent);
            var marker = new google.maps.Marker({
                map: map,
                anchorPoint: new google.maps.Point(0, -29),
                draggable: true
            });
    
            autocomplete.addListener('place_changed', function() {
                infowindow.close();
                marker.setVisible(false);
                var place = autocomplete.getPlace();
                console.log(place);
    
                if (!place.geometry) {
                    // User entered the name of a Place that was not suggested and
                    // pressed the Enter key, or the Place Details request failed.
                    window.alert("No details available for input: '" + place.name + "'");
                    return;
                }
    
                // If the place has a geometry, then present it on a map.
                if (place.geometry.viewport) {
                    map.fitBounds(place.geometry.viewport);
                } else {
                    map.setCenter(place.geometry.location);
                    map.setZoom(17); // Why 17? Because it looks good.
                }
                marker.setPosition(place.geometry.location);
                marker.setVisible(true);
    
                var address = '';
                if (place.address_components) {
                    address = [
                        (place.address_components[0] && place.address_components[0].short_name || ''),
                        (place.address_components[1] && place.address_components[1].short_name || ''),
                        (place.address_components[2] && place.address_components[2].short_name || '')
                    ].join(' ');
                }
    
                infowindowContent.children['place-icon'].src = place.icon;
                infowindowContent.children['place-name'].textContent = place.name;
                infowindowContent.children['place-address'].textContent = address;
                infowindow.open(map, marker);
                fillInAddress();
    
            });
    
            function fillInAddress(new_address) { // optional parameter
                if (typeof new_address == 'undefined') {
                    var place = autocomplete.getPlace(input);
                } else {
                    place = new_address;
                }
                //console.log(place);
                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;
                    }
                }
            }
    
            google.maps.event.addListener(marker, 'dragend', function() {
                geocoder.geocode({
                    'latLng': marker.getPosition()
                }, function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        if (results[0]) {
                            console.log(autocomplete);
                            $('#autocomplete').val(results[0].formatted_address);
                            $('#latitude').val(marker.getPosition().lat());
                            $('#longitude').val(marker.getPosition().lng());
                            infowindow.setContent(results[0].formatted_address);
                            infowindow.open(map, marker);
                            // google.maps.event.trigger(autocomplete, 'place_changed');
                            fillInAddress(results[0]);
                        }
                    }
                });
            });
        }
    </script>
    </body>
    </html>
    

    【讨论】:

    • @ Emmanuel Delay 现在我的 google api 有些问题是我没有得到地图我让你知道它是否工作
    • 我认为我超出了请求数
    • 据你所知,代码没问题吧?只是导致问题的请求限制?
    • 最后一切正常@Emmanuel Delay 非常感谢现在一切都很好,我有一个疑问,我试图填充数据库地址(完整地址值)以输入时间图在选择时未显示的类型建议然后显示地图有什么方法可以不选择建议显示地图(这个仅用于从数据库场景中呈现地址)
    猜你喜欢
    • 2012-08-09
    • 2023-03-12
    • 1970-01-01
    • 2017-02-27
    • 1970-01-01
    • 2016-07-03
    • 2012-03-15
    • 1970-01-01
    相关资源
    最近更新 更多