谷歌在PHP中映射多个标记不起作用

时间:2015-09-08 05:14:47

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

将地图放在我的网站中我按照一个示例显示静态标记,如。

var locations = [
['Bondi Beach', -33.890542, 151.274856],
['Coogee Beach', -33.923036, 151.259052],
['Cronulla Beach', -34.028249, 151.157507],
['Manly Beach', -33.80010128657071, 151.28747820854187],
['Maroubra Beach', -33.950198, 151.259302]
];

我希望它从mysql表动态化。它有lat和lng。我试过这个但没有工作

<?php
    $host = "localhost";
    $db_name = "aarya";
    $user = "root";
    $password = "";

    $con = mysql_connect($host,$user,$password) or die("connection error");

    mysql_select_db($db_name) or die("could't connect to database");

    $query="SELECT * FROM detail";
    $result=mysql_query($query);
    while ($row=mysql_fetch_array($result)) {
    ?>
var locations = [
  ['<?php echo $row['name'];?>','<?php echo $row['lat'];?>','<?php echo $row['lng'];?>'],
<?php
}
?>
];

我认为位置数组中的问题和谷歌地图中的新功能请帮助我。

5 个答案:

答案 0 :(得分:3)

以下是执行此操作的粗略示例:

您的locations数组:

<?php
$locations[0] = array("lat"=>"-33.890542", "long"=>"151.274856", "info" => "Bondi Beach");
$locations[1] = array("lat"=>"-33.923036", "long"=>"151.259052", "info" => "Coogee Beach");
$locations[2] = array("lat"=>"-34.028249", "long"=>"151.157507", "info" => "Cronulla Beach");
$locations[3] = array("lat"=>"-33.80010128657071", "long"=>"151.28747820854187", "info" => "Manly Beach");
$locations[4] = array("lat"=>"-33.950198", "long"=>"151.259302", "info" => "Maroubra Beach");
?>

或者你可以查询数据库,如:

<?php
$query="SELECT * FROM detail";
$result=mysql_query($query);
while ($row=mysql_fetch_array($result)) {
    $locations[] = array("lat"=>$row['lat'], "long"=>$row['lng'], "info" => $row['name']);
}
?>

您可以使用数据库中的值修改上述数组。 地图:

<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <style type="text/css">
            body { font: normal 10pt Helvetica, Arial; }
            #map { width: 350px; height: 300px; border: 0px; padding: 0px; }
        </style>
        <script src="http://maps.google.com/maps/api/js?v=3&sensor=false" type="text/javascript"></script>
        <script type="text/javascript">

        var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png",
        new google.maps.Size(32, 32), new google.maps.Point(0, 0),
        new google.maps.Point(16, 32));
        var center = null;
        var map = null;
        var currentPopup;
        var bounds = new google.maps.LatLngBounds();

        function addMarker(lat, lng, info)
        {
            var pt = new google.maps.LatLng(lat, lng);
            bounds.extend(pt);
            var marker = new google.maps.Marker(
            {
                position: pt,
                icon: icon,
                map: map
            });
            var popup = new google.maps.InfoWindow(
            {
                content: info,
                maxWidth: 300
            });

            google.maps.event.addListener(marker, "click", function()
            {
                if (currentPopup != null)
                {
                    currentPopup.close();
                    currentPopup = null;
                }
                popup.open(map, marker);
                currentPopup = popup;
            });
            google.maps.event.addListener(popup, "closeclick", function()
            {
                map.panTo(center);
                currentPopup = null;
            });
        }

        function initMap()
        {
            map = new google.maps.Map(document.getElementById("map"), {
            center: new google.maps.LatLng(0, 0),
            zoom: 0,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: false,
            mapTypeControlOptions:
            {
                style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
            },
            navigationControl: true,
            navigationControlOptions:
            {
                style: google.maps.NavigationControlStyle.SMALL
            }
            });
            <?php foreach($locations AS $loc) { //you could replace this with your while loop query ?>
                addMarker(<?php echo $loc["lat"]; ?>, <?php echo $loc["long"]; ?>, '<?php echo $loc["info"]; ?>');
            <?php } ?>
            center = bounds.getCenter();
            map.fitBounds(bounds);
        }
        </script>
    </head>
    <body onload="initMap()" style="margin:0px; border:0px; padding:0px;">
    <div id="map"></div>
