我在显示从 MySQL 数据库提取的数据标记时遇到问题。尽管 JSON 有效,但 JSON 格式不正确。我想至少有两种方法可以解决我的问题,1. 更改 MySQL 查询或 2. 在使用 Gmap3 构建 Google map 之前使用 jQuery 操作 JSON 输出。我和他们中的任何一个都在挣扎..
my-json.php 中的 MySQL 查询和 JSON 编码:
try {
$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$tatorte = $db->query("
SELECT p.post_title as title,
max(case when pm.meta_key = '_cmb_tatort_map_latitude' then pm.meta_value end) as lat,
max(case when pm.meta_key = '_cmb_tatort_map_longitude' then pm.meta_value end) as lng,
max(case when pm.meta_key = '_cmb_subline' then pm.meta_value end) as subline,
max(case when pm.meta_key = '_cmb_teaser_text' then pm.meta_value end) as teaser
FROM mob_posts p join
mob_postmeta pm
on pm.post_id = p.ID
WHERE pm.meta_key in ('_cmb_tatort_map_latitude', '_cmb_tatort_map_longitude', '_cmb_subline', '_cmb_teaser_text') and
p.post_type = 'tatort'
group by p.id
ORDER BY p.id DESC
LIMIT 100;
");
$rows = array();
while ($locations = $tatorte->fetch_assoc()) {
$rows[] = array('values' => $locations);
}
$json = array(
"center" => array(51.95026490,11.69227350), // center map at a given location
"tatorte" => $rows
);
header('Content-Type: application/json; charset=UTF-8;');
echo json_encode( $json );
} catch (Exception $e) {
echo $e->getMessage();
}
所以这似乎工作正常,我得到了一个有效的 JSON,如下所示:
{
"center":[
51.9502649,
11.6922735
],
"tatorte":[
{
"values":{
"title":"my title",
"lat":"51.7920562",
"lng":"11.141447999999968",
"subline":"my sublime",
"teaser":"my teaser text"
}
}
]
}
显然,格式应该是这样的:
{
"center": [
46.578498,
2.457275
],
"tatorte": [
{
"lat": 49.00408,
"lng": 2.56228,
"data": {
"title":"my title",
"subline":"my sublime",
"teaser":"my teaser text"
}
}
]
}
所以我尝试在 jQuery 中加载和操作我的 JSON,如下所示:
function loadData(){
var markers = [];
$.ajax({
url:'my-json-load.php',
success:function(data){
var markers = [];
$.each(data, function(key, val){
var position = [val.lat, val.lng];
markers.push({ latLng: position });
});
display(data.center, data.tatorte);
}
});
}
然后,使用Gmap3插件来显示它们:
$(function(){
loadData();
});
function display(center, tatorte) {
$('#map_canvas').gmap3({
map:{
options:{
center: center,
zoom:7,
mapTypeId: google.maps.MapTypeId.TERRAIN
}
},
marker: {
values: tatorte
}
});
}
中心点显示正确,与 map 相同。仅缺少标记。我缺少一些正确的方法...我想这很简单,但我对 jQuery/javascript 没有太多经验,也没有太多的经验如何改变 MySQL 查询以获得标记值的正确格式。任何人?非常感谢帮助。谢谢。
最佳答案
尝试调整你的 php。
while ($locations = $tatorte->fetch_assoc()) {
$lat = $locations['lat'];
$lng = $locations['lng'];
$values = json_encode( array('title' => $locations['title'], 'subline' => $locations['subline'], 'teaser' => $locations['teaser']) );
$rows[] = array('lat' => $lat, 'lng' => $lng, 'values' => $values);
}
关于jquery - 使用 MySQL、JSON 和 jQuery 插件 Gmap3 填充 Google map 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20425415/