2017-09-06 64 views
-1

我想在googlemap上顯示來自mysql的多個標記。來自MySQL數據庫的谷歌地圖上的多個標記不顯示

我的地圖顯示正確,但標記沒有顯示出來。

我有一個PHP腳本,從MySQL中檢索數據。

PHP:

<?php 

    // Include config file 

    require_once 'config.php'; 

    $sql = "SELECT client_address, GPS1, GPS2 FROM client"; 
    $stmt = $mysqli->prepare($sql); 
    if($stmt->execute()){ 
     $result = $stmt->get_result(); 
    } else $stmt->close(); 

    foreach ($result as $key) 
     $locations[]=array('client_address'=>$key['client_address'], 'GPS1'=> $key['GPS1'], 'GPS2'=> $key['GPS2']); 
    $markers = json_encode($locations); 
?> 

$標記:

[{"client_address":"SA294","GPS1":"-34.031300","GPS2":"18.577680"},{"client_address":"SB619","GPS1":"-34.031510","GPS2":"18.575890"}] 

HTML:

<script> 
      <?php 
       echo "var markers=$markers;\n"; 
      ?> 

       function initMap() { 
       var latlng = new google.maps.LatLng(-34.031342, 18.577419); // default location 
       var myOptions = { 
        zoom: 16, 
        center: latlng, 
        mapTypeId: google.maps.MapTypeId.SATELLITE, 
        mapTypeControl: true 
       }; 

      var map = new google.maps.Map(document.getElementById('mapall'),myOptions); 
       var infowindow = new google.maps.InfoWindow(), marker, lat, lng; 
       var json=JSON.parse(markers); 

       for(var i in json){ 

        lat = (json[i].GPS1); 
        lng = (json[i].GPS2); 
        name = (json[i].client_address); 

        marker = new google.maps.Marker({ 
         position: new google.maps.LatLng(lat,lng), 
         name:name, 
         map: map 
        }); 
        google.maps.event.addListener(marker, 'click', function(e){ 
         infowindow.setContent(this.name); 
         infowindow.open(map, this); 
        }.bind(marker)); 
       } 
      } 

      </script> 
      <script async defer 
       src="https://maps.googleapis.com/maps/api/js?key=AIzaSyANS0uqM7qedfDCzPjJ3xoB15vh2DC4Tls&callback=initMap"> 
      </script> 

<div class="row"> 
<div class="col-md-4"> 
<div class="panel panel-primary"> 
<div class="panel-heading"><b>Siqalo Active Units</b></div> 
<div class="panel-body"> 
<div id="mapall" style="width:350px;height:350px;"></div> 
</div> 
</div>  
</div> 
</div> 

我立足很多這樣的: Adding multiple markers on Google Maps from MySQL database

回答

2

你不需要做JSON.parse,你可以循環通過json標記。

for(i = 0; i < markers.length; i++) { 
    lat = (markers[i].GPS1); 
    lng = (markers[i].GPS2); 
    name = (markers[i].client_address); 
0
  <?php 
      echo "var markers=$markers;\n"; 
     ?> 

這就是瘋了。 做這個,而不是,因爲你已經解析JSON字符串這應該工作,看起來更乾淨。

  <script> 

      var markers='<?=$markers;?>'; 


      function initMap() { ... 
+0

標記不顯示是否我這樣做。 – wazzahenry