我有一个AJAX函数,可以通过某个角色来按用户查询帖子,这很好并且可以工作,但是问题是我试图在AJAX完成并查询帖子后刷新Google Maps上的标记。
在我的AJAX调用中,我将结果的html输出输入到div中,我试图使地图基本识别并识别该div中的结果,并根据该div中的结果更新标记。
例如,当页面加载时,地图上最初有18个结果,而当AJAX调用完成时,本来有3个结果,但是当我在AJAX调用后重新初始化地图时,原始的18个结果仍然出现在地图上。
我认为问题可能出在$ each函数或map函数中,因为它没有正确更新标记。当我在每个函数中记录结果的标题时,即使在AJAX调用完成后,所有18个原始结果也都被返回,并且HTML将3个结果输出到结果div中。
我希望我已经足够清楚地解释了我的问题,并希望有人可以帮助我。我将在下面粘贴所有相关代码。
AJAX函数以获取结果:
$('#private').on('click', function(e) {
e.preventDefault();
var owner = $(this).data('owner');
var res = $('.total-matches').data('res');
$('#stm_owner').val(owner);
$('#stm_res').val(res);
$(this).addClass('active');
var data_form = $('.filters').closest('form').serialize();
$.ajax({
url: ajaxurl,
dataType: 'json',
context: this,
data: data_form + '&action=ajax_filter',
beforeSend: function() {
$('.ajax-row').addClass('loading');
},
success: function(data) {
$('.sorting').html(data.html);
$('.map-results').html(data.html);
$('.total-matches span').text(' ' + data.total);
$('.ajax-row').removeClass('loading');
},
complete: function() {
$('.timeago').timeago();
initGoogleMap(markersInfo);
}
});
});
Google地图功能:
var markersInfo = $('.ia-map').map(function() {
var info = {
id: $(this).data('map-id'),
address: $(this).data('map-address'),
title: $(this).data('map-title'),
price: $(this).data('map-price'),
latitude: $(this).data('map-latitude'),
longitude: $(this).data('map-longitude'),
html: "<img src=" + $(this).data('map-image') + ">",
link: $(this).data("map-link"),
contentHtml: "<div class='image'>" + "<img src=" + $(this).data('map-image') + ">" + "</div>" + '<b>' + $(this).data('map-title') + '</b><br>' + "<div class='changeprice'><div style='display: none;' class='currency-selector'></div>" + $(this).data('map-price') + "</div>" + "<br><a href='" + $(this).data("map-link") + "'>More>></a>"
};
return info;
}).get();
var distinctMarkerInfo = [];
markersInfo.forEach(function(item) {
if (!distinctMarkerInfo.some(function(distinct) {
return distinct.id == item.id;
})) distinctMarkerInfo.push(item);
});
initGoogleMap(distinctMarkerInfo);
// GMAP ON SEARCH RESULTS PAGE
function initGoogleMap(markersInfo) {
var mapOptions = {
// zoom: 2,
// center: new google.maps.LatLng(53.334430, -7.736673)
},
bounds = new google.maps.LatLngBounds(),
mapElement = document.getElementById('map_results'),
map = new google.maps.Map(mapElement, mapOptions);
var markerList = []; // create an array to hold the markers
var geocoder = new google.maps.Geocoder();
var iconBase = '../assets/images/';
$.each(markersInfo, function(key, val) {
var marker = new google.maps.Marker({
//map: map,
position: {
lat: parseFloat(val.latitude),
lng: parseFloat(val.longitude)
},
title: val.title,
icon: iconBase + 'single.png',
info: new google.maps.InfoWindow({
content: val.contentHtml
})
});
markerList.push(marker); // add the marker to the list
google.maps.event.addListener(marker, 'click', function() {
marker.info.open(map, marker);
});
var loc = new google.maps.LatLng(val.latitude, val.longitude);
bounds.extend(loc);
});
map.fitBounds(bounds);
map.panToBounds(bounds);
markerCluster = new MarkerClusterer(map, markerList, {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
}
最后是地图html:
<div id="map_results" style="width:100%; height:600px;"></div>
,以及AJAX调用后每个结果输出到结果div中的div
<div class="ia-map" data-price="<?php echo esc_attr($data_price) ?>" data-date="<?php echo get_the_date('Ymdhi') ?>" data-mileage="<?php echo esc_attr($data_mileage); ?>" data-map-id="<?php echo $id; ?>" data-map-address="<?php echo $location; ?>" data-map-title="<?php echo $title; ?>" data-map-price="<?php echo esc_attr($price); ?>" data-map-latitude="<?php echo $lat; ?>" data-map-longitude="<?php echo $lng; ?>" data-map-image="<?php echo esc_url($img[0]); ?>" data-map-link="<?php the_permalink() ?>" <?php if(isset($distance)): ?>data-distance="<?php echo esc_attr(floatval($distance)); ?>"<?php endif; ?>></div>
,最后是结果div本身
<div class="map-results" style="display: none;"></div>
答案 0 :(得分:0)
我所做的事情与您尝试的类似,因此您可以查看我的代码,对其进行修改并将其用于您的目的。
var map;
var elevator;
var markers = [];
function mapinitialize() {
var myOptions = {
zoom: 5,
center: new google.maps.LatLng(23.603296, 81.885962),
mapTypeId: 'roadmap',
styles: [
{
"featureType": "administrative",
"elementType": "geometry",
"stylers": [
{
"color": "#ff8040"
},
{
"weight": 1.5
}
]
},
{
"featureType": "administrative",
"elementType": "labels",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "poi",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "road",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "transit",
"stylers": [
{
"visibility": "off"
}
]
}
]
};
map = new google.maps.Map(document.getElementById('hp-map-js'), myOptions);
}
function mapMark(receivedAddress = '') {
//Loop through all the markers and remove
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
var icon = '/wp-content/themes/sssbv/assets/img/homepage/map/logo-map.png';
var addresses = receivedAddress != '' ? receivedAddress : ['Norway', 'Africa', 'Asia','North America','South America'];
console.log(addresses);
for (var x = 0; x < addresses.length; x++) {
//I am geocoding the coordinates from individual location address.
jQuery.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location;
var latlng = new google.maps.LatLng(p.lat, p.lng);
map.setCenter(data.results[0].geometry.location);
map.setZoom(6);
window.setTimeout(function() {
markers.push( new google.maps.Marker({
position: latlng,
map: map,
animation: google.maps.Animation.DROP,
icon: icon
}));
}, (x+1*200));
});
}
}
jQuery(document).ready(function($) {
var loaded = false;
//This is the part you have to change.
//Instead of on change you will use your ajax output on completion.
$(".location-selector").on('change', '#district-js', function(e){
e.preventDefault();
//Here I am getting the state and district name.
var selectedDistrictVal = $(this).val();
selectedDistrictVal = selectedDistrictVal.replace('-', ' ');
var selectedStateVal = $('.location-selector #state-js').val();
selectedStateVal = selectedStateVal.replace('-', ' ');
if (selectedDistrictVal != '') {
var createdAddress = [];
createdAddress.push(selectedDistrictVal);
mapMark(createdAddress);
}
});
});
答案 1 :(得分:0)
这是我基于您的ajax调用的答案(您只需在代码中进行更改)。
$.ajax({
url: ajaxurl,
dataType: 'json',
context: this,
data: data_form + '&action=ajax_filter',
beforeSend: function(){
$('.ajax-row').addClass('loading');
},
success: function (response) {
//This logs the ajax response.
console.log(response);
$('.sorting').html(response.html);
$('.map-results').html(response.html);
$('.total-matches span').text(' ' + response.total);
$('.ajax-row').removeClass('loading');
var ajaxMarkersInfo = [];
$('.map-results .ia-map').each(function(index, el){
//var ajaxMarker = [];
var mapID = $(this).attr('data-map-id');
var mapAddress = $(this).attr('data-map-address');
var mapTitle = $(this).attr('data-map-title');
var mapPrice = $(this).attr('data-map-price');
var mapLatitude = $(this).attr('data-map-latitude');
var mapLongitude = $(this).attr('data-map-longitude');
var mapHTML = "<img src=" + $(this).attr('data-map-image') + ">";
var mapLink = $(this).attr('data-map-link');
var mapContentHTML = "<div class='image'>" + "<img src=" + $(this).attr('data-map-image') + ">" + "</div>" + '<b>' + $(this).attr('data-map-title') + '</b><br>' + "<div class='changeprice'><div style='display: none;' class='currency-selector'></div>" + $(this).attr('data-map-price') + "</div>" + "<br><a href='" + $(this).attr("data-map-link") + "'>More>></a>";
var ajaxMarker = {
id: mapID,
address: mapAddress,
title: mapTitle,
price: mapPrice,
latitude: mapLatitude,
longitude: mapLongitude,
html: mapHTML,
link: mapLink,
contentHtml: mapContentHTML
};
ajaxMarkersInfo.push(ajaxMarker);
});
console.log(ajaxMarkersInfo);
initGoogleMap(ajaxMarkersInfo);
},
complete: function() {
$('.timeago').timeago();
}
});
这应该对您有用,但为了进行验证,我已在控制台中记录了ajaxMarkersInfo
变量,以便您可以从代码中记录info
变量并进行比较。
我希望这会有所帮助。