0

我正在尝试使用从我的 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 rewquest,但这导致代码在设置原始值之前执行,现在正在设置但看起来不正确

如何确保我的纬度和经度结果采用正确的 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>';
          } 
          }
        });
     }
4

1 回答 1

1

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

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

我在猜测特定属性,您可能想console.log(result)查看确切的对象结构。

于 2013-04-07T01:01:58.917 回答