2013-12-25 5 views
0

У меня есть страница, в которой у меня есть несколько ссылок, которые должны открывать диалоги jquery-ui с картами google. Поскольку я загружаю координаты из пользовательских полей Wordpress, я выводю координаты в атрибутах rel-данных, чтобы я мог их собрать с помощью jQuery. Все работает, карты инициализируются, но я не могу прикрепить слушателя к объекту карты в массиве карт.Не удается получить доступ к карте google в массиве

Я делаю это, как этот

HTML:

<div class="mapalokacija"> 
    <a title="Gde se nalazimo?" rel="addon-map-<?php echo $counter;?>" class="showmap" data-rel-lat='<?php echo $lat;?>' data-rel-long='<?php echo $long;?>' href='#map-<?php echo $counter;?>'>map</a> 
<div class="modal" id="map-<?php echo $counter;?>"> 
<div id="addon-map-<?php echo $counter++;?>" style="width:400;height:400px;margin:10px auto;"></div> 
</div> 

JS

var title = '<?php the_title();?>'; 
window.maps = new Array(); 

$(document).ready(function(){ 

    var cdc = 0; 
    $('.showmap').each(function(){ 


     var popup = $(this).attr('href'); 
     var lt = $(this).attr('data-rel-lat'); 
     var ll = $(this).attr('data-rel-long'); 
     var dv = $(this).attr('rel'); 
     console.log(popup,lt,ll,dv,cdc); 
     cdc++; 
     addonMap(lt,ll,dv); 


    }); 
}); 
$(window).load(function(){ 
    var counter = 0; 
    $('.showmap').each(function(){ 


     $('.modal').dialog({ 
      title: 'Gde se nalazimo?', 
      autoOpen: false, 
      width: 500, 
      height: 500, 
      resizeStop: function(event, ui) {google.maps.event.trigger(window.maps[counter], 'resize') }, 
      open: function(event, ui) {google.maps.event.trigger(window.maps[counter], 'resize');} 

     }); 
     google.maps.event.addListener(maps[counter], 'idle', function(){ google.maps.event.trigger(window.maps[counter],'resize');}); 
     counter++; 

    }); 
}); 


function addonMap(lat,lng,div,ccc) { 

    var lat = parseFloat(lat); 
    var lng = parseFloat(lng); 

    var latLang = new google.maps.LatLng(lat,lng); 

    var mapOptions = { 
     scrollwheel: false, 
     navigationControl: false, 
     mapTypeControl: true, 
     scaleControl: false, 
     zoomControl: true, 
     draggable: true, 
     center: new google.maps.LatLng(lat,lng), 
     zoom: 12, 
     mapTypeId: google.maps.MapTypeId.ROADMAP, 
    }; 



    var mapstring = div; 
    var lmap = new google.maps.Map(document.getElementById(mapstring),mapOptions);   

    var marker = new google.maps.Marker({ 
     position: latLang, 
     map: lmap, 
     title: title 
    }); 

    window.maps.push(lmap); 


} 


$('.showmap').click(function(e){ 
    e.preventDefault(); 
    var popup = $(this).attr('href'); 
    var lt = $(this).attr('data-rel-lat'); 
    var ll = $(this).attr('data-rel-long'); 
    var cc = $(popup).attr('rel'); 
    cc = +cc; 
    console.log(cc); 
    $(popup).dialog('open'); 
    google.maps.event.trigger(maps[cc], 'resize'); 


}); 

Живой пример:

One map Multiple Maps

+0

Почему ты хотел слушать 'idle' события? – sabotero

+0

Итак, я могу изменить размер моей карты внутри div –

+0

, чтобы посмотреть на мой ответ ниже. – sabotero

ответ

1

Я смотрю ваши живые примеры, и у вас есть несколько ошибок в коде, но в основном причина, по которой ваши карты не изменяются, - это то, что ваши css не определены правильно, и вы не фокусируетесь в том случае, если вы должны слушать и в вам нужно вызвать событие resize на карте.

Для этого вам необходимо вызвать событие resize на карте в событии open объекта dialog.

Слушайте idle события карты, чтобы вызвать resize события не будет работать как idle событие: срабатывает, когда карта становится неактивной после панорамирования или масштабирования. Как вы можете видеть здесь Google Maps API Reference/Map. Таким образом, событие idle не активируется, когда карта готова.

Для простоты вы можете использовать только один диалог и одну карту и привязать маркер, полилинию, infoWindow ..., которую хотите показать при открытии диалога.

Рассмотрим следующий пример работоспособной и рассмотрим также логику, немного проще и eaiser реализовать:

