【问题标题】:Ajax success updates markers and infoWindowsAjax 成功更新标记和 infoWindows
【发布时间】:2018-03-28 13:08:04
【问题描述】:

在过去的一周里,我一直在研究这个问题,但还没有找到可行的解决方案。我知道我遗漏了一些简单的东西,我认为我需要遍历每个现有标记以删除它们,然后再发布新数据集。

目标: 在页面加载时加载一组初始标记和 infoWindows。更新通过 ajax 检索到的新数据的标记和 infoWindows 并设置新边界。

初始加载没有问题,我通过 ajax 返回一组新数组,其数据集与初始地图标记和 infoWindows 具有相同的格式。我的想法是对初始地图加载使用相同的函数,然后简单地将新数据数组传递给相同的函数以更新地图。数据通过了,但我还不能删除或更新数据。

理论上,这是一种可以接受的解决方法吗?如果是这样,我将如何删除现有标记并从“newMarkers”和“newInfoWindowContent”放置更新的标记。

如果有更好的方法可以做到这一点,请...我全神贯注!我开始制作小提琴,但想先获得有关该程序的反馈,因为我觉得它很臃肿并且可以简化。

提前感谢大家!

= = = = =

jQuery(function($) {
  // Asynchronously Load the map API 
  var script = document.createElement('script');
  script.src = "//maps.googleapis.com/maps/api/js?key=AIzaSyAqb3fT3SbMSDMggMEK7fJOIkvamccLrjA&callback=initialize";
  document.body.appendChild(script);
});

function applyFilterMap (cabins) {

  // Loop through old markers and set map to null for each.
  // This is not working.
  setMapOnAll(null); 

  markers = []
  //console.log(markers)


  // Build the array of new markers from filtered results.
  newMarkers = '';
  newMarkers += '[';
  $.each(cabins, function(i, cabin) {
    newMarkers += '[\''+ cabin.name + '\', ' + cabin.latitude + ', ' + cabin.longitude +'],'
  });
  newMarkers = newMarkers.slice(0, -1);
  newMarkers += ']';

  // Build the array of new infoWindowContent from filtered results.
  newInfoWindowContent = '';
  newInfoWindowContent += '[';
  $.each(cabins, function(i, cabin) {
    newInfoWindowContent += '[\'<div class="property clearfix"><div class="image"><div class="content"><a href="'+ cabin.listing_url + '" onclick="ga(\'send\', \'event\', \'Destination-Listing\', \'Map - Photo\', \'' + cabin.destination + ' - ' + cabin.name + '\', 1);"><i class="fa fa-external-link"></i></a><img src="' + cabin.image_url + '" alt="' + cabin.name + '" class="img-responsive" onload="ga(\'send\', \'event\', \'Impression-MapPin\', \'' + cabin.property.destination.slug + '\', \'' + cabin.cabinid + '\', 1);"><span class="label-sleeps"><i class="fa fa-group"></i> ' + cabin.maxguests + '</span> <span class="label-price">$'+ cabin.minrate + '</span></div></div><div class="property-detail"><h5 class="title"><a href="' + cabin.list_url + '" onclick="ga(\'send\', \'event\', \'Destination-Listing\', \'Map - Name\', \'' + cabin.destination + ' - ' + cabin.name + '\', 1);">' + cabin.name + '</a></h5><h5>' + cabin.property.org.name + '</h5></div></div>\'],'
  });
  newInfoWindowContent = newInfoWindowContent.slice(0, -1);
  newInfoWindowContent += ']';

  // console.log(newMarkers);
  // console.log(newInfoWindowContent);  

  initialize(newMarkers, newInfoWindowContent);

  // Display the Map after it has been filtered and updated.
  // $('#destinationMap_wrapper').html('<h3>New Map Here</h3>');
  $('#sizeMap').fadeIn('fast');
  $('#destinationMap_wrapper').fadeIn('fast');

} // END applyFilterMap() Function.

