我如何将自动完成与Geocode结合起来以获取LAT。 &液化天然气。从此自动完成功能中的表单输入?

发布于 2025-02-01 13:48:04 字数 8141 浏览 4 评论 0 原文

我正在制作此表格,其中用户在其邮政编码中键入自动完成 Google..maps.places下拉列表的完整地址。唯一缺少的是 Latitude 经度,我打算为我的Google Sheeps evredsheet中的 onsubmit 发布适当的字段。

我坚持使用的是将地理编码API调用与自动完成的JavaScript函数结合在一起。我要做的是添加带有自动完成函数的地理编码API调用,以便将其添加。液化天然气被发送到隐藏的字段,我一直在试图弄清楚这三天,我想知道是否有人有解决方案

这是我拥有的代码:

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 initAutocomplete() {
  // Create the autocomplete object, restricting the search to geographical
  // location types.
  autocomplete = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
    {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() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }

  // 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++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;
    }
  }
}

// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      var circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}
<form id="myform" method="POST" 
              action="https://script.google.com/macros/s/AKfycbzF_r-4ENEXSMD36Ry_gQ9iSQ5dqfpZiw3VytR7LmpSAwxbEcRelxhGJroi8QCBavEI/exec"
              autocomplete="off" class="form" role="form">
                <input autocomplete="false" name="hidden" type="text" style="display:none;">
                
                <div class="form-group row">
                  
                  <label>Business address</label>
                  <div class="col-sm-4">
                    
                    <input id="autocomplete" autocomplete="off" autofill="off" placeholder="Postcode" onFocus="geolocate()" type="text"
                      class="form-control">
                  </div>
                </div>
                <br>
                <div class="form-group row">
                  <label>Number</label>
                  <div class="col-sm-4">
                    <input name="No."  class="form-control" id="street_number" disabled="false" required>
                  </div>
                  <label>Street</label>
                  <div class="col-sm-4">
                    <input name="Street"  class="form-control" id="route" disabled="true" required>
                  </div>
                </div>
                <br>
                <div class="form-group row">
                  <label>City</label>
                  <div class="col-sm-4">
                    <input name="City"  class="form-control field" id="locality" disabled="true" required>
                  </div>
                  <label>State</label>
                  <div class="col-sm-4">
                    <input name="State" class="form-control" id="administrative_area_level_1" disabled="true">
                  </div>
                </div>
                <br>
                <div class="form-group row">
                  <label>Postal/zipcode</label>
                  <div class="col-sm-4">
                    <input name="Postcode"  class="form-control" id="postal_code" disabled="true" required>
                  </div>
                  <label>Country</label>
                  <div class="col-sm-4">
                    <input name="Country"  class="form-control" id="country" disabled="true">
                  </div>
                </div>

                <div class="form-group row">
                  <label>Lat</label>
                  <div class="col-sm-4">
                    <input name="Lat"  class="form-control" id="Lat" disabled="true" required>
                  </div>
                  <label>Lng</label>
                  <div class="col-sm-4">
                    <input name="Lng"  class="form-control" id="Lng" disabled="true">
                  </div>
                </div>

              </div>
            <div class="form-group row">
              
              <div id="submit">
                <button type="submit" value="Submit" >Submit</button>
              </div>
            </div>
            </form>
            <script
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initAutocomplete"
        async defer></script>

现在,我还有此代码段用于调用Google GeoCoding API

 document.getElementById('myform').addEventListener('submit', function(e){
    e.preventDefault(); //prevent form submit
    const place = autocomplete.getPlace(); //get place from autocomplete
    if (!place || !place.geometry) { //check if valid location
      swal("You have provided an Invalid address","Enter a valid Address", "warning");
      return;
    }
    // It is valid, proceed to geocode!
    else {
      // Listen for form submit
      document.getElementById('myForm').addEventListener('submit', geocode);
      function geocode(e){
        // Prevent actual submit
        e.preventDefault();
        var location = document.getElementById('location-input').value; //* I think this is where I might have made a mistake
        axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
            params:{
                address: location,
                key: 'YOUR_API_KEY'
            }
        })
        .then(function(response){
            // Log full response
            console.log(response);
    
            // Formatted Address
            var formattedAddress = response.data.results[0].formatted_address;
            
            // Address Components
            var addressComponents = response.data.results[0].address_components;
    
            // Get values from the input fields
            var veg_planted = getInputVal('veg_planted');
        
            // Get geometry 
            var lat = response.data.results[0].geometry.location.lat;
            var lng = response.data.results[0].geometry.location.lng;
            var coords= (formattedAddress + ": " + lat + "," + lng);
            console.log(coords);
    
            // Save messages
            saveMessage(veg_planted, coords);
            
        })
        .catch(function(error){
            console.log(error);
        });
    }
    }
  });

可以将此函数与自动完成功能集成在一起,我必须使表单填充lat。和lng。值?如果有人有解决方案,它将对我有很大帮助。谢谢。

I'm making this form where the user types in their postcode and it autocompletes the full address from google.maps.places dropdown list. The only thing that's missing is the latitude and longitude which I intend to make hidden fields for and then onsubmit post to my google sheets spreadsheet in the appropriate fields.

What I'm stuck on, is combining the Geocoding API call, with the Autocomplete Javascript function. What I'm trying to do, is add in a Geocoding API call with the autocomplete function so that the Lat. and Lng is sent to the hidden fields, I've been trying to figure this out for 3 days, I wonder if anyone has a solution.

Here is the code I have:

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 initAutocomplete() {
  // Create the autocomplete object, restricting the search to geographical
  // location types.
  autocomplete = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
    {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() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }

  // 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++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;
    }
  }
}

// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      var circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}
<form id="myform" method="POST" 
              action="https://script.google.com/macros/s/AKfycbzF_r-4ENEXSMD36Ry_gQ9iSQ5dqfpZiw3VytR7LmpSAwxbEcRelxhGJroi8QCBavEI/exec"
              autocomplete="off" class="form" role="form">
                <input autocomplete="false" name="hidden" type="text" style="display:none;">
                
                <div class="form-group row">
                  
                  <label>Business address</label>
                  <div class="col-sm-4">
                    
                    <input id="autocomplete" autocomplete="off" autofill="off" placeholder="Postcode" onFocus="geolocate()" type="text"
                      class="form-control">
                  </div>
                </div>
                <br>
                <div class="form-group row">
                  <label>Number</label>
                  <div class="col-sm-4">
                    <input name="No."  class="form-control" id="street_number" disabled="false" required>
                  </div>
                  <label>Street</label>
                  <div class="col-sm-4">
                    <input name="Street"  class="form-control" id="route" disabled="true" required>
                  </div>
                </div>
                <br>
                <div class="form-group row">
                  <label>City</label>
                  <div class="col-sm-4">
                    <input name="City"  class="form-control field" id="locality" disabled="true" required>
                  </div>
                  <label>State</label>
                  <div class="col-sm-4">
                    <input name="State" class="form-control" id="administrative_area_level_1" disabled="true">
                  </div>
                </div>
                <br>
                <div class="form-group row">
                  <label>Postal/zipcode</label>
                  <div class="col-sm-4">
                    <input name="Postcode"  class="form-control" id="postal_code" disabled="true" required>
                  </div>
                  <label>Country</label>
                  <div class="col-sm-4">
                    <input name="Country"  class="form-control" id="country" disabled="true">
                  </div>
                </div>

                <div class="form-group row">
                  <label>Lat</label>
                  <div class="col-sm-4">
                    <input name="Lat"  class="form-control" id="Lat" disabled="true" required>
                  </div>
                  <label>Lng</label>
                  <div class="col-sm-4">
                    <input name="Lng"  class="form-control" id="Lng" disabled="true">
                  </div>
                </div>

              </div>
            <div class="form-group row">
              
              <div id="submit">
                <button type="submit" value="Submit" >Submit</button>
              </div>
            </div>
            </form>
            <script
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initAutocomplete"
        async defer></script>

