0

I have a Google map that I want to automatically load with a prepopulated route (taken from a series of PHP form submissions).

Currently, the PHP forms culminate in a page that has a Google Map on it, and some drop-down boxes with the start and end points prepopulated (from their previous PHP form submissions), and an onChange function on the drop-down menus which calculates the route (onChange="calcRoute();", in the example below). This works fine but, in reality, every final form ends up with just one option for the route. Therefore, getting the user to "select" the start points and end points for the route is worthless - there is only one option in each drop down menus, so I might as well load those options and the calculated route between them automatically when the page loads.

Is there any way of doing this?

My directions function looks like this:

    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false"></script>
<?PHP
$Start_latLng = $_POST["start-latitude"] . ", " . $_POST["start-longitude"];
$End_latLng = $_POST["end-latitude"] . ", " . $_POST["end-longitude"];
?>
    <script>
      var directionDisplay;
      var directionsService = new google.maps.DirectionsService();
      var map;

      function initialize() {
        directionsDisplay = new google.maps.DirectionsRenderer();
        var mapOptions = {
          zoom:7,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          center: new google.maps.LatLng(54.219218, -2.905669)
        }
        map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
        directionsDisplay.setMap(map);
      }

      function calcRoute() {
        var start = document.getElementById('start').value;
        var end = document.getElementById('end').value;
        var request = {
            origin:start,
            destination:end,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
          if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
          }
        });
      }
    </script>

...and my dropdown menus are populated by the results of the PHP $_POST functions.

Obviously, I need wait for the map to load before I can calculate the route, so a pause might need to be injected - any ideas?

2
  • 1
    Could you just fire calcRoute(); as the last line of your initialize function? Jan 2, 2013 at 15:49
  • Always the simplest option! How did I not think of that?! Thank you, @Robot Woods Jan 2, 2013 at 15:58

1 Answer 1

0

Thank you to @Robot Woods: Could you just fire calcRoute(); as the last line of your initialize function? – Robot Woods

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.