Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 8 of 8
  1. #1
    New to the CF scene
    Join Date
    Apr 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Route calculation in Google Maps

    Hi Guys,

    I'm building something where i can have two dependent drop boxes that get their information from a mysql database.

    Select box 1 = Start adress
    Select box 2 = Destination adress

    I'm a hiker (someone who transports lease car's) and would like to keep track which routes i've driven. So let's say i choose a lease company above by adress and box 2 gives alle the destination adresses where i've been to.

    I would like to show these routes on google maps. I have the following code below, when i click calculate route i get a random chinese city to another chinese city route. Really strange, could you guys help me out?

    Thanks,

    Tom
    Code
    Code:
    
    <?php
    
    $vertrekadres = $eindadres =  null; //declare vars
    
    $conn = mysql_connect('localhost', 'root', 'admin');
    $db = mysql_select_db('Easyway',$conn);
    
    if(isset($_GET["vertrekadres"]) && is_numeric($_GET["vertrekadres"]))
    {
        $vertrekadres = $_GET["vertrekadres"];
    }
    
    if(isset($_GET["eindadres"]) && is_numeric($_GET["eindadres"]))
    {
        $eindadres = $_GET["eindadres"];
    }
    
    
    ?>
    
    <!DOCTYPE html>
    
    
    
     
    <html lang="en">
        <head>
            <meta charset="utf-8" />
            <title>Google Maps Example</title>
            <style type="text/css">
                body { font: normal 14px Verdana; }
                h1 { font-size: 24px; }
                h2 { font-size: 18px; }
                #sidebar { float: right; width: 30%; }
                #main { padding-right: 15px; }
                .infoWindow { width: 220px; }
            </style>
            <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
            <script type="text/javascript" language="javascript">
            
            //<![CDATA[
     
    
    
    function autoSubmit()
    {
        var formObject = document.forms['theForm'];
        formObject.submit();
    }
    
    
            
    var map;
     
    var center = new google.maps.LatLng(52.18740, 5.47119);
     
    var geocoder = new google.maps.Geocoder();
    var infowindow = new google.maps.InfoWindow();
     
    var directionsService = new google.maps.DirectionsService();
    var directionsDisplay = new google.maps.DirectionsRenderer();
     
    function init() {
         
        var mapOptions = {
          zoom: 9,
          center: center,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
         
        map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
         
        directionsDisplay.setMap(map);
        directionsDisplay.setPanel(document.getElementById('directions_panel'));
         
       function addOption(selectBox, text, value) {
        var option = document.createElement("OPTION");
        option.text = text;
        option.value = value;
        selectBox.options.add(option);
        
        
    }
         
       /*
     makeRequest('get_locations.php', function(data) {
             
            var data = JSON.parse(data.responseText);
            var selectBox = document.getElementById('destination');
             
            for (var i = 0; i < data.length; i++) {
                displayLocation(data[i]);
                addOption(selectBox, data[i]['Bedrijf_B'], data[i]['Eindadres']);
            }
        });
    */
        
        makeRequest('get_locations.php', function(data) {
             
            var data = JSON.parse(data.responseText);
            var selectBox = document.getElementById('start');
             
            for (var i = 0; i < data.length; i++) {
                displayLocation(data[i]);
                addOption(selectBox, data[i]['Bedrijf_A'], data[i]['Vertrekadres']);
            }
        });
    
        
    }
     
    function displayLocation(location) {
     
        var content =   '<div class="infoWindow"><strong>'  + location.Ritdatum + '</strong>'
                        + '<br/>'     + location.Vertrekpunt
                        + '<br/>'     + location.Opmerkingen + '</div>';
         
        if (parseInt(location.lat) == 0) {
            geocoder.geocode( { 'Vertrekpunt': location.Vertrekpunt }, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                     
                    var marker = new google.maps.Marker({
                        map: map, 
                        position: results[0].geometry.location,
                        title: location.name
                    });
                     
                    google.maps.event.addListener(marker, 'click', function() {
                        infowindow.setContent(content);
                        infowindow.open(map,marker);
                    });
                     
                    /* Save geocoding result to the Database
                    var url =   'set_coords.php?id=' + location.id 
                                + '&lat=' + results[0].geometry.location.lat() 
                                + '&lon=' + results[0].geometry.location.lng();
                     
                    makeRequest(url, function(data) {
                        if (data.responseText == 'OK') {
                            // Success
                        }
                    });*/
                }
            });
        } else {
             
            var position = new google.maps.LatLng(parseFloat(location.lat), parseFloat(location.lon));
            var marker = new google.maps.Marker({
                map: map, 
                position: position,
                title: location.name
            });
             
            google.maps.event.addListener(marker, 'click', function() {
                infowindow.setContent(content);
                infowindow.open(map,marker);
            });
        }
    }
     
    function addOption(selectBox, text, value) {
        var option = document.createElement("OPTION");
        option.text = text;
        option.value = value;
        selectBox.options.add(option);
    }
     
    function calculateRoute() {
         
        var start = document.getElementById('start').value;
        var destination = document.getElementById('destination').value;
         
        if (start == '') {
            start = center;
        }
         
        var request = {
            origin: start,
            destination: destination,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
            }
        });
    }
     
    function makeRequest(url, callback) {
        var request;
        if (window.XMLHttpRequest) {
            request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
        } else {
            request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
        }
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                callback(request);
            }
        }
        request.open("GET", url, true);
        request.send();
    }        //]]>
            </script>
            
            
        </head>
        
       <body onload="init();">
            
    
    <form name="theForm" method="get">
    
        <!-- Select Startadress-->
        
        <select name="vertrekadres" onChange="autoSubmit();" id="start">
            <option value="null"></option>
            <option value="1" <?php if($vertrekadres == 1) echo " selected"; ?>Amsterdam</option>
            <option value="2" <?php if($vertrekadres == 2) echo " selected"; ?>>Rotterdam</option>
        </select>
    
        <br><br>
    
    
         
     <!-- Filter Destination Adresses-->
      
        <select name="eindadres" id="destination">        
            <option value="null"></option>
            
            <?php
            
            
            $sql = "SELECT id, Eindadres FROM voertuigen WHERE vertrek_id = $vertrekadres";
            $vertrekadressen = mysql_query($sql,$conn);
            
            while($row = mysql_fetch_array($vertrekadressen))
            {        
                echo ("<option value=\"$row[id]\" " . ($vertrekadres == $row["id"] ? " selected" : "") . ">$row[Eindadres]</option>");        
            }
            
            ?>
            
        </select>
     <input type="button" value="Display Directions" onclick="calculateRoute();" />
    
    
    </form>          
       <section id="sidebar">
            <div id="directions_panel"></div>
        </section>
         
        <section id="main">
            <div id="map_canvas" style="width: 70%; height: 500px;"></div>
        </section>
          
       
             
        </body>
    </html>

  • #2
    Master Coder
    Join Date
    Jun 2003
    Location
    Cottage Grove, Minnesota
    Posts
    9,549
    Thanks
    8
    Thanked 1,095 Times in 1,086 Posts
    Might it be possible that you have reversed the lat and lng?

    This is hard for us to test because we can't use your database.
    Maybe you can give us a URL where we can your web page and see what is happening.

  • #3
    New to the CF scene
    Join Date
    Apr 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Ok, URL = http://213.10.156.115/easyway/googlemaps.php

    I don't use lat Lon for the locations. I just have street addresses. Amsterdam and woerden are just some examples. In real life that would be also addresses of
    lease companies.

    Tom

  • #4
    Master Coder
    Join Date
    Jun 2003
    Location
    Cottage Grove, Minnesota
    Posts
    9,549
    Thanks
    8
    Thanked 1,095 Times in 1,086 Posts
    I only see one drop box with city or location names.
    The 2nd select box is empty (no selections).

    <select name="eindadres" id="destination">
    <option value="null"></option>

    Something must be wrong with your query, or no destinations are loaded because of syntax errors ...

    I see a typo ... see red (missing)


    <option value="1" <?php if($vertrekadres == 1) echo " selected"; ?>>Amsterdam</option>

    Here's another one ... array designation within echo needs to be separated ...

    echo ("<option value=\"$row[id]\" " . ($vertrekadres == $row["id"] ? " selected" : "") . ">$row[Eindadres]</option>");

    Try this:

    $selected="";
    if($vertrekadres == $row[id]){
    $selected="selected";
    }
    echo ("<option value='".$row[id]."' " .$selected. ">".$row[Eindadres]."</option>");



    Just in case the "if" statement within the echo is an issue .. I removed it from the echo.
    messed-up quotes ... $row[id] and $row["id"] ... might be causing problems.


    Another Tip:
    Leave out all MySQL and "hardcode" the start and stop destinations without any PHP or MySQL.
    Get the Google javascripting to work BEFORE you deal with the PHP database.
    That eliminates any possibilities of PHP problems.



    .
    Last edited by mlseim; 04-17-2012 at 01:40 AM.

  • #5
    New to the CF scene
    Join Date
    Apr 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by mlseim View Post
    I only see one drop box with city or location names.
    The 2nd select box is empty (no selections).

    <select name="eindadres" id="destination">
    <option value="null"></option>

    Something must be wrong with your query, or no destinations are loaded because of syntax errors ...

    I see a typo ... see red (missing)


    <option value="1" <?php if($vertrekadres == 1) echo " selected"; ?>>Amsterdam</option>

    Here's another one ... array designation within echo needs to be separated ...

    echo ("<option value=\"$row[id]\" " . ($vertrekadres == $row["id"] ? " selected" : "") . ">$row[Eindadres]</option>");

    Try this:

    $selected="";
    if($vertrekadres == $row[id]){
    $selected="selected";
    }
    echo ("<option value='".$row[id]."' " .$selected. ">".$row[Eindadres]."</option>");



    Just in case the "if" statement within the echo is an issue .. I removed it from the echo.
    messed-up quotes ... $row[id] and $row["id"] ... might be causing problems.


    Another Tip:
    Leave out all MySQL and "hardcode" the start and stop destinations without any PHP or MySQL.
    Get the Google javascripting to work BEFORE you deal with the PHP database.
    That eliminates any possibilities of PHP problems.



    .
    The double >>Amsterdam</option is not a type. The first > closes the previous php statement. I will enclose a picture of the website and the database. The second selectbox gets filled by the php statement below it. If i choose let's say, Amsterdam it will give me all the places i've been to from there. So all Endaddresses (Eindadres) with $vertrekadres (Amsterdam) will be showed in the second select box. All those Eindadressen have 1 thing in common, vertrek_id.

    I deleted some functions because the weren't needed for the google maps route calculation.




    Shot at 2012-04-17
    Last edited by tommie20; 04-17-2012 at 06:22 PM. Reason: incomplete

  • #6
    Master Coder
    Join Date
    Jun 2003
    Location
    Cottage Grove, Minnesota
    Posts
    9,549
    Thanks
    8
    Thanked 1,095 Times in 1,086 Posts
    I'm still thinking that PHP/MySQL is messed up with your locations.

    Have you duplicated your script (as a test script), removed all PHP and MySQL,
    and were able to make it work between two locations? Do that first.
    Forget about PHP for now ... hard-code your two locations. Get the javascripting
    with Google Maps to work without any PHP involved.

  • #7
    New to the CF scene
    Join Date
    Apr 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by mlseim View Post
    I'm still thinking that PHP/MySQL is messed up with your locations.

    Have you duplicated your script (as a test script), removed all PHP and MySQL,
    and were able to make it work between two locations? Do that first.
    Forget about PHP for now ... hard-code your two locations. Get the javascripting
    with Google Maps to work without any PHP involved.
    Oke, the following code works. If i select Energieweg from the first select box the pages refreshes and only gives directions from meander 1061, Arnhem to Amsterdam. This has to do with the autosubmit function. If i leave that out it works on both adresses.

    Code:
    <!DOCTYPE html>
    
    
    
     
    <html lang="en">
        <head>
            <meta charset="utf-8" />
            <title>Google Maps Example</title>
            <style type="text/css">
                body { font: normal 14px Verdana; }
                h1 { font-size: 24px; }
                h2 { font-size: 18px; }
                #sidebar { float: right; width: 30%; }
                #main { padding-right: 15px; }
                .infoWindow { width: 220px; }
            </style>
            <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
            <script type="text/javascript" language="javascript">
            
            
    
    
    function autoSubmit()
    {
        var formObject = document.forms['theForm'];
        formObject.submit();
    }
    
    
            
    var map;
     
    var center = new google.maps.LatLng(52.18740, 5.47119);
     
    var geocoder = new google.maps.Geocoder();
    
     
    var directionsService = new google.maps.DirectionsService();
    var directionsDisplay = new google.maps.DirectionsRenderer();
     
    function init() {
         
        var mapOptions = {
          zoom: 9,
          center: center,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
         
        map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
         
        directionsDisplay.setMap(map);
        directionsDisplay.setPanel(document.getElementById('directions_panel'));
                 
      
    }
     
     
     
    function calculateRoute() {
         
        var start = document.getElementById('start').value;
        var destination = document.getElementById('destination').value;
         
        if (start == '') {
            start = center;
        }
         
        var request = {
            origin: start,
            destination: destination,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
            }
        });
    }
     
         
            </script>
            
            
        </head>
        
       <body onload="init();">
            
    
    <form name="theForm" method="get">
    
        <!-- Select Startadress-->
        
        <select name="vertrekadres" onChange="autoSubmit();" id="start">
            <option value="Meander 1061, Arnhem"  >Meander 1061, Arnhem</option>
            <option value="Energieweg 37, Meerkerk" >Energieweg 37, Meerkerk</option>
        </select>
    
        <br><br>
    
    
         
     <!-- Filter Destination Adresses-->
      
        <select name="eindadres" id="destination">        
            <option value="Amsterdam">Amsterdam</option>
            
    
            
        </select>
     <input type="button" value="Display Directions" onclick="calculateRoute();" />
    
    
    </form>          
       <section id="sidebar">
            <div id="directions_panel"></div>
        </section>
         
        <section id="main">
            <div id="map_canvas" style="width: 70%; height: 500px;"></div>
        </section>
          
       
             
        </body>
    </html>

  • #8
    Master Coder
    Join Date
    Jun 2003
    Location
    Cottage Grove, Minnesota
    Posts
    9,549
    Thanks
    8
    Thanked 1,095 Times in 1,086 Posts
    OK ... that's good ... now you know the PHP portion is what is causing the China issue.

    So, since I can't test anything that has to do with your PHP, you'll have to determine
    what the PHP is doing wrong. I also don't understand the "autosubmit" thing you
    mentioned.

    Why can't the PHP create the drop-down menus before you pick anything?

    Not much else I can do ... I don't have any access to your database, so I can't experiment with it.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •