javascript - 使用谷歌地图 API 填充经度和纬度

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

我有以下 html 和 javascript。 JavaScript 将位置详细信息从 google map api 填充到 html 表单字段。这个想法是有人输入第一个 html 表单字段中填充的原始位置,然后输入第二个表单中填充的第二个位置。这非常有效。

现在我还想用第一个和第二个位置的经度和纬度填充表单。

*<!DOCTYPE html>
<html>
  <head>
    <title>Place Autocomplete Address Form</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
  </head>

  <body>
    <script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="locationField">
  <input id="autocomplete" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
</div>
<div id="addressone">
  <input type="text" id="street_number" name="street_number" />
  <input type="text" id="route" name="street_name" />
  <input type="text" id="locality" name="town_city" />
  <input type="text" id="administrative_area_level_1" name="administrative_area_level_1" />
  <input type="text" id="postal_code" name="postcode" />
  <input type="text" id="country" name="country" />
  <input type="text" id="longitude" name="longitude" />
  <input type="text" id="latitude" name="latitude" />

</div>
<div id="locationField2">
  <input id="autocomplete2" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
</div>
<div id="addresstwo">
  <input type="text" id="street_number2" name="street_number2" />
  <input type="text" id="route2" name="street_name2" />
  <input type="text" id="locality2" name="town_city2" />
  <input type="text" id="administrative_area_level_12" name="administrative_area_level_12" />
  <input type="text" id="postal_code2" name="postcode2" />
  <input type="text" id="country2" name="country2" />
  <input type="text" id="longitude2" name="longitude2" />
  <input type="text" id="latitude2" name="latitude2" />
</div>

    <script>
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.

var placeSearch, autocomplete, autocomplete2;
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', function() {
    fillInAddress(autocomplete, "");
  });

  autocomplete2 = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */
    (document.getElementById('autocomplete2')), {
      types: ['geocode']
    });
  autocomplete2.addListener('place_changed', function() {
    fillInAddress(autocomplete2, "2");
  });

}

function fillInAddress(autocomplete, unique) {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    if (!!document.getElementById(component + unique)) {
      document.getElementById(component + unique).value = '';
      document.getElementById(component + unique).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] && document.getElementById(addressType + unique)) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType + unique).value = val;
    }
  }
}
google.maps.event.addDomListener(window, "load", initAutocomplete);

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());
    });
  }
}
// [END region_geolocation]

    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAqYwW9d0lnFABF-0NKCTrO__G_d3d958k&signed_in=true&libraries=places&callback=initAutocomplete"
        async defer></script>
  </body>
</html>*

代码填充所有必填字段,但不填充经度和纬度。有解决办法吗?

最佳答案

您没有任何代码来填充纬度和经度字段。将其添加到 fillInAddress:

document.getElementById('latitude'+unique).value = place.geometry.location.lat();
document.getElementById('longitude'+unique).value = place.geometry.location.lng();

功能齐全:

function fillInAddress(autocomplete, unique) {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    if (!!document.getElementById(component + unique)) {
      document.getElementById(component + unique).value = '';
      document.getElementById(component + unique).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] && document.getElementById(addressType + unique)) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType + unique).value = val;
    }
  }
  document.getElementById('latitude'+unique).value = place.geometry.location.lat();
  document.getElementById('longitude'+unique).value = place.geometry.location.lng();
}

proof of concept fiddle

代码片段:

// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.

var placeSearch, autocomplete, autocomplete2;
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', function() {
    fillInAddress(autocomplete, "");
  });

  autocomplete2 = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */
    (document.getElementById('autocomplete2')), {
      types: ['geocode']
    });
  autocomplete2.addListener('place_changed', function() {
    fillInAddress(autocomplete2, "2");
  });

}

function fillInAddress(autocomplete, unique) {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    if (!!document.getElementById(component + unique)) {
      document.getElementById(component + unique).value = '';
      document.getElementById(component + unique).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] && document.getElementById(addressType + unique)) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType + unique).value = val;
    }
  }
  document.getElementById('latitude' + unique).value = place.geometry.location.lat();
  document.getElementById('longitude' + unique).value = place.geometry.location.lng();

}
google.maps.event.addDomListener(window, "load", initAutocomplete);

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());
      });
    }
  }
  // [END region_geolocation]
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="locationField">
  <input id="autocomplete" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
</div>
<div id="addressone">
  <input type="text" id="street_number" name="street_number" />
  <input type="text" id="route" name="street_name" />
  <input type="text" id="locality" name="town_city" />
  <input type="text" id="administrative_area_level_1" name="administrative_area_level_1" />
  <input type="text" id="postal_code" name="postcode" />
  <input type="text" id="country" name="country" />
  <input type="text" id="longitude" name="longitude" />
  <input type="text" id="latitude" name="latitude" />

</div>
<div id="locationField2">
  <input id="autocomplete2" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
</div>
<div id="addresstwo">
  <input type="text" id="street_number2" name="street_number2" />
  <input type="text" id="route2" name="street_name2" />
  <input type="text" id="locality2" name="town_city2" />
  <input type="text" id="administrative_area_level_12" name="administrative_area_level_12" />
  <input type="text" id="postal_code2" name="postcode2" />
  <input type="text" id="country2" name="country2" />
  <input type="text" id="longitude2" name="longitude2" />
  <input type="text" id="latitude2" name="latitude2" />
</div>

关于javascript - 使用谷歌地图 API 填充经度和纬度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35334324/

相关文章:

javascript - 上传完成后如何获取json结果?

javascript - 禁用 Google map 中的 InfoWindow

javascript - 在类而不是 id 中加载 map

javascript - 谷歌地图 API v3 上的单图 block WMS 图层

php - 谷歌地图信息窗口通过XML的多个地址

javascript - 在精确位置数组中搜索

javascript - 无法从 Angular 的下拉列表中填充和发布值

javascript - Google Maps 3 API - 单击功能(来自 geojson)并检查它是否包含位置

angularjs - NgMap错误 "could not find map"

javascript - scss 文件未在 React 中编译