如何使用php / xml在google map api上放置多个标记?

时间:2018-04-30 07:31:48

标签: php google-maps google-maps-api-3

我需要在谷歌地图上放置多个商店,但是下面的代码只显示每个商店的一个类似标记。当我尝试将脚本移动到foreach循环时,它根本不起作用。当我在商店点击按钮时,我还需要居中标记。

   <?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>

我也尝试循环标记数组

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;?>
        ];

但它有这样的错误

  

无法阅读财产&#39; 47.4592&#39;未定义的

1 个答案:

答案 0 :(得分:2)

您可以使用xml。然后你可以在你的javascript中调用xml,其中标记将取决于你的xml。或者您可以尝试谷歌地图开发人员,但只需将URL更改为您的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>';

这是我的javascript示例,我称之为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')));