Now I also have this code snippet for calling the google geocoding API

 document.getElementById('myform').addEventListener('submit', function(e){
    e.preventDefault(); //prevent form submit
    const place = autocomplete.getPlace(); //get place from autocomplete
    if (!place || !place.geometry) { //check if valid location
      swal("You have provided an Invalid address","Enter a valid Address", "warning");
      return;
    }
    // It is valid, proceed to geocode!
    else {
      // Listen for form submit
      document.getElementById('myForm').addEventListener('submit', geocode);
      function geocode(e){
        // Prevent actual submit
        e.preventDefault();
        var location = document.getElementById('location-input').value; //* I think this is where I might have made a mistake
        axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
            params:{
                address: location,
                key: 'YOUR_API_KEY'
            }
        })
        .then(function(response){
            // Log full response
            console.log(response);
    
            // Formatted Address
            var formattedAddress = response.data.results[0].formatted_address;
            
            // Address Components
            var addressComponents = response.data.results[0].address_components;
    
            // Get values from the input fields
            var veg_planted = getInputVal('veg_planted');
        
            // Get geometry 
            var lat = response.data.results[0].geometry.location.lat;
            var lng = response.data.results[0].geometry.location.lng;
            var coords= (formattedAddress + ": " + lat + "," + lng);
            console.log(coords);
    
            // Save messages
            saveMessage(veg_planted, coords);
            
        })
        .catch(function(error){
            console.log(error);
        });
    }
    }
  });

Can this function be integrated with the autocomplete function I have to make the form fill out Lat. and Lng. values? If anyone out there has the solution it would help me a lot. Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

纵山崖 2025-02-08 13:48:04

您无需使用地理编码器。 API在其响应中返回LAT/LNG坐标(如果有)。

placerEsult.spracerEsult.Stemult.Stemry

几何可选
类型:PlaceMetry 可选
该地点的几何信息。

noreflow noreferrer“> plotegemetry”>
定义有关位置几何形状的信息。
属性
位置 可选
类型: latlng 可选
这个地方的位置。


document.getElementById("Lat").value = place.geometry.location.lat();
document.getElementById("Lng").value = place.geometry.location.lng();

工作代码段:

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 initAutocomplete() {
  // Create the autocomplete object, restricting the search to geographical
  // location types.
  autocomplete = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */
    (document.getElementById('autocomplete')), {
      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() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }
  document.getElementById("Lat").value = place.geometry.location.lat();
  document.getElementById("Lng").value = place.geometry.location.lng();

  // 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++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;
    }
  }
}

// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      var circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}
<form id="myform" method="POST" action="https://script.google.com/macros/s/AKfycbzF_r-4ENEXSMD36Ry_gQ9iSQ5dqfpZiw3VytR7LmpSAwxbEcRelxhGJroi8QCBavEI/exec" autocomplete="off" class="form" role="form">
  <input autocomplete="false" name="hidden" type="text" style="display:none;">

  <div class="form-group row">

    <label>Business address</label>
    <div class="col-sm-4">

      <input id="autocomplete" autocomplete="off" autofill="off" placeholder="Postcode" onFocus="geolocate()" type="text" class="form-control">
    </div>
  </div>
  <br>
  <div class="form-group row">
    <label>Number</label>
    <div class="col-sm-4">
      <input name="No." class="form-control" id="street_number" disabled="false" required>
    </div>
    <label>Street</label>
    <div class="col-sm-4">
      <input name="Street" class="form-control" id="route" disabled="true" required>
    </div>
  </div>
  <br>
  <div class="form-group row">
    <label>City</label>
    <div class="col-sm-4">
      <input name="City" class="form-control field" id="locality" disabled="true" required>
    </div>
    <label>State</label>
    <div class="col-sm-4">
      <input name="State" class="form-control" id="administrative_area_level_1" disabled="true">
    </div>
  </div>
  <br>
  <div class="form-group row">
    <label>Postal/zipcode</label>
    <div class="col-sm-4">
      <input name="Postcode" class="form-control" id="postal_code" disabled="true" required>
    </div>
    <label>Country</label>
    <div class="col-sm-4">
      <input name="Country" class="form-control" id="country" disabled="true">
    </div>
  </div>

  <div class="form-group row">
    <label>Lat</label>
    <div class="col-sm-4">
      <input name="Lat" class="form-control" id="Lat" disabled="true" required>
    </div>
    <label>Lng</label>
    <div class="col-sm-4">
      <input name="Lng" class="form-control" id="Lng" disabled="true">
    </div>
  </div>

  </div>
  <div class="form-group row">

    <div id="submit">
      <button type="submit" value="Submit">Submit</button>
    </div>
  </div>
