Pol Vilarrasa
Pol Vilarrasa

Reputation: 322

How to load data from a DB(mysql) into the google maps API(laravel)

So i have this laravel app where i need my google maps API to load some markers. I have the lat and lng of each marker stored in my db and i want to pass all this data into the script of the google maps API:

    function initMap() {
    var lafarinera = {lat: 41.934029, lng: 2.265616};
    var vic = {lat: 41.930445, lng: 2.254321};
    var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 8,
    center: vic
    });
    var contentString = '<div id="content">'+
    '<div id="siteNotice">'+
    '</div>'+
    '<h3 id="firstHeading" class="firstHeading">La Farinera</h3>'+
    '<img src="">'+
    '<div id="bodyContent">'+
    '<p> 84, Carrer de Sant Jordi, 82, 08500 Vic, Barcelona </p>'+
    '<button type="button" class="btn btn-primary">Informacio</button>'+
    '</div>'+
    '</div>';
        var infowindow = new google.maps.InfoWindow({
            content: contentString,
            maxWidth: 200
        });
            var marker_lafarinera = new google.maps.Marker({
            position: lafarinera,
            map: map,
            title: 'La farinera'
        });
        marker_lafarinera.addListener('click', function() {
            infowindow.open(map, marker_lafarinera);
        });
    }


this way it works just by one marker as i have the lat and lng static but what i would like is to just to pass all the data from de db so that then i can use it inside my .js.

Upvotes: 3

Views: 762

Answers (1)

Mahdi Younesi
Mahdi Younesi

Reputation: 7499

you need to add the markers array in script tag or get them by ajax

<script>
  var markers= @json($markers);

  $.each(markers as marker,function(){
      addMarkerToMap(marker);
  });

  function addMarkerToMap(marker){

        var location = new google.maps.LatLng(marker.latitude,marker.longitude);

        marker = new google.maps.Marker({
            position: location,
            map: map,
        });

  });
</script>

Upvotes: 2

Related Questions