</html>

希望有所帮助:)

答案 1 :(得分:0)

每次while循环运行时,都在初始化var位置。在这方面你将只有最后一次迭代的值。请在外面初始化位置并推送javascript数组中的值。另外你应该考虑json_encode方式。它更清洁。

答案 2 :(得分:0)

如果你是谷歌地图的新手,你可以使用gmaps.js,它可以让你以一种简单的方式利用谷歌地图的潜力。

https://hpneo.github.io/gmaps/

及其标记示例: https://hpneo.github.io/gmaps/examples/markers.html

我认为你需要使用对象:

A<T...>

您可以使用json_encode代替

答案 3 :(得分:0)

在您的代码中,您已经拥有全球可用的以下位置:

var locations = [
['Bondi Beach', -33.890542, 151.274856],
['Coogee Beach', -33.923036, 151.259052],
['Cronulla Beach', -34.028249, 151.157507],
['Manly Beach', -33.80010128657071, 151.28747820854187],
['Maroubra Beach', -33.950198, 151.259302]
];

现在在您的文件中添加以下HTMLJavascript并刷新页面。这将显示Google地图。

<强> HTML

<div id="map_canvas" style="width:700px;height:500px;"></div>;

<强>的Javascript

function loadMap()
{
  var map;
  var bounds = new google.maps.LatLngBounds();
  var mapOptions = {
    mapTypeId: 'roadmap'
  };
  // Display a map on the page
  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  for( i = 0; i < locations.length; i++ ) {
    var loc = locations[i];
    var position = new google.maps.LatLng(loc[1], loc[2]);
    bounds.extend(position);
    marker = new google.maps.Marker({
      position: position,
      map: map,
      title: loc[0]
    });
    map.fitBounds(bounds);
  }
}
google.maps.event.addDomListener(window, 'load', loadMap);

答案 4 :(得分:0)

如果您想动态使用数据库,请查看此示例。

创建文件map3.php。文件与此处相同

$conn = mysql_connect("localhost","root","");

mysql_select_db('yourdatabase');

function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}

$query = mysql_query("select * from yourtable");



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

/* Get lat and Lan using table query */
$i=0;

while($row = mysql_fetch_assoc($query)){


$reposnse['markers'][$i]['lat']= $row['lat'];
$reposnse['markers'][$i]['lag']= $row['lag'];


$i++;
}

echo json_encode($reposnse);
?>

After create map2.php same as here

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>

    <script type="application/javascript">





     $(document).ready(function(e) {



$.ajax({
url:"map3.php",
dataType: 'json',
success: function(result){
var html = '<markers>';


for (var prop in result['markers']) {

var value = result['markers'][prop];
//alert(value.lat);
html += '<marker ';
html += 'lat="';
html += value.lat+'"';
html += 'lng="';
html += value.lag+'"';
html += '/>';
}
html += '</markers>';
$('#test').html(html);

function initialize() {
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 6,
            center: new google.maps.LatLng(15.317277,75.71389),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

var infowindow = new google.maps.InfoWindow();

        var marker;

        var location = {};


var markers = document.getElementsByTagName("marker");


        for (var i = 0; i < markers.length; i++) {

//alert(markers[i].getAttribute("lat"));
            location = {
                name : 'test'+i,
                address : 'baglore',
                city : 'bangalore',
                state : 'Karnataka',
                zip : '560017',
                pointlat : parseFloat(markers[i].getAttribute("lat")),
                pointlng : parseFloat(markers[i].getAttribute("lng"))  
            };

            console.log(location);

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

            google.maps.event.addListener(marker, 'click', (function(marker,location) {
                return function() {
                    infowindow.setContent(location.name);
                    infowindow.open(map, marker);
                };
            })(marker, location));
        }
  }

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

},
});

    });

    </script>
</head>
<body>
    <div id="test">
    </div>

    <div id="map" style="width: 500px; height: 400px;"></div>
</body>
</html>

请查看以下链接Adding multiple markers to google maps using javascript and php