gpt4 book ai didi

javascript - 在谷歌地图中显示 JSON 响应(纬度、经度)

转载 作者:行者123 更新时间:2023-11-29 20:37:22 25 4
gpt4 key购买 nike

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

这是代码示例:

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. get_location.php 中 echo $j; 它显示了正确的响应

  2. 在此行之前 var data = JSON.parse(data.responseText);alert("abc") 有效,但在此之后无效,所以我认为问题出在这一行,但不知道为什么会这样,有什么想法吗?

最佳答案

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

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

?>

关于javascript - 在谷歌地图中显示 JSON 响应(纬度、经度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38735941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com