</form>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB_MrpX85obMpsk_eEdfE-iPIt06qbHyt0&libraries=places&callback=initAutocomplete" async defer></script>

You don't need to use the geocoder. The places API returns the lat/lng coordinates in its response (if it has them).

PlaceResult.geometry
geometry optional
Type: PlaceGeometry optional
The Place’s geometry-related information.

PlaceGeometry interface
Defines information about the geometry of a Place.
Properties
location optional
Type: LatLng optional
The Place’s position.

document.getElementById("Lat").value = place.geometry.location.lat();
document.getElementById("Lng").value = place.geometry.location.lng();

working code snippet:

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 initAutocomplete() {
  // Create the autocomplete object, restricting the search to geographical
  // location types.
  autocomplete = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */
    (document.getElementById('autocomplete')), {
      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() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }
  document.getElementById("Lat").value = place.geometry.location.lat();
  document.getElementById("Lng").value = place.geometry.location.lng();

  // 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++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;
    }
  }
}

// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      var circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}
<form id="myform" method="POST" action="https://script.google.com/macros/s/AKfycbzF_r-4ENEXSMD36Ry_gQ9iSQ5dqfpZiw3VytR7LmpSAwxbEcRelxhGJroi8QCBavEI/exec" autocomplete="off" class="form" role="form">
  <input autocomplete="false" name="hidden" type="text" style="display:none;">

  <div class="form-group row">

    <label>Business address</label>
    <div class="col-sm-4">

      <input id="autocomplete" autocomplete="off" autofill="off" placeholder="Postcode" onFocus="geolocate()" type="text" class="form-control">
    </div>
  </div>
  <br>
  <div class="form-group row">
    <label>Number</label>
    <div class="col-sm-4">
      <input name="No." class="form-control" id="street_number" disabled="false" required>
    </div>
    <label>Street</label>
    <div class="col-sm-4">
      <input name="Street" class="form-control" id="route" disabled="true" required>
    </div>
  </div>
  <br>
  <div class="form-group row">
    <label>City</label>
    <div class="col-sm-4">
      <input name="City" class="form-control field" id="locality" disabled="true" required>
    </div>
    <label>State</label>
    <div class="col-sm-4">
      <input name="State" class="form-control" id="administrative_area_level_1" disabled="true">
    </div>
  </div>
  <br>
  <div class="form-group row">
    <label>Postal/zipcode</label>
    <div class="col-sm-4">
      <input name="Postcode" class="form-control" id="postal_code" disabled="true" required>
    </div>
    <label>Country</label>
    <div class="col-sm-4">
      <input name="Country" class="form-control" id="country" disabled="true">
    </div>
  </div>

  <div class="form-group row">
    <label>Lat</label>
    <div class="col-sm-4">
      <input name="Lat" class="form-control" id="Lat" disabled="true" required>
    </div>
    <label>Lng</label>
    <div class="col-sm-4">
      <input name="Lng" class="form-control" id="Lng" disabled="true">
    </div>
  </div>

  </div>
  <div class="form-group row">

    <div id="submit">
      <button type="submit" value="Submit">Submit</button>
    </div>
  </div>
</form>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB_MrpX85obMpsk_eEdfE-iPIt06qbHyt0&libraries=places&callback=initAutocomplete" async defer></script>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文