我正在努力为我的谷歌地图API使用回调。我正在尝试有一个Goolge地图自动完成搜索框,收集Lat并渴望搜索到的位置。我找到了this answer 这确实很好,但有时搜索框不会加载位置建议。我发现这可能是由于google.maps.event.addDomListener(window, \'load\', initialize);
我使用的。相反,我发现我需要在脚本中使用回调。我试过了,但现在搜索框不再加载任何建议。下面是我现在拥有的。我做错什么了吗?非常感谢您的帮助和建议!
In functions.php
<?php
//ENQUE SCRIPTS
function my_enqueue() {
// First register script
// Google maps API
wp_register_script(\'googlemaps\', \'https://maps.googleapis.com/maps/api/js?key=XXXXXX&libraries=places&callback=initialize\');
wp_register_script( \'ajax-script\', get_stylesheet_directory_uri() . \'/js/custom.js\', array(\'jquery\') );
// Then enqueue script
wp_enqueue_script( \'googlemaps\' );
wp_enqueue_script( \'ajax-script\' );
}
add_action( \'wp_enqueue_scripts\', \'my_enqueue\' );
?>
In custom.js
jQuery( document ).ready(function($) {
function initialize() {
var input = document.getElementById(\'searchTextField\');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, \'place_changed\', function () {
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Select a suggestion from the list");
return;
}
document.getElementById(\'city2\').value = place.name;
document.getElementById(\'cityLat\').value = place.geometry.location.lat();
document.getElementById(\'cityLng\').value = place.geometry.location.lng();
});
}
//Window load does not seem to always work?
//google.maps.event.addDomListener(window, \'load\', initialize);
}); //Close document ready
In html
<input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" />
<input type="hidden" id="city2" name="city2" />
<input type="hidden" id="cityLat" name="cityLat" />
<input type="hidden" id="cityLng" name="cityLng" />
最合适的回答,由SO网友:shanebp 整理而成
在js文件中尝试以下操作:
function robbte_map_initialize() {
var input = document.getElementById(\'searchTextField\');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, \'place_changed\', function () {
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Select a suggestion from the list");
return;
}
document.getElementById(\'city2\').value = place.name;
document.getElementById(\'cityLat\').value = place.geometry.location.lat();
document.getElementById(\'cityLng\').value = place.geometry.location.lng();
});
}
jQuery(document).ready (robbte_map_initialize);