我想將 Places 自動完成 API 結果偏向用戶位置周圍的半徑。
我在應該使用的Places API 檔案components中看到,但我不確定語法,也找不到示例。 我已經在專案的另一部分擁有用戶當前位置,因此為了這篇文章可以忽略。
<script src="https://maps.googleapis.com/maps/api/js?key=[KEY]&libraries=places&callback=initAutocomplete" async defer></script>
<script>
function initAutocomplete() {
var input = document.getElementById('directions-from');
new google.maps.places.Autocomplete(input);
}
</script>
<div class="row">
<div class="col-6">
<label for="directions-from">From:</label>
<input id="directions-from" placeholder="Enter a place" class="form-control" type="text" />
<br />
<label for="directions-to">To:</label>
<input type="text" id="directions-to" class="form-control" value="@formatToAddressInput" disabled />
<br />
<input type="button" value="Go" onclick="setMapAddress()" />
<input type="button" value="Clear" onclick="clearInput()" />
</div>
</div>
<div class="row">
<div class="col-12">
<iframe
height="350"
id="google-maps"
width="600"
frameborder="0"
style="border:0"
referrerpolicy="no-referrer-when-downgrade"
src="https://www.google.com/maps/embed/v1/directions?key=[KEY]&origin=@formatToAddressAPI&destination=@formatToAddressAPI">
</iframe>
</div>
</div>
<script>
function clearInput() {
$('#directions-from').val("");
}
function setMapAddress() {
if ($('#directions-from').val().length > 1) {
var address = $('#directions-from').val();
address = address.replace(' ', ' ');
var mapsURL = $('#google-maps').attr('src');
var url = new URL(mapsURL);
url.searchParams.set("origin", address);
//reload iFrame
console.log(url);
document.getElementById('google-maps').src = url;
}
}
</script>
uj5u.com熱心網友回復:
您正在查看錯誤的檔案。您在問題中鏈接的是網路服務,而不是作為 Javascript API 一部分的小部件。
正確的檔案在這里。
您不能使用位置/半徑來偏向結果,但您可以使用bounds.
bounds是一個google.maps.LatLngBounds物件,指定要在其中搜索地點的區域。結果偏向但不限于包含在這些范圍內的地方。
您還可以使用以下方法將搜索限制在這些范圍內
strictBounds是一個布林值,指定 API 是否必須僅回傳嚴格在給定邊界定義的區域內的那些地方。API 不會回傳此區域之外的結果,即使它們與用戶輸入匹配。
例子:
const center = new google.maps.LatLng(52.518588, 13.369337);
// Create a bounding box with sides ~10km away from the center point
const defaultBounds = {
north: center.lat 0.1,
south: center.lat - 0.1,
east: center.lng 0.1,
west: center.lng - 0.1,
};
const input = document.getElementById('directions-from');
const options = {
bounds: defaultBounds,
fields: ["address_components"], // Or whatever fields you need
strictBounds: true, // Only if you want to restrict, not bias
types: ["establishment"], // Whatever types you need
};
const autocomplete = new google.maps.places.Autocomplete(input, options);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/473380.html
標籤:javascript html 谷歌地图 google-places-api
