0

I am trying to return database values for latitude and longitude from a PHP/MySQL query to my Javascript function in order to populate a google maps JSON request.

My PHP/MySQL query script, phpsearch2.php is:

<?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 '}';    
}
?>

It returns a value in this format:

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

Here is my calculate root function, when I run the program I get an error saying 'origin is not defined' even though I think I am setting it to have the same value as the return result from the JSON request to phpsearch, I just don't know where the mistake lies.

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

      } 
      }
    });
 }
1
  • OT: Always use json_encode to generate JSON in PHP. Have a look at this answer to learn the difference between synchronous and asynchronous code: stackoverflow.com/a/14220323/218196. Ajax is asynchronous. Commented Apr 7, 2013 at 0:25

1 Answer 1

1

You are passing 'result' in as a string. You need to pass the result object, without the quotes:

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

Keep in mind that $.getJSON is asynchronous. You probably need to wrap the rest of your gmaps code in a function declaration, and call that function in the $.getJSON callback after origin is set. Otherwise you're still trying to use origin before it has been fetched from the server.

Something like:

$.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>
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that was definitely an issue, I am still seeing an error after I make that change though Error: Invalid value for property <origin>: undefined ...y)/d);f&&f.io&&(qa(k,f.io[0]),Ka(k,f.io[1]));return{ya:f,W:e,df:g,anchorOffset:k...
Look at the updated answer. You need to wait for $.getJSON to return before you move on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.