我打算制作一个与 https://www.swiggy.com/ 中的完全相同的自动完成地址表单 我被困的地方是:-
下面是我的代码。
<!DOCTYPE html>
<html>
<head>
<title>Place Autocomplete Address Form</title>
<script>
var lat, lng;
//This function is to fetch the current location of the user
function geolocate(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getCoordinates);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
//This function returns the latitude and longitude of the user
function getCoordinates(position){
lat = position.coords.latitude;
lng = position.coords.longitude;
console.log(lat, lng);
}
//This function fetches the current string in the input field and calls a function to get places suggestions for the current string
function Suggestions(){
userlocation = document.getElementById('userlocation');
console.log(userlocation.value);
getSuggestions(userlocation.value);
}
//This function returns the predictions for the entered string, nearest to the current location coordinates, within a radius of 500 units and in India
function getSuggestions(value){
console.log(value);
var request = new XMLHttpRequest()
request.open('GET', 'https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api/place/autocomplete/json?input='+value+'&types=establishment&components=country:IN&location='+lat+','+lng+'&radius=500&key=YOUR-API-KEY&callback=initAutocomplete', true)
request.setRequestHeader('Content-Type', 'application/json');
request.send();
request.onload = function (){
var data = JSON.parse(this.response)
console.log(data); // Returns the array of predictions
}
}
</script>
</head>
<body onload="geolocate();">
<div class="row">
<input type="text" id="userlocation" placeholder="Enter your address" autocomplete="off" oninput="Suggestions();">
</div><br>
<button class="btn">Submit</button>
</body>
</html>
请帮我解决这个问题。任何形式的帮助将不胜感激。 谢谢