Moh*_*mad 0 jquery google-maps google-places-api
我正在尝试为Google地图位置创建一个简单的自动填充字段,但是即使我的字段是HtmlInputElement,我也会收到以下错误消息
InvalidValueError:不是HTMLInputElement的实例
的HTML:
<input type="text" id="input"/>
<div id="map" style="width: 200px; height: 200px;"></div>
Run Code Online (Sandbox Code Playgroud)
js:
$(document).ready(function(){
var map_input = $('#input');
setTimeout(function(){initMap()},'5000');
function initMap() {
var map = new google.maps.Map($('form #map'), {
center: {lat: 33.8892846, lng: 35.539302},
zoom: 11
});
var autocomplete = new google.maps.places.Autocomplete(map_input);
var marker = new google.maps.Marker({
map: map
});
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert("No details available for input: '" + place.name + "'");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
//map.setCenter(place.geometry.location);
//map.setZoom(17); // Why 17? Because it looks good.
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
});
}
});
Run Code Online (Sandbox Code Playgroud)
您的“输入元素” 不是 HTMLInputElement的实例。它是一个JQuery数组。这将起作用:
var map_input = $('#input')[0];
Run Code Online (Sandbox Code Playgroud)
代码段:
var map_input = $('#input')[0];
Run Code Online (Sandbox Code Playgroud)
$(document).ready(function(){
var map_input = $('#input')[0];
setTimeout(function(){initMap()},'5000');
function initMap() {
var map = new google.maps.Map($('form #map'), {
center: {lat: 33.8892846, lng: 35.539302},
zoom: 11
});
var autocomplete = new google.maps.places.Autocomplete(map_input);
var marker = new google.maps.Marker({
map: map
});
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert("No details available for input: '" + place.name + "'");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
//map.setCenter(place.geometry.location);
//map.setZoom(17); // Why 17? Because it looks good.
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
});
}
});Run Code Online (Sandbox Code Playgroud)