要将Places Autocomplete API限制为仅返回距离当前位置2公里范围内的地点,你需要结合使用Places Autocomplete API和Places Details API,并在Places Details API请求中添加location
和radius
参数
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
// 使用经纬度进行后续操作
}
function getAutocompletePredictions(latitude, longitude) {
const apiKey = 'YOUR_API_KEY';
const url = `https://maps.googleapis.com/maps/api/place/autocomplete/json?input=YOUR_INPUT&location=${latitude},${longitude}&radius=2000&key=${apiKey}`;
fetch(url)
.then((response) => response.json())
.then((data) => {
console.log(data);
});
}
请注意,你需要将YOUR_API_KEY
替换为你的Google Maps API密钥,将YOUR_INPUT
替换为用户输入的搜索词。
function getPlaceDetails(placeId) {
const apiKey = 'YOUR_API_KEY';
const url = `https://maps.googleapis.com/maps/api/place/details/json?place_id=${placeId}&location=${latitude},${longitude}&radius=2000&key=${apiKey}`;
fetch(url)
.then((response) => response.json())
入如下:
```javascript
{
"status": "OK",
"result": {
"name": "Your Place Name",
"location": {
"lat": 40.7128,
"lng": -74.0060
}
}
}
请注意,你需要将YOUR_API_KEY
替换为你的Google Maps API密钥。
getLocation();
function showPosition(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
getAutocompletePredictions(latitude, longitude);
}
function getAutocompletePredictions(latitude, longitude) {
const apiKey = 'YOUR_API_KEY';
const url = `https://maps.googleapis.com/maps/api/place/autocomplete/json?input=YOUR_INPUT&location=${latitude},${longitude}&radius=2000&key=${apiKey}`;
fetch(url)
.then((response) => response.json())
.then((data) => {
console.log(data);
});
}
现在,你已经成功地将Places Autocomplete API限制为仅返回距离当前位置2公里范围内的地点。
领取专属 10元无门槛券
手把手带您无忧上云