2015-01-24 5 views
0

Я пытаюсь создать карту с маркерами, расположение и содержимое этих маркеров хранятся в базе данных.Loop with PHP + JavaScript

Здесь мой код:

<?php 

$query_map = "SELECT * FROM denuncias ORDER BY id"; 
$map_executa = mysql_query($query_map); 
$lat = -1.456688; 
$log = -48.477586; 

?> 
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> 
     <script type="text/javascript"> 
     //<![CDATA[ 

     var map; 


     var center = new google.maps.LatLng(<?= $lat ?>, <?= $log ?>); 

     function init() { 

      var mapOptions = { 
       zoom: 13, 
       center: center, 
       mapTypeId: google.maps.MapTypeId.ROADMAP 
      } 

      map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); 


      <?php while ($map = mysql_fetch_object($map_executa)) { ?> 
        var contentString = '<div id="content" style="height: 200px;">'+ 
     '<div id="siteNotice">'+ 
     '</div>'+ 
     '<h3 id="firstHeading" class="firstHeading"><?= $map->titulo ?></h3>'+ 
     '<div id="bodyContent">'+ 
     '<?= $map->descricao ?>'+ 
     '</div>'+ 
     '</div>'; 

var infowindow = new google.maps.InfoWindow({ 
     content: contentString, 
     maxWidth: 400 
    }); 


       var marker = new google.maps.Marker({ 
     position: new google.maps.LatLng(<?= $map->lat ?>, <?= $map->log ?>), 
     map: map, 
     clickable: true, 
     title: 'teste' 
    }); 
       google.maps.event.addListener(marker, 'click', function() { 
    infowindow.open(map,marker); 
    }); 

       <?php } ?> 

     } 
     google.maps.event.addDomListener(window, 'load', initialize); 
     //]]> 
     </script> 

Я смог получить маркеры в правильных позициях, но содержание всегда одинаково: последняя строка. Может ли кто-нибудь мне помочь? Спасибо!

Поставленные Исходный код:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/> 
    <title>Ver denúncias</title> 

    <!-- CSS --> 
    <style type="text/css"> 
    body { 
     background: #3f51b5 !important; 
    } 
    </style> 
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> 
     <script type="text/javascript"> 
     //<![CDATA[ 

     var map; 


     var center = new google.maps.LatLng(-1.456688, -48.477586); 

     function init() { 

      var mapOptions = { 
       zoom: 13, 
       center: center, 
       mapTypeId: google.maps.MapTypeId.ROADMAP 
      } 

      map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); 


           var contentString = '<div id="content" style="height: 200px;">'+ 
     '<div id="siteNotice">'+ 
     '</div>'+ 
     '<h3 id="firstHeading" class="firstHeading">Nanana</h3>'+ 
     '<div id="bodyContent">'+ 
     'Teste'+ 
     '</div>'+ 
     '</div>'; 

var infowindow = new google.maps.InfoWindow({ 
     content: contentString, 
     maxWidth: 400 
    }); 


       var marker = new google.maps.Marker({ 
     position: new google.maps.LatLng(-1.458780, -48.480526), 
     map: map, 
     clickable: true, 
     title: 'teste' 
    }); 
       google.maps.event.addListener(marker, 'click', function() { 
    infowindow.open(map,marker); 
    }); 

           var contentString = '<div id="content" style="height: 200px;">'+ 
     '<div id="siteNotice">'+ 
     '</div>'+ 
     '<h3 id="firstHeading" class="firstHeading">Teste 2</h3>'+ 
     '<div id="bodyContent">'+ 
     'AAAAAAAAAAAAAAAAAAA'+ 
     '</div>'+ 
     '</div>'; 

var infowindow = new google.maps.InfoWindow({ 
     content: contentString, 
     maxWidth: 400 
    }); 


       var marker = new google.maps.Marker({ 
     position: new google.maps.LatLng(-1.471875, -48.494237), 
     map: map, 
     clickable: true, 
     title: 'teste' 
    }); 
       google.maps.event.addListener(marker, 'click', function() { 
    infowindow.open(map,marker); 
    }); 


     } 
     google.maps.event.addDomListener(window, 'load', initialize); 
     //]]> 
     </script> <link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/> 
    <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/> 
