Google 地点自动完成、地理编码和地址验证
Google Places Autocomplete, Geocoding and address validation
我的代码遇到了挑战。我有一个 JS 和 HTML 代码,允许用户输入他们的地点地址并将其提交到我的 Firebase 数据库。无论用户在地址输入中输入什么,代码都应首先检查它是否是有效输入,而不是像 'thsd' 这样的随机单词,从技术上讲,这不是一个地方的 place/location。如果它是一个有效的输入,即它是从 Google 地图建议中选择的,它应该继续对其进行地理编码并将坐标发送到数据库。当我提交一个无效地址时,它会发送它而不告诉我它不是有效地址的警报。请检查我的代码并告诉我我可能做错了什么,因为我已经尝试了所有方法但仍然出现错误。
/ Requires the Places library. Include the libraries=places
// parameter when you first load the API.
function initMap() {
const input = document.getElementById("location-input");
const autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener("place_changed", () => {
const place = autocomplete.getPlace();
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 + "'");
swal("You have provided an Invalid address","Enter a valid Address", "warning");
return;
}
});
//Check before submit if it is Valid
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: 'AIzaSyCZhP_mwsdzM5X-tgmkplUj5ew'
}
})
.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);
});
}
}
});
}
// Listen for Form Submit
document.getElementById('myForm').addEventListener('submit', submitForm);
// Submit Form
function submitForm(e){
e.preventDefault();
}
// Function to get form values
function getInputVal(id){
return document.getElementById(id).value;
}
// Save message to firebase
function saveMessage(veg_planted, coords){
var newMessageRef = messagesRef.push();
newMessageRef.set({
Coordinates: coords,
Veg_planted: veg_planted,
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="form.css">
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCZhP_mwsdzM5X-tgmkplUj5ew&callback=initMap&libraries=places&v=weekly" defer></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<title>Document</title>
</head>
<body>
<form action="" id="myform">
<div class="container">
<div class="row">
<!--Vegetable Planted Section-->
<div class="form_item col-md-6 mg-b">
<label for="veg_planted" class="form_label">Vegetable Planted<span>*</span></label>
<select name="veg_planted" id="veg_planted" class="form_input" required>
<option selected disabled>Choose a plant from the list</option>
<option value="Agastache - Hyssop">Agastache - Hyssop</option>
<option value="Ageratum">Ageratum</option>
<option value="Amaranth">Amaranth</option>
</select>
</div>
<!--End of Vegetable Planted Section-->
<!--Address Section-->
<div class="form_item col-md-6 mg-b">
<label for="address" class="form_label">Location<span>*</span></label>
<input type="address" class="form_input" name="address" id="location-input" placeholder="Enter Address of Area where Crop was Planted" required>
</div>
<!--End of Address Section-->
<!--Form Submit Section-->
<div class="row fill-form">
<input name="submit" type="submit" id="submit" class="submit" value="Submit">
</div>
<!--End of Form Submit Section-->
</div>
</div>
<script src="places.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
</form>
</body>
</html>
请帮助我检查代码,我已经尝试更改所有可能的更改但仍然没有成功。
由于我们已经在 submit
侦听器中,因此您无需在 else 中添加此行:
document.getElementById('myForm').addEventListener('submit', geocode);
只需写下您的 geocode
函数,然后 运行 单独写下它。
function geocode(){
// your function codes
}
geocode();
对于这一行:
var location = document.getElementById('location-input').value;
因为你已经 place.geometry
持有你可以找到 lat lang 和任何其他类似的东西
let lat = place.geometry.lat();
let lng = place.geometry.lng();
您不需要再次检查几何有效性,因为我们在提交侦听器之前已经检查过了。
我的代码遇到了挑战。我有一个 JS 和 HTML 代码,允许用户输入他们的地点地址并将其提交到我的 Firebase 数据库。无论用户在地址输入中输入什么,代码都应首先检查它是否是有效输入,而不是像 'thsd' 这样的随机单词,从技术上讲,这不是一个地方的 place/location。如果它是一个有效的输入,即它是从 Google 地图建议中选择的,它应该继续对其进行地理编码并将坐标发送到数据库。当我提交一个无效地址时,它会发送它而不告诉我它不是有效地址的警报。请检查我的代码并告诉我我可能做错了什么,因为我已经尝试了所有方法但仍然出现错误。
/ Requires the Places library. Include the libraries=places
// parameter when you first load the API.
function initMap() {
const input = document.getElementById("location-input");
const autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener("place_changed", () => {
const place = autocomplete.getPlace();
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 + "'");
swal("You have provided an Invalid address","Enter a valid Address", "warning");
return;
}
});
//Check before submit if it is Valid
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: 'AIzaSyCZhP_mwsdzM5X-tgmkplUj5ew'
}
})
.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);
});
}
}
});
}
// Listen for Form Submit
document.getElementById('myForm').addEventListener('submit', submitForm);
// Submit Form
function submitForm(e){
e.preventDefault();
}
// Function to get form values
function getInputVal(id){
return document.getElementById(id).value;
}
// Save message to firebase
function saveMessage(veg_planted, coords){
var newMessageRef = messagesRef.push();
newMessageRef.set({
Coordinates: coords,
Veg_planted: veg_planted,
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="form.css">
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCZhP_mwsdzM5X-tgmkplUj5ew&callback=initMap&libraries=places&v=weekly" defer></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<title>Document</title>
</head>
<body>
<form action="" id="myform">
<div class="container">
<div class="row">
<!--Vegetable Planted Section-->
<div class="form_item col-md-6 mg-b">
<label for="veg_planted" class="form_label">Vegetable Planted<span>*</span></label>
<select name="veg_planted" id="veg_planted" class="form_input" required>
<option selected disabled>Choose a plant from the list</option>
<option value="Agastache - Hyssop">Agastache - Hyssop</option>
<option value="Ageratum">Ageratum</option>
<option value="Amaranth">Amaranth</option>
</select>
</div>
<!--End of Vegetable Planted Section-->
<!--Address Section-->
<div class="form_item col-md-6 mg-b">
<label for="address" class="form_label">Location<span>*</span></label>
<input type="address" class="form_input" name="address" id="location-input" placeholder="Enter Address of Area where Crop was Planted" required>
</div>
<!--End of Address Section-->
<!--Form Submit Section-->
<div class="row fill-form">
<input name="submit" type="submit" id="submit" class="submit" value="Submit">
</div>
<!--End of Form Submit Section-->
</div>
</div>
<script src="places.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
</form>
</body>
</html>
请帮助我检查代码,我已经尝试更改所有可能的更改但仍然没有成功。
由于我们已经在 submit
侦听器中,因此您无需在 else 中添加此行:
document.getElementById('myForm').addEventListener('submit', geocode);
只需写下您的 geocode
函数,然后 运行 单独写下它。
function geocode(){
// your function codes
}
geocode();
对于这一行:
var location = document.getElementById('location-input').value;
因为你已经 place.geometry
持有你可以找到 lat lang 和任何其他类似的东西
let lat = place.geometry.lat();
let lng = place.geometry.lng();
您不需要再次检查几何有效性,因为我们在提交侦听器之前已经检查过了。