Dynamic google map with multiple markers

Lately i need to use the google API to create maps with multiple markers. Obviously, the operation need to get the markers latitude and longitude from somewhere and i used database. Basically the process is easy: we create an ajax call and create the markers with a loop and then display them on a map.

so first, get the google maps api:

<script src="https://maps.googleapis.com/maps/api/js"></script>

 Then we create a function that will do basically all the process needed:

      function initialize() {
        var mapCanvas = document.getElementById('map');
        var mapOptions = {
            zoom: 13,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        var map = new google.maps.Map(mapCanvas, mapOptions);
        var centerLat = '';
        var centerLng = '';

            url: 'get-locations.php',

                //Loop through each location.
                // Sample use of first data
                centerLat = data[0].lat;
                centerLng = data[0].lng;
                $.each(data, function(){
                    //Plot the location as a marker
                    var theposition = new google.maps.LatLng(this.lat, this.lng); 
                    var marker = new google.maps.Marker({
                        position: theposition,
                        map: map,
                        title: 'Uluru (Ayers Rock)',
                        animation: google.maps.Animation.DROP

                var contentString = '<div id="content">'+
                '<div id="siteNotice">'+
                '<h1 id="firstHeading" class="firstHeading">'+this.name+'</h1>'+
                '<div id="bodyContent">'+

                var infowindow = new google.maps.InfoWindow({
                    content: contentString

                    marker.addListener('click', function() {
                        infowindow.open(map, marker);
                map.setCenter(new google.maps.LatLng(centerLat,centerLng));


    google.maps.event.addDomListener(window, 'load', initialize);

 The main thing is the ajax call that takes the data from the database, loop it, and create the markers and send additional data to the infowindow.

Obviously the main info that you have to store is the longitude and latitude, all other data are just additional information.

just as an example this is my simple query for the database and sending the data back to my ajax call:

$sql = "SELECT * FROM `markers`";
$sel = $db->dbSelectBySql($sql);

//Encode the $locations array in JSON format and print it out.
header('Content-Type: application/json');
echo json_encode($sel);

 Notice that after the function we call it when listening to the page load event.

And that is it basically. I will recommend you to check the google maps API to see all the options available to you.

Leave a Reply

Your email address will not be published. Required fields are marked *