2016-02-08 33 views
0

我需要在地圖的主頁上顯示muiltiple標記。我在數據庫中存儲每個Travel Flyers的lng和lat,然後顯示每個flyer。 (哪些工作正常),但是當我使用此代碼在我的主頁上顯示它時,它只顯示插入到數據庫中的最後一個經緯度和lng。Google將多個標記與lng和lat進行映射

這裏是我的代碼:

<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBaB_9hgeARViVKIT6O1pFKXRCSuYaol2A&libraries=places&callback=initAutocomplete"></script> 
    <script> 


      jQuery(function($) { 
       // Asynchronously Load the map API 
       var script = document.createElement('script'); 
       script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize"; 
       document.body.appendChild(script); 
      }); 

      function initialize() { 

      @foreach($flyer as $flyers) 
       var lat = {{ $flyers->lat }}; 
       var lng = {{ $flyers->lng }}; 
      @endforeach 

       var map; 
       var bounds = new google.maps.LatLngBounds(); 
       var mapOptions = { 
        mapTypeId: 'roadmap' 
       }; 

       // Display a map on the page 
       map = new google.maps.Map(document.getElementById("map"), mapOptions); 
       map.setTilt(45); 


       // Multiple Markers 
       var markers = [ 
        [lat, lng ] 
       ]; 




       // Display multiple markers on a 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] 
        }); 

        // Allow each marker to have an info window 
        google.maps.event.addListener(marker, 'click', (function(marker, i) { 
         return function() { 
          infoWindow.setContent(infoWindowContent[i][0]); 
          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 (Make sure it only runs once) 
       var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) { 
        this.setZoom(14); 
        google.maps.event.removeListener(boundsListener); 
       }); 

     } 
    </script> 

正如你所看到的IM通過每個傳單循環。當我去看看網頁源,它顯示的是通過在的foreach的所有LAT和液化天然氣,但在這裏:

   // Multiple Markers 
       var markers = [ 
        ['', lat, lng ] 
       ]; 

只顯示最後LNG和緯度,你能跟大家知道,也許我必須將它插入數組或其他東西,我嘗試了很多東西? 這就是現在看起來像有1個標記: enter image description here

+0

這不僅是因爲要覆蓋變量每次循環顯示最後的座標。無論如何,你不應該通過PHP傳遞你的座標,你應該做一個Ajax調用,並獲取所有座標的JSON,然後做一個JS循環來創建不同的標記。 – enriqg9

回答

0

知道了!這是我必須做的:

// Multiple Markers 
var markers = [ 
@foreach($flyer as $flyers) 
     ['', {{ $flyers->lat }}, {{ $flyers->lng }} ], 
@endforeach 
]; 
相關問題