<!DOCTYPE html> 
<html> 
<head> 
    <title>Multiple Maps on Popup demo </title> 
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDYeeEtBV1zi5IOTKYz4WBD2UO0U3fuVcg&sensor=false"></script> 
    <!-- jQuery UI CSS --> 
    <link rel="stylesheet" href="//code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> 
    <!-- jQuery --> 
    <script src="//code.jquery.com/jquery-1.9.1.js"></script> 
    <!-- jQuery UI js --> 
    <script src="//code.jquery.com/ui/1.10.3/jquery-ui.js"></script> 

    <style type="text/css"> 
     html, body { height: 100%; margin: 0; padding: 0; } 
     .map-container { height: 100%; width: 100%; min-width: 500px; min-height: 300px; } 
     .dialog {} 
     .btn-dialog{} 
    </style> 
</head> 
    <body> 
     <div> 
      <!-- buttons conveniently named as 'btn-dialog-n' where 'n' is the index of the dialog the button will open --> 
      <button id="btn-dialog-0" class="btn-dialog">Open Dialog 0</button> 
      <button id="btn-dialog-1" class="btn-dialog">Open Dialog 1</button> 
      <button id="btn-dialog-2" class="btn-dialog">Open Dialog 2</button> 
      <button id="btn-dialog-3" class="btn-dialog">Open Dialog 3</button> 
      <button id="btn-dialog-4" class="btn-dialog">Open Dialog 4</button> 
     </div> 
     <div> 
      <!-- divs (being dialogs) conveniently named as 'dialog-n' where 'n' is the index of the dialog --> 
      <div id="dialog-0" class="dialog"> 
       <div id="map-container-0" class="map-container"></div> 
      </div> 
      <div id="dialog-1" class="dialog"> 
       <div id="map-container-1" class="map-container"></div> 
      </div> 
      <div id="dialog-2" class="dialog"> 
       <div id="map-container-2" class="map-container"></div> 
      </div> 
      <div id="dialog-3" class="dialog"> 
       <div id="map-container-3" class="map-container"></div> 
      </div> 
      <div id="dialog-4" class="dialog"> 
       <div id="map-container-4" class="map-container"></div> 
      </div> 
     </div> 
     <script language="javascript"> 
      // maps array --> does not have to be direcly declared as window.maps as it will 'put itself' in the global object (aka window) 
      var maps = []; 

      // you can do all what you was wanting to do in only this DOM ready handler event. 
      $(document).ready(function() { 

       //Google Maps 
       var mapOptions = { 
        zoom: 8, 
        center: new google.maps.LatLng(-34.397, 150.644), 
        mapTypeId: google.maps.MapTypeId.ROADMAP 
       }; 
       // initialize the maps and store them in 'maps' array 
       $(".map-container").each(function(){ 
        var map = new google.maps.Map(this, mapOptions); 
        maps.push(map); 
       }); 


       // Dialogs 
       // initialize the dialogs 
       $(".dialog").dialog({ 
        autoOpen: false, 
        height: 500, 
        width: 700, 
        modal: true, 
        open: function() { 
         // get the current dialog being opend and then get the 'id' attribut that has a simply convetion 'dialog-n' where 'n' is the index of the dialog 
         var $this = $(this), 
          index = $this.attr("id").split('-')[1]; 
         // so that i can trigger the 'resize' event in the correct 'map' object 
         google.maps.event.trigger(maps[index], "resize"); 
        }, 
        close: function() { 
         console.log("close"); 
        } 
       }); 

       // initialize the buttons 
       $(".btn-dialog").button() 
        // bind the click event to each button 
        .click(function() { 
         console.log(this); 
         console.log($(this)); 
         // get the current 'button' which the user is clicking to, 
         var $this = $(this), 
          // then get the 'id' attribute that has a simply convention 'btn-dialog-n' where 'n' is the index of the dialog the button will open 
          index = $this.attr("id").split('-')[2]; 
         // then I can open the correct dialog 
         $("#dialog-" + index).dialog("open"); 
        }); 
      }); 
     </script> 
    </body> 
</html> 
+0

Не могу поверить, что это было «просто» :) Большое спасибо за вашу помощь. Я реализую ваш код, и я посмотрю, как это происходит с маркерами. Еще раз спасибо –

+1

Я рад, что помог вам! – sabotero

+0

Могу я попросить вас снова взглянуть на несколько страниц? Он работает так, как должен, я просто задаюсь вопросом, эффективен он или может быть лучше? :) –

Смежные вопросы