2013-01-18 3 views
1

나는 현재 검색 결과을 표시하는 페이지가 있습니다. 사용자가 결과를 클릭하면 세부 정보이 ajax를 사용하여 가져와 페이지에로드됩니다. 이러한 세부 정보에는 Google지도가 있습니다.비동기 적으로 여러 Google지도 표시

이전에는 세부 정보 페이지에 콜백이 포함 된 Gmaps 스크립트가있었습니다. 그러나 사용자가 여러 결과를 클릭하면 Gmaps 스크립트가 여러 번 삽입되는 문제가 발생했습니다.

이제 결과 페이지에 스크립트를로드하고 세부 정보 페이지는 필요한 모든 매개 변수를 전달하면서 초기화 함수를 호출합니다. 하지만 undefined is not a function 오류가 발생합니다.

내 질문은 : Gmaps 스크립트, 콜백 및 비동기 두 페이지 (결과 및 세부 사항) 간의 맵 초기화 구조는 어떻게됩니까?

결과 페이지

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key=[key]"></script> 

function initialize(params) { 
var directionsService, directionsDisplay, map; 

directionsService = new google.maps.DirectionsService(); 
directionsDisplay = new google.maps.DirectionsRenderer(); 

// your typical gmaps stuff 

} 

세부 정보 페이지

<div id="map_canvas"></div> 

initialize(params); 
+0

가능한 중복 [정의되지 않은 비동기 Google지도 API v3의이 함수가 아닙니다 (http://stackoverflow.com/questions/14184956/async-google-maps-api-v3- undefined-is-not-a-function) –

+0

하나의지도를로드하는 것은 문제가되지 않습니다 (콜백 추가). 확실하지 않은 점은 "이 페이지에 Google Maps API를 여러 번 포함 시켰습니다"라는 오류 메시지없이 반복적으로 gmaps의'콜백 '을 사용하는 방법입니다. – greener

+1

'google.maps'가 있는지 확인하십시오. 존재할 때 간단히 initialize를 호출하십시오. 그렇지 않다면 로더를 사용하십시오. –

답변

2

구글지도의 스크립트가 이미 추가됩니다은 "구글"전역 변수를 확인하여로드 된 경우 그냥 볼 수 있습니다 DOM에.

Full jsfiddle example here: http://jsfiddle.net/gavinfoley/yD8Qt/.

// dom ready 
 
    $(function() { 
 
     if (typeof google === "undefined") { 
 
      alert("Lazy loading Google maps"); 
 
      lazyLoadGoogleMaps(); 
 
     } else {     
 
      alert("Google Maps is already loaded"); 
 
      googleMapsLoaded(); 
 
     } 
 
    }); 
 

 
    function lazyLoadGoogleMaps() { 
 
     // Note the callback function name 
 
     $.getScript("http://maps.google.com/maps/api/js?sensor=true&callback=googleMapsLoaded") 
 
     .done(function (script, textStatus) {    
 
      alert("Google maps loaded successfully"); 
 
     }) 
 
     .fail(function (jqxhr, settings, ex) { 
 
      alert("Could not load Google Maps: ", ex); 
 
     }); 
 
    } 
 

 
    // This function name is passed in to the Google maps script load above 
 
    // and will be called once Google maps has loaded 
 
    function googleMapsLoaded() {   
 
     alert("Done!"); 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

+0

DrMolle의 의견을 통해 문제를 해결할 수 있었지만 답변은 매우 좋습니다. 실제로'$ .getScript'에 소개해 주셔서 감사합니다. – greener

+0

걱정할 필요가 없습니다! '$ .getax'는'$ .ajax'의 약식 래퍼입니다.하지만 여러분이하고있는 일을 더 잘 읽고 더 잘 볼 수 있기를 좋아합니다. – GFoley83

관련 문제