</head> 
<body onload="init();"> 
    <nav class="indigo no-pad-bot" role="navigation"> 
    <div class="container" class="parallax-container"> 
     <div class="nav-wrapper"><a id="logo-container" href="#" class="brand-logo"></a> 
     <ul id="nav-mobile" class="right side-nav no-pad-bot"> 
      <li><a href="#">Início</a></li> 
      <li><a href="#" class="disabled">Ver denúncias</a></li> 
      <a class="waves-effect waves-light btn-large fazerdenuncia" style="margin-top: 5px; float: right !important">Fazer denúncia</a> 
     </ul><a href="#" data-activates="nav-mobile" class="button-collapse"><i class="mdi-navigation-menu"></i></a> 
     </div> 
    </div> 
    </nav> 

<div class="section no-pad-bot no-pad-top white" id="index-banner"> 
<div class="row"> 
<div class="col s12 m8"> 
     <h1>Places to check out in Zagreb</h1> 

     <section id="sidebar"> 
      <div id="directions_panel"></div> 
     </section> 

     <section id="main"> 
      <div id="map_canvas" style="width: 100%; height: 500px;"></div> 
     </section> 
</div> 
<div class="col s12 m4 barra flow-text"> 
<h1> 
Últimas denúncias 
</h1> 
    <!-- últimas denuncias --> 
<div class="row"> 
<div class="col s10 m10 offset-s1 offset-m1 z-depth-2 grey lighten-3" id="ultimas-denuncias"> 
    <h2 class="flow-text"> 
Nanana </h2> 
<h2 class="flow-text"> 
Teste 2 </h2> 
</div> 
</div> 

<div class="col s10 m10 offset-s1 offset-m1"> 
<p class="ultimos120">Nos últimos 120 dias</p> 
<div class="text-center"> 
<h5 class="flow-text">55 denúncias feitas</h5> 
<h5 class=" flow-text">25 denúncias resolvidas</h5> 
</div></div> 
<!-- fim últimas denúncias --> 
</div> 
</div> 
    </div> 

    <footer class="page-footer grey lighten-2"> 
    <div class="container"> 
     <div class="row"> 
     <div class="col l6 s12"> 
      <h5 class="black-text">Sobre este site</h5> 
      <p class="black-text text-lighten-1"> 
      Esse site é mantido estudantes do ensino médio para lallalallala. <br> Caso queira contribuir para o projeto, clique <a href="doacao.html">aqui</a> para fazer uma doação. 
      </p> 


     </div> 
     <div class="col l3 s12"> 
      <h5 class="black-text">Links úteis</h5> 
      <ul> 
      <li><a class="black-text" href="#!">Link 1</a></li> 
      <li><a class="black-text" href="#!">Link 2</a></li> 
      <li><a class="black-text" href="#!">Link 3</a></li> 
      <li><a class="black-text" href="#!">Link 4</a></li> 
      </ul> 
     </div> 

     </div> 
    </div> 
    <div class="footer-copyright"> 
     <div class="container"> 
    <span class="black-text">Feito por</span> <a class="pink-text" href="http://www.mat3.us">mat3.us</a> 
     </div> 
    </div> 
    </footer> 


    <!-- Scripts--> 
    <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> 
    <script src="js/materialize.js"></script> 
    <script src="js/init.js"></script> 

    </body> 
</html> 

Got сделать появляются 2 текстов, однако, оба из них появляется на тот же маркер!

<?php 

$query_map = "SELECT * FROM denuncias ORDER BY id"; 
$map_executa = mysql_query($query_map); 
$lat = -1.456688; 
$log = -48.477586; 
$Count = 0; 
$i = 0; 

