正如标题所说,我正在尝试使用谷歌API自动完成功能而不创建谷歌地图。我在多个网站上找到了一些代码并尝试将它们放在一起,填补了缺失的部分,但到目前为止它还没有工作。我想知道是否有人知道谷歌API如何工作,可以帮助我,谢谢!
HTML:
<head>
....
<script src="file.js"></script>
....
</head>
<body>
....
<input type="text" class="form-control" id="university" onfocus="geolocate()" placeholder="Name of University" required>
....
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&signed_in=true&libraries=places&callback=initialize" async defer></script>
</body>
JS:
/*global google */
var autocomplete;
function initialize() {
"use strict";
autocomplete = new google.maps.places.Autocomplete(document.getElementById("university"), {types: ["geocode"]});
}
function geolocate() {
"use strict";
var geolocation, circle;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
答案 0 :(得分:2)
下面提供的Place Autocomplete example不依赖于google.maps.Map
类:
function initMap() {
var input = document.getElementById('pac-input');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
document.getElementById('placeInfo').innerHTML = '<div><strong>' + place.name + '</strong><br>' + address;
});
}
&#13;
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
.controls {
margin-top: 10px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 300px;
}
#pac-input:focus {
border-color: #4d90fe;
}
.pac-container {
font-family: Roboto;
}
&#13;
<input id="pac-input" class="controls" type="text"
placeholder="Enter a location"/>
<pre id="placeInfo"></pre>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap"
async defer></script>
&#13;