/// Initialize Map for initial load.
function initialize(newMarkers, newInfoWindowContent) {

var map;
var bounds = new google.maps.LatLngBounds();

var mapOptions = {
    mapTypeId: 'roadmap',
};

// Create Markers
if(newMarkers) {
  markers = newMarkers;
} else {
  markers = [
    ['The Encantado', 40.38917970, -105.46607810],
    ['Valhalla', 40.35821830, -105.56307860],
    ['Mountain Side', 40.39301450, -105.43687520],
  ];
}

// Info Window Content
if(newInfoWindowContent) {
  infoWindowContent = newInfoWindowContent;
} else {
  infoWindowContent = [
    ['<h3>The Encantado Info</h3>'],
    ['<h3>Valhalla Info</h3>'],
    ['<h3>Mountain Side Info</h3>']
  ];
}

// Display map on the page
map = new google.maps.Map(document.getElementById("destinationMap_canvas"), mapOptions);

// Display markers on map
var infoWindow = new google.maps.InfoWindow(), marker, i;

// Loop through our array of markers & place each one on the map  
for( i = 0; i < markers.length; i++ ) {
    var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
    bounds.extend(position);
    marker = new google.maps.Marker({
        position: position,
        map: map,
        title: markers[i][0]
    });

    // Create info window for each marker    
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
            infoWindow.setContent(infoWindowContent[i][0]);
            // map.setCenter(marker.getPosition());
            infoWindow.open(map, marker);
        }
    })(marker, i));

    // Automatically center the map fitting all markers on the screen
    map.fitBounds(bounds);
}

// Override our map zoom level once our fitBounds function runs.
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
    google.maps.event.removeListener(boundsListener);
});

}

function setMapOnAll(map1) {
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(map1);
  }
}

【问题讨论】:

  • 好的,现在你如何更新你的标记
  • EDIT - 我添加了创建 newMarkers 和 newInfoWindowContent 的函数。该函数在 ajax 请求成功时触发。我们基本上是对一组结果应用过滤器,然后返回为我们提供数据来为列表(在本例中为地图)构建新数组。
  • 我添加了回复你看到了吗
  • 我在发布的代码中出现 javascript 错误:Uncaught ReferenceError: setMapOnAll is not defined
  • 我刚刚添加了 setupMapOnAll() 函数。我觉得这就是我所缺少的。在某个地方我“认为”我需要在初始页面加载时设置标记,以便我可以删除它们,然后用新数据重置它们。

标签: javascript jquery ajax google-maps-api-3


【解决方案1】:

问题在于您的 applyFilterMap 您将 newMarkers 定义为具有数组表示形式的字符串(因此它不是数组),而在您的 initilize 方法中您正在等待数组循环。 newInfoWindowContent 也是同样的问题。你可以试试这样的代码

    newMarkers = [];
  $.each(cabins, function(i, cabin) {
    newMarkers.push([ ''+cabin.name ,  cabin.latitude , cabin.longitude])
  });

并为 newInfoWindowContent 应用相同的内容。但是代码会让所有的 div 都是一团糟 尝试使用简单的文本进行测试,如果它有效,则应用您的 html 并进行一些清理

更新

这是您方法的一个可能版本

    function applyFilterMap (cabins) {

  // Loop through old markers and set map to null for each.
  // This is not working.
  //setMapOnAll(null);

  markers = []
  //console.log(markers)


  // Build the array of new markers from filtered results.
  newMarkers = [];
  $.each(cabins, function(i, cabin) {
    newMarkers.push([ ''+cabin.name ,  cabin.latitude , cabin.longitude])
  });

  // Build the array of new infoWindowContent from filtered results.
  newInfoWindowContent = []
  $.each(cabins, function(i, cabin) {
    var oneArray = ['<h3>'+cabin.name+'</h3>'];
    newInfoWindowContent.push(oneArray);
  });

  // console.log(newMarkers);
  // console.log(newInfoWindowContent);

  initialize(newMarkers, newInfoWindowContent);

  // Display the Map after it has been filtered and updated.
  // $('#destinationMap_wrapper').html('<h3>New Map Here</h3>');
  $('#sizeMap').fadeIn('fast');
  $('#destinationMap_wrapper').fadeIn('fast');

}

【讨论】:

  • 今晚我会在小地毯上床睡觉后试一试——大约一个小时后。但是,我仍然觉得我需要从原始页面加载到新的 ajax 数据中“删除”和“重新添加”标记。从我之前读过的内容来看,我错过了一些关于删除它们的东西。不过,我很快就会在这里试一试 - 非常感谢!
  • 谢谢你!这里有多种功能在起作用,但您能够直接解决根本问题。我比这更了解,应该知道我在创建这些数组时做了什么。非常感谢!
猜你喜欢
  • 2019-10-19
  • 1970-01-01
  • 2017-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多