?> 
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> 
     <script type="text/javascript"> 
     //<![CDATA[ 

     var map; 


     var center = new google.maps.LatLng(<?= $lat ?>, <?= $log ?>); 

     function init() { 

      var mapOptions = { 
       zoom: 13, 
       center: center, 
       mapTypeId: google.maps.MapTypeId.ROADMAP 
      } 

      map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); 


      <?php while ($map = mysql_fetch_object($map_executa)) { 
       ++$Count; ?> 

        var contentString<?= $Count ?> = '<div id="content" style="height: 200px;">'+ 
     '<div id="siteNotice">'+ 
     '</div>'+ 
     '<h3 id="firstHeading" class="firstHeading"><?= $map->titulo ?></h3>'+ 
     '<div id="bodyContent">'+ 
     '<?= $map->descricao ?>'+ 
     '</div>'+ 
     '</div>'; 

var infowindow = new google.maps.InfoWindow({ 
     content: contentString<?= $Count ?>, 
     maxWidth: 400 
    }); 
    var infowindow1 = new google.maps.InfoWindow({ 
     content: contentString1, 
     maxWidth: 400 
    }); 


       var marker = new google.maps.Marker({ 
     position: new google.maps.LatLng(<?= $map->lat ?>, <?= $map->log ?>), 
     map: map, 
     clickable: true, 
     title: 'teste' 
    }); 
          <?php } ?> 
       google.maps.event.addListener(marker, 'click', function() { 
       // Aqui!!! 

    infowindow.open(map,marker); 
    infowindow1.open(map,marker); 
    infowindow2.open(map,marker); 

    }); 



     } 
     google.maps.event.addDomListener(window, 'load', initialize); 
     //]]> 
     </script> 

Я сделал что-то не так?

+0

Whats доставленного исходного кода? Можете ли вы отправить код, который показывает ваш браузер –

+0

Конечно. Я собираюсь отредактировать его. Я думаю, это потому, что var имеет одно и то же имя! В любом случае, я могу это исправить? –

ответ

1

Попробуйте первой выборки объекта, а затем сделать foreach Loop:

<?php 
$Count = 0; 
$map = mysql_fetch_object($map_executa) : 
foreach($map as $marker)) { 
++$Count; //This adds 1 to Count every time ?> 
        var contentString = '<div id="content" style="height: 200px;">'+ 
     '<div id="siteNotice">'+ 
     '</div>'+ 
     '<h3 id="firstHeading" class="firstHeading"><?= $marker->titulo ?></h3>'+ 
     '<div id="bodyContent">'+ 
     '<?= $marker->descricao ?>'+ 
     '</div>'+ 
     '</div>'; 

var infowindow = new google.maps.InfoWindow({ 
     content: contentString, 
     maxWidth: 400 
    }); 


       var marker = new google.maps.Marker({ 
     position: new google.maps.LatLng(<?= $marker->lat ?>, <?= $marker->log ?>), 
     map: map, 
     clickable: true, 
     title: 'teste' 
    }); 
       google.maps.event.addListener(marker, 'click', function() { 
    infowindow.open(map,marker); 
    }); 
      <?php } ?> 

Еогеасп Loop имеет лучшую производительность тоже. См. http://php.net/manual/en/control-structures.foreach.php для получения дополнительной информации.

Edit: Вы должны Параметры:

1) Создать новую переменную каждый раз; Вам просто нужно Count:

var infowindow<?php echo count;?> = new google.maps.InfoWindow({ 
     content: contentString, 
     maxWidth: 400 
    }); 

2) Использование массива: (Im не exactlly конечно о массиве Синтаксис в JS)

infowindow() = new google.maps.InfoWindow({ 
     content: contentString, 
     maxWidth: 400 
    }); 

, а затем вызвать окно с

google.maps.event.addListener(count, marker, 'click', function() { 
    infowindow(count).open(map,marker); 
    }); 

Вам нужно создать массив для маркеров не только для infowindows

+0

Карта даже не открыта ... Я просто не знаю, почему lol –

+0

Вы только что скопировали мой код? Я, конечно, не проверял его, поэтому может возникнуть проблема с синтаксисом. Но, как сказал чандра, проблема, скорее всего, будет в вашем Javascript. –

+0

Я изменил его, но он не сработал ... ну, все равно добавить новые переменные в каждый цикл? –

0

При создании информационного окна ob ject для каждой итерации, он всегда отображает последнее значение, потому что оно переопределяет объект. Попробуйте поместить код ниже цикла while и сообщите мне, есть ли у вас какие-либо проблемы.

var infowindow = new google.maps.InfoWindow({ 
     content: contentString, 
     maxWidth: 400 
    });     

Спасибо

+0

Привет! Это не работает ... Есть ли возможность поместить этот var внутри цикл и добавить число каждый раз? Я имею в виду var infowindow var infowindow2 ... –

+0

Вы можете каждый раз создавать массив и записывать новую запись –