在谷歌地图上绘制多个标记

时间:2016-01-29 03:03:22

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

我有一个输出此json数据的php文件

[{"lat":"5.92687670","lng":"116.10072270"},{"lat":"6.23331022","lng":"116.42924500"},{"lat":"47.62456131","lng":"-122.35644531"},{"lat":"47.60636520","lng":"-122.33765411"},{"lat":"47.61282349","lng":"-122.34567261"},{"lat":"47.60596085","lng":"-122.34036255"},{"lat":"47.61397552","lng":"-122.34546661"},{"lat":"47.61721420","lng":"-122.32658386"}]

这是上面结果的php代码(genjson.php):

<?php

require("connect.php");

$link = mysqli_connect("localhost", "$username", "$password", "$database");

if (!$link) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
    echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
    exit;
}

mysqli_select_db($link,"senangbah");

$var = array();
$sql = "SELECT `lat`, `lng` FROM markers";

$result = mysqli_query($link, $sql);

while($obj = mysqli_fetch_object($result)) {
$var[] = $obj;
}

header('Content-Type: application/json');
echo json_encode($var);
?>

这是地图的javascript

function initMap() {
    var latlng = new google.maps.LatLng(5.5117338, 117.0463637);
    var myOptions = {
        zoom: 3,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false
    };
    var map = new google.maps.Map(document.getElementById("map"),myOptions);

    $.getJSON('genjson.php', function(markers) {
    for (i = 0; i < markers.length; i++) {  
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(markers[i][0], markers[i][1]),
            map: map
        });

    }
});

}

地图加载正常,但没有显示标记?我做错了哪一部分? TQ

1 个答案:

答案 0 :(得分:1)

错误在此声明中:

position: new google.maps.LatLng(markers[i][0], markers[i][1]),

由于每个marker[n]都是一个对象,而不是一个数组,因此您必须使用:

position: new google.maps.LatLng(markers[i].lat, markers[i].lng),

顺便说一句,请注意,您最好先编写var marker = ...而不是marker = ...,以避免污染全球空间。