我正在使用 JS 加载 Google map ,代码如下。
$(document).ready(function(){
$('.acf-map').each(function(){
map = new_map( $(this) );
});
var geocoder = new google.maps.Geocoder();
document.getElementById('submit').addEventListener('click', function() {
geocodeAddress(geocoder, map);
location.reload();
});
});
我正在使用 PHP 创建 map 和标记
<div class="acf-map">
<?php $custom = new WP_Query(array(
'post_type' => 'centre',
'posts_per_page' => -1
)); ?>
<?php
if ($custom->have_posts()) {
while ($custom->have_posts()) {
$custom->the_post(); ?>
<?php $location = get_field('centre_location'); ?>
<div class="marker" data-lat="<?php echo $location['lat'] ?>" data-lng="<?php echo $location['lng']; ?>" style="border: 5px solid grey;">
<a href="<?= the_permalink() ?>"><h5 class="orange"><?= get_field('centre_name'); ?></h5></a>
<p class="address"><?php echo get_field('centre_address') ?></p>
<p class="orange">Call us at <a href="tel: <?= get_field('centre_telephone_number'); ?>"><?= get_field('centre_telephone_number'); ?></a></p>
</div>
<?php
}
wp_reset_postdata();
}
?>
</div>
然后我从用户那里获取输入并将其解码以推送到数据库。
<input type="text" placeholder="Enter your postcode" class="orange find input" id="address">
<button id="submit" class="find sub orange">Search</button>
function geocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('address').value;
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
$.ajax({
url: "../link/to/post.php",
type: "POST",
data : {
lat: lat,
lng: lng
}
});
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location,
title: 'Your location'
});
}
});
}
数据按应有的方式推送到数据库中,需要额外的代码并添加标记。但是,当页面刷新时,即使数据库中的数据是立即插入的,也需要再次刷新才能获取新数据。
我尝试了不同的刷新,但都没有解决问题。
我的解决方案之一是找到一种刷新页面两次的方法,但这不够有效,因为我必须加载数百个标记。
最佳答案
我回答了我的问题。
问题是,据我猜测,SQL 查询的运行速度比刷新页面的速度慢。
为了解决这个问题,我添加了延迟。
关于javascript - 页面不刷新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45955503/