2017-10-16 3 views
-1

지난 한 주 동안이 문제를 둘러 보았고 실제로 해결 방법을 찾지 못했습니다. 나는 간단한 것을 놓치고있는 것을 알고 있으며 새로운 데이터 세트를 게시하기 전에 각 기존 마커를 반복하여 루프를 제거해야한다고 생각합니다.Ajax 성공 마커 및 infoWindows 업데이트

목표 : 페이지로드시 초기 마커 세트 및 정보창을로드하십시오. ajax를 통해 검색된 새 데이터에 마커 및 정보 윈도우를 업데이트하고 새 경계를 설정합니다.

초기로드는 문제가되지 않으며 초기 맵 마커 및 정보 윈도우와 동일한 서식을 가진 데이터 세트를 사용하여 아약스를 통해 새로운 배열 세트를 반환합니다. 내 생각은 초기 맵로드에 동일한 함수를 사용하고 새 데이터 배열을 동일한 함수에 전달하여 맵을 업데이트하는 것이 었습니다. 데이터가 전달되었지만 아직 데이터를 제거하거나 업데이트 할 수 없습니다.

이론적으로이 문제를 해결할 수있는 방법인가요? 그렇다면 기존 마커를 제거하고 '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); 
    } 
} 
+1

자 이제 마커를 업데이트하는 방법 – douxsey

+0

EDIT - newMarkers 및 newInfoWindowContent를 만드는 함수를 추가했습니다. 이 함수는 ajax 요청이 성공하면 시작됩니다. 기본적으로 필터를 결과 집합에 적용하고 반환하면 목록 (이 경우지도)에 대한 새 배열을 만들기위한 데이터가 제공됩니다. – riverecho

+0

응답을 추가 했습니까? – douxsey

답변

1

문제는 당신이 applyFilterMap 당신이 배열 (그래서이 아니 배열)의 표현이 문자열로 newMarkers를 정의와 당신의 initilize 방법에 당신 배열이 반복 될 때까지 기다리는 중입니다. newInfoWindowContent와 동일한 문제입니다. 이런 코드를 사용해보십시오.

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

그리고 newInfoWindowContent에 똑같은 것을 적용하십시오. 그것은 몇 가지 청소 여기

UPDATE

와 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'); 

} 
+0

오늘 밤, 러그 라트가 잠자리에 들고 나서 약 1 시간 만에 이걸 쐈습니다. 그러나 원래 페이지로드에서 새 아약스 데이터로 마커를 '다시 추가'해야한다고 생각합니다. 내가 전에 읽은 것에서, 나는 그들을 제거하는 것에 대해 뭔가를 놓치고있다. 그러나, 나는 이것을 여기에서 곧 발사 할 것이다 - 정말로 고마워! – riverecho

+0

douxsey 감사합니다! 여기서 여러 가지 기능을 사용할 수 있지만 루트 문제를 바로 처리 할 수있었습니다.나는 이것보다 더 잘 알고 있으며, 내가 그 배열을 만드는 과정에서 무엇을하고 있는지보아야했다. 정말 고맙습니다! – riverecho