Iva Kobalava
Iva Kobalava

Reputation: 129

How place multiple markers on google map api with php/xml?

I have multiple stores that i need to place on google map but with the code below it only shows one similar marker on each store. when i try to move script to foreach loop it is not working at all. and also i need to center marker when button is clicked on that store.

   <?php foreach ($list as $record): ?>
     <?php if (strcmp($record->district, $current_district) == 0): ?>
      <?php $x = explode(',', $record->coord); ?>
         <tr>
           <td> <?php echo $record->address; ?> </td>
           <td> <?php echo $record->work_range; ?> </td>
           <td><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#mapid">Show on map</button>
           <?php $coords = explode(',', $record->coord);?>
           </td>
        </tr>

     <?php endif; ?>
    <?php endforeach; ?>


<script type="text/javascript">
    jQuery(function($) {
        var script = document.createElement('script');
        script.src = "//maps.googleapis.com/maps/api/js?key=AIzaSyCOGCQoaHaVrdY9z2Tg3hfowUtEeb-BwQs&callback=initialize";
        document.body.appendChild(script);
    });

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

        map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
        map.setTilt(45);

        var markers = [
            ['<?php echo $record->address;?>', <?php echo $coords[0];?>, <?php echo $coords[1];?>]
        ];

        var infoWindowContent = [
            ['<div class="info_content">' +
            '<h3><?php echo $record->address;?></h3>' +
            '<p>.</p>' +        '</div>']
        ];

        var infoWindow = new google.maps.InfoWindow(), marker, i;

        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]
            });

            google.maps.event.addListener(marker, 'click', (function(marker, i) {
                return function() {
                    infoWindow.setContent(infoWindowContent[i][0]);
                    infoWindow.open(map, marker);
                }
            })(marker, i));
            map.fitBounds(bounds);
        }
        var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
            this.setZoom(1);
            google.maps.event.removeListener(boundsListener);
        });
    }
</script>

I also tried to loop through markers array

var markers = [
            <?php foreach ($list as $record):?>
            <?php $coord = explode(',', $record->coord);?>
            ['<?php if(!empty($coord[0])){echo $record->address;}else{echo "None";}?>', <?php if(!empty($coord[0])){echo $coord[0];}else{echo "48.7795";}?>, <?php if(!empty($coord[1])){echo $coord[1];}else{echo "47.8138";}?>]
            <?php endforeach;?>
        ];

but it has such error

Cannot read property '47.4592' of undefined

Upvotes: 0

Views: 577

Answers (1)

gwapo
gwapo

Reputation: 218

You can use an xml. Then you can call the xml in your javascript where the markers will depend on your xml. Or you can try the google map developer but just change the URL to your xml. https://developers.google.com/maps/documentation/javascript/mysql-to-maps

<?php
require("config.php");

function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','&lt;',$htmlStr);
$xmlStr=str_replace('>','&gt;',$xmlStr);
$xmlStr=str_replace('"','&quot;',$xmlStr);
$xmlStr=str_replace("'",'&#39;',$xmlStr);
$xmlStr=str_replace("&",'&amp;',$xmlStr);
return $xmlStr;
}

// Opens a connection to a MySQL server
$connection=mysqli_connect('localhost', $username, $password);
if (!$connection) {
  die('Not connected : ' . mysqli_error());
}

// Set the active MySQL database
$db_selected = mysqli_select_db($connection, $database);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysqli_error());
}

// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysqli_query($connection, $query);
if (!$result) {
  die('Invalid query: ' . mysqli_error($connection));
}

header("Content-type: text/xml");

// Start XML file, echo parent node
echo "<?xml version='1.0' ?>";
echo '<markers>';
$ind=0;
// Iterate through the rows, printing XML nodes for each
while ($row = @mysqli_fetch_assoc($result)){
  // Add to XML document node
  echo '<marker ';
  echo 'id="' . $row['id'] . '" ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'contact_number="' . parseToXML($row['contact_number']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo 'image="' . $row['image'] . '" ';
  echo '/>';
  $ind = $ind + 1;
}

// End XML file
echo '</markers>';

And this is the sample of my javascript where i called the xml

Array.prototype.forEach.call(markers, function(markerElem) {
              var id = markerElem.getAttribute('id');
              var name = markerElem.getAttribute('name');
              var address = markerElem.getAttribute('address');
              var contact_number = markerElem.getAttribute('contact_number');
              var image = markerElem.getAttribute('image');
              var point = new google.maps.LatLng(
                  parseFloat(markerElem.getAttribute('lat')),
                  parseFloat(markerElem.getAttribute('lng')));

Upvotes: 2

Related Questions