2016-08-04 2 views
1

У меня есть карты Google, загружающие местоположения из моей базы данных динамически на карте. Проблема заключается в том, что он не отображает в каждом месте правильную отображаемую информацию. Его только показ информации из последнего продукта на всех маркерах. Мне нужно как-то перебирать каждый маркер. Мой код ниже:Google Map API, загружающий динамические информационные окна

<section class="content jumbotron jumbotron-full-height"> 
    <div class="item slide-1"> 
     <div id="home-map"></div> 
    </div> 
</section> 

<script> 
    var map; 
    function initMap() { 

     map = new google.maps.Map(document.getElementById('home-map'), { 
      center: {lat: 52.1326, lng: 5.2913}, 
      zoom: 6, 
      mapTypeId: 'roadmap', 
      styles: [ 
       { 
        featureType: 'all', 
        stylers: [ 
         { saturation: 0 } 
        ] 
       },{ 
        featureType: 'road.arterial', 
        elementType: 'geometry', 
        stylers: [ 
         { hue: '#00ffee' }, 
         { saturation: 0 } 
        ] 
       },{ 
        featureType: 'poi.business', 
        elementType: 'labels', 
        stylers: [ 
         { visibility: 'off' } 
        ] 
       },{ 
        featureType: 'road', 
        elementType: 'labels', 
        stylers: [ 
         { visibility: 'on' } 
        ] 
       } 
      ] 
     }); 

     {% for product in products %} 
      var contentString = '<div class="info-window">'+ 
            '<div id="siteNotice">'+ 
            '</div>'+ 
            '<div id="window-content">'+ 
             '{% set path = product.image is not null ? product.image.path|imagine_filter(filter|default('sylius_shop_map_thumbnail')) : 'http://placehold.it/200x200' %}'+ 
             '<img src="{{ path }}" />'+ 
             '<h1>{{ product.code }}</h1>'+ 
            '</div>'+ 
            '<h2>{{ product.city }} - {{ product.country }}</h2>'+ 
            '<p><strong> Description: </strong>{{ product.shortDescription }}</p>'+ 
            '<p><strong> Price: </strong>from {{ product.price|sylius_price }} a day.</p>'+ 
            '<a class="btn btn-primary" href="{{ path("sylius_shop_product_show", {"slug": product.slug}) }}">more info</a>'+ 
           '</div>'; 

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

      var marker = new google.maps.Marker({ 
       position: {lat: {{ product.latitude }}, lng: {{ product.longitude }}}, 
       map: map, 
       title: '{{ product.city }}', 
       label: '{{ product.address }}' 
      }); 
      marker.addListener('click', function() { 
       infowindow.open(map, marker); 
      }); 
     {% endfor %} 
    } 
</script> 
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC1c34AXAQ5Y3yV43Alj_ieMRaDPb0qZ44&callback=initMap" async defer> 
</script> 

ответ

0

Проблема заключается в том, что вы не устанавливаете свой контент динамически. Для этого нужно создать маркер из другой функции

<section class="content jumbotron jumbotron-full-height"> 
     <div class="item slide-1"> 
      <div id="home-map"></div> 
     </div> 
    </section> 

    <script> 
     var map,infowindow; 
     function initMap() { 

      map = new google.maps.Map(document.getElementById('home-map'), { 
       center: {lat: 52.1326, lng: 5.2913}, 
       zoom: 6, 
       mapTypeId: 'roadmap', 
       styles: [ 
        { 
         featureType: 'all', 
         stylers: [ 
          { saturation: 0 } 
         ] 
        },{ 
         featureType: 'road.arterial', 
         elementType: 'geometry', 
         stylers: [ 
          { hue: '#00ffee' }, 
          { saturation: 0 } 
         ] 
        },{ 
         featureType: 'poi.business', 
         elementType: 'labels', 
         stylers: [ 
          { visibility: 'off' } 
         ] 
        },{ 
         featureType: 'road', 
         elementType: 'labels', 
         stylers: [ 
          { visibility: 'on' } 
         ] 
        } 
       ] 
      }); 

      infowindow = new google.maps.InfoWindow({ 
        maxWidth: 600 
       }); 

      {% for product in products %} 
       createMarker(product) 
      {% endfor %} 
     } 

     function createMarker(product){ 

     var contentString = '<div class="info-window">'+ 
             '<div id="siteNotice">'+ 
             '</div>'+ 
             '<div id="window-content">'+ 
              '{% set path = product.image is not null ? product.image.path|imagine_filter(filter|default('sylius_shop_map_thumbnail')) : 'http://placehold.it/200x200' %}'+ 
              '<img src="{{ path }}" />'+ 
              '<h1>{{ product.code }}</h1>'+ 
             '</div>'+ 
             '<h2>{{ product.city }} - {{ product.country }}</h2>'+ 
             '<p><strong> Description: </strong>{{ product.shortDescription }}</p>'+ 
             '<p><strong> Price: </strong>from {{ product.price|sylius_price }} a day.</p>'+ 
             '<a class="btn btn-primary" href="{{ path("sylius_shop_product_show", {"slug": product.slug}) }}">more info</a>'+ 
            '</div>'; 


       var marker = new google.maps.Marker({ 
        position: {lat: {{ product.latitude }}, lng: {{ product.longitude }}}, 
        map: map, 
        title: '{{ product.city }}', 
        label: '{{ product.address }}' 
       }); 
       marker.addListener('click', function() { 
        infowindow.setContent(contentString); 
        infowindow.open(map, marker); 
       }); 
     } 


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

Обязательно объявить InfoWindow как глобальная переменная

+0

его до сих пор не работает, потому что «продукт» не определен в функции createMarker, мне нужно поместить {% для продукта в продуктах%} где-нибудь, чтобы функция узнала, к какому продукту он обращается. –

+0

о, это была типичная ошибка. я исправлю, что вы можете попробовать сейчас –

+0

Я все еще получаю ошибку Переменный «продукт» не существует в SyliusShopBundle: Homepage: index.html.twig в строке 79 -> это строка 79: '{% set path = product.image is not ноль ? product.image.path | imagine_filter (filter | default ('sylius_shop_map_thumbnail')): 'http://placehold.it/200x200'%} '+ –

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