【发布时间】:2015-04-11 05:05:08
【问题描述】:
我正在尝试加载 Google Maps Places API,以便将自动完成功能添加到我的搜索框中。我最初尝试将脚本标签粘贴到页面上,但出现错误“在文档上执行写入:除非显式打开,否则无法从异步加载的外部脚本写入文档。”我查看了错误,很多消息来源说我需要在 window.onload 中加载脚本,所以我尝试这样做,但我仍然收到“Execute write on doc”错误。
<script type="text/javascript">
var acService;
function loadScript() {
debugger;
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://maps.google.com/maps/api/js?v=3&libraries=places!callback';
document.body.appendChild(script);
acService = new google.maps.places.AutocompleteService(),
placesService = new google.maps.places.PlacesService(document.createElement('div'));
$("input#location").autocomplete({
source: function(req, resp) {
acService.getPlacePredictions({
input: req.term,
types:['(regions)']
}, function(places, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var _places = [];
for (var i = 0; i < places.length; ++i) {
_places.push({
id: places[i].place_id,
value: places[i].description,
label: places[i].description
});
}
resp(_places);
}
});
},
select: function(e, o) {
placesService.getDetails({
placeId: o.item.id
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
alert(o.item.value +
'\n is located at \n ' +
place.geometry.location.toUrlValue());
}
});
}
});
}
window.onload = loadScript;
</script>
这是我第一次尝试同样的错误:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places"></script>
<input id="location" />
<script type="text/javascript">
function bindAutocomplete() {
var acService = new google.maps.places.AutocompleteService(),
placesService = new google.maps.places.PlacesService(document.createElement('div'));
$("input#location").autocomplete({
source: function(req, resp) {
acService.getPlacePredictions({
input: req.term,
types:['(regions)']
}, function(places, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var _places = [];
for (var i = 0; i < places.length; ++i) {
_places.push({
id: places[i].place_id,
value: places[i].description,
label: places[i].description
});
}
resp(_places);
}
});
},
select: function(e, o) {
placesService.getDetails({
placeId: o.item.id
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
alert(o.item.value +
'\n is located at \n ' +
place.geometry.location.toUrlValue());
}
});
}
});
}
$(window).load(bindAutocomplete);
</script>
【问题讨论】:
标签: javascript asynchronous google-maps-api-3 autocomplete