0

我正在尝试从 PHP/MySQL 查询将纬度和经度的数据库值返回到我的 Javascript 函数,以填充谷歌地图 JSON 请求。

我的 PHP/MySQL 查询脚本 phpsearch2.php 是:

<?php
include "base.php";
$name = $_GET["name"];
$query = "SELECT lat, lng FROM markers WHERE name = '".$name."'";
$result = mysql_query($query);
while($row = mysql_fetch_array ($result))     
{
     echo '{';
           echo '"latitude":"'.$row['lat'].'",';
           echo '"longitude":"'.$row['lng'].'",';
     echo '}';    
}
?>

它以这种格式返回一个值:

{"latitude":"37.730267","longitude":"-122.498589",} 

这是我的计算根函数,当我运行程序时,即使我认为我将它设置为与从 JSON 请求到 phpsearch 的返回结果具有相同的值,我也会收到一条错误消息,说“原点未定义” ,我只是不不知道错在哪里。

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

$.getJSON("phpsearch2.php", {name : startname}, function (result) {
origin = google.maps.LatLng('result');
});

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>'+ start + end + '</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

您将“结果”作为字符串传递。您需要传递结果对象,不带引号:

var origin = google.maps.LatLng(result);

请记住 $.getJSON 是异步的。您可能需要将其余 gmaps 代码包装在函数声明中,并在设置 origin在 $.getJSON 回调中调用该函数。否则,在从服务器获取原始数据之前,您仍在尝试使用它。

就像是:

$.getJSON("phpsearch2.php", {name : startname}, function (result) {
    var origin = google.maps.LatLng(result);

    // Now that we have our origin, we can initialize the rest
    init(origin);
});

function init(origin) {
   var end = new google.maps.LatLng('37.738029', '-122.499481');
   var request = {
        origin: origin,
   <snip>
}
于 2013-04-06T23:41:32.197 回答