无法使用格式正确的数据填充JSON请求

时间:2013-04-07 00:33:48

标签: php javascript json google-maps

我正在尝试使用从我的phpsearch.php文件返回的数据填充JSON请求(此处显示)

<?php
include "base.php";
$name = $_GET["name"];
$query = "SELECT lat, lng FROM markers WHERE name = '".$name."'";
$result = mysql_query($query);
$json = array();
while($row = mysql_fetch_array ($result))     
{
  $bus = array(
        'lat' => $row['lat'],
        'lng' => $row['lng']
    );
    array_push($json, $bus);
}
$jsonstring = json_encode($json);
echo $jsonstring;
?>

数据在控制台中以这种格式显示:

[{"lat":"37.730267","lng":"-122.498589"}]

路由计算函数位于问题的底部,我之前使用过异步JSON重写,但这导致代码在设置原始值之前执行,现在它已被设置但看起来不正确

如何确保我的纬度和经度结果采用正确的JSON格式?目前JSON请求如下所示:

 Request URL:https://maps.googleapis.com/maps/api/js/DirectionsService.Route?4b0&5m4&1m3&1m2&1dNaN&2dNaN&5m4&1m3&1m2&1d37.738029&2d-122.499481&6e1&8b1&12sen-GB&100b0&102b0&callback=_xdc_._1rqnjk&token=80599

路线计算代码:

  function calcRoute() {
        var startname = document.getElementById('start').value;
        var endname = document.getElementById('end').value;
        var waypts = [];
        var checkboxArray = document.getElementById('waypoints');
        for (var i = 0; i < checkboxArray.length; i++) {
          if (checkboxArray.options[i].selected == true) {
            waypts.push({
                location:checkboxArray[i].value,
                stopover:true});
          }
        }

$.ajax({
    url:'phpsearch2.php', 
    dataType:'html', 
    data:{name:startname},
    async:false,
    success:function (result)
{
    console.log(result)
    origin = new google.maps.LatLng(result[0].lat, result[0].lng);
}});

    var end = new google.maps.LatLng('37.738029', '-122.499481');
    var request = {
            origin: origin,
            destination: end,
            waypoints: waypts,
            optimizeWaypoints: true,
            travelMode: google.maps.DirectionsTravelMode.WALKING
        };

            directionsService.route(request, function(response, status) {
        document.write('<b>'+ origin +'</b>');
          if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            var route = response.routes[0];
            var summaryPanel = document.getElementById('directions_panel');
            summaryPanel.innerHTML = '';
            // For each route, display summary information.
            for (var i = 0; i < route.legs.length; i++) {
              var routeSegment = i + 1;
              summaryPanel.innerHTML += '<b>Time for a Walkabout </b><br>';
              summaryPanel.innerHTML += '<b>From ' + startname + '   </b>';
              summaryPanel.innerHTML += '<b>to ' + endname + '('+ route.legs[i].distance.text +')</b><br>';
          } 
          }
        });
     }

1 个答案:

答案 0 :(得分:1)

LatLng构造函数将两个数字作为参数,您将其传递给JSON对象。获取纬度和经度属性并直接传递数字,如下所示:

function (result){
    origin = new google.maps.LatLng(result[0].latitude, result[0].longitude);
}

我猜测具体的属性,你可能希望console.log(result)看到确切的对象结构。