在谷歌地图中显示JSON响应(lat,lon)

时间:2016-08-03 06:27:26

标签: javascript php mysql json google-maps

我正在尝试构建一个从数据库(mysql)获取用户数据(lat,lon)的应用程序,然后在谷歌地图上显示它们的位置。

以下是代码示例:

function initMap() {
        var mapDiv = document.getElementById('map');
        var map = new google.maps.Map(mapDiv, {
        center: {lat: 33.7167, lng: 73.0667},
        zoom: 11
    });

    makeRequest('get_locations.php', function(data) {
        //alert("abc");
        var data = JSON.parse(data.responseText);
        //window.alert(data);

        for (var i = 0; i < data.length; i++) {
            //display(data[i]);
            displayLocation(data[i]);
        }
    });
}   


function makeRequest(url, callback) {
    var request;
    if (window.XMLHttpRequest) {
        request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
    } else {
        request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
    }
    request.onreadystatechange = function() {
        if (request.readyState == 4 && request.status == 200) {
            callback(request);
        }
    }
    request.open("GET", url, true);
    request.send();
}

get_locations.php

<?php
    include('connection.php');
    $l= array();
    $result = mysqli_query($con,"SELECT * FROM users");
    while ($row = mysqli_fetch_assoc($result)) {
        $l[] = $row;
    }
    $j = json_decode($l, true);
     //echo $j;

?>

有些事情我试图在代码上找到问题但是失败了

  1. 在echo $ j上的 get_location.php; ,它显示正确的回复

  2. 在此行之前 var data = JSON.parse(data.responseText); alert(“abc”)有效但不在此之后,所以我认为问题出在此行,但不知道为什么会发生这种情况, 有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我认为主要问题是在您需要相反的情况下滥用json_decode json_encode

function initMap() {
        var mapDiv = document.getElementById('map');
        var map = new google.maps.Map(mapDiv, {
        center: {lat: 33.7167, lng: 73.0667},
        zoom: 11
    });

    makeRequest('get_locations.php', function(data) {
        if( data ){
            var data = JSON.parse( data );
            for( var n in data ){
                var obj=data[ n ];

                console.log( '%o', obj );
                displayLocation.call(this,obj);
            }
        }
    });
}   


function makeRequest(url, callback) {
    var request;
        request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

    request.onreadystatechange = function() {
        if (request.readyState == 4 && request.status == 200) {
            callback( request.responseText );
        }
    }
    request.open("GET", url, true);
    request.send();
}




<?php

    include('connection.php');
    $l= array();

    $result = mysqli_query( $con, "SELECT * FROM users" );
    while ( $row = mysqli_fetch_assoc( $result ) ) {
        $l[] = $row;
    }

    /* encode array as a json object */
    $json = json_encode( $l );

    /* send the correct content-type header */
    header('Content-Type: application/json');

    /* send the data */
    exit( $json );

?>