Results 1 to 5 of 5

Thread: Loading javascript content dynamically into Google map javascript

  1. #1
    Join Date
    Jan 2008
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Loading javascript content dynamically into Google map javascript

    Hi, I'm using ajax with php for getting information from mysql database. My problem is how to put the code (latitudes, longitudes) into google javascript file (not into div in the body section) and also how to load the map to see changes.

    The purpose of this script is to show ships route on google map on defined date (javascript).

    So it should put "new GLatLng(lat,long)," - values into javascript file.

    ------------------- index.html: -------------------------
    HTML Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <title>Google Maps JavaScript API Example</title>
        <script src="selectuser.js"></script>
        <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAA8932eZOB5JEYtvZPasq4FxQ54HRG6gq8VpzycMbCIkcuTGCE9hRMM
    9j97YB3eghRasY7q3LcbbWseg"
          type="text/javascript"></script>
          <script type="text/javascript">
    	function load() {
            //<![CDATA[
    	if (GBrowserIsCompatible()) {
    		var map = new GMap2(document.getElementById("map"));
    		map.addControl(new GSmallMapControl());
    		map.addControl(new GMapTypeControl());
    		map.setCenter(new   
     GLatLng(60.1766666666667,25.776666666666), 6);
    		var polyline = new GPolyline([                           
    ********************** Here is where the code should be put **********************
    	new GLatLng(60.1592,24.9227),
    	new GLatLng(60.1592,12.4257),
    	], "#ff0000", 3, 0.9);
    	map.addOverlay(polyline);
          }
          //]]>
        }
    
    
        </script>
        
      </head>
      <body onload="load()" onunload="GUnload()">
        <h2>Arandan matka Combine4/2007</h2>
        Alkoi: 2007-12-10 12:30:00 ja p&auml;&auml;ttyi: 2007-12-14 07:35:00
        <h3>Hae tiedot:</h3>
        Anna aloitusaika, askelv&auml;li (yksi askel on noin 10s) ja esitett&auml;vien rivien m&auml;&auml;r&auml;. 
      <form>
     
    	steppi: <input id="steppi" name="steppi" value="60" type="text"> Alkuaika: <input id="startti" name="startti" type="text" value="2007-12-10 12:30:00"> limit: <input id="limitti" name="limitti" value="10" type="text">
       
    	<input type="button" value="Hae" onclick="showUser(steppi.value, startti.value, limitti.value)" ></form>
    	<div id="txtHint"></div>	
    	<div id="map" style="width: 500px; height: 400px"></div>
      </body>
    </html>
    ---------------------- selectuser.js: ----------------------------
    Code:
    var xmlHttp
    
    function showUser(steppi, start, limitti)
    { 
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
     {
     alert ("Browser does not support HTTP Request")
     return
     }
    var url="getuser.php"
    url= url + "?q=" + steppi + "&s=" + start + "&l=" + limitti
    url=url+"&sid="+Math.random()
    xmlHttp.onreadystatechange=stateChanged 
    xmlHttp.open("GET",url,true)
    xmlHttp.send(null)
    }
    
    function stateChanged() 
    { 
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
     { 
     document.getElementById("txtHint").innerHTML=xmlHttp.responseText 
     } 
    }
    
    function GetXmlHttpObject()
    {
    var xmlHttp=null;
    try
     {
     // Firefox, Opera 8.0+, Safari
     xmlHttp=new XMLHttpRequest();
     }
    catch (e)
     {
     //Internet Explorer
     try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
     catch (e)
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
     }
    return xmlHttp;
    }
    --------------------------- getuser.php ----------------------------------
    PHP Code:
    <?php
    $q
    =$_GET["q"];
    $s=$_GET["s"];
    $l=$_GET["l"];
    $con mysql_connect('localhost''user''password');
    if (!
    $con)
     {
     die(
    'Could not connect: ' mysql_error());
     }

    mysql_select_db("awc"$con);

    $sql="SELECT * FROM locations WHERE mod(Id,".$q." ) = 0 AND str_to_date('".$s."','%Y-%m-%d %T') > ReceiveTime limit " .$l"";

    // str_to_date('".$s."','%Y-%m-%d %k:%i:%s')
    $result mysql_query($sql);

    echo 
    "<table border='1'>
    <tr>
    <th>Id</th>
    <th>Latitude</th>
    <th>Longitude</th>
    <th>Datumcode</th>
    <th>ReceiveTime</th>
    </tr>"
    ;

    while(
    $row mysql_fetch_array($result))
     {
     echo 
    "<tr>";
     echo 
    "<td>" $row['Id'] . "</td>";
     echo 
    "<td>" $row['Latitude'] . "</td>";
     echo 
    "<td>" $row['Longitude'] . "</td>";
     echo 
    "<td>" $row['DatumCode'] . "</td>";
     echo 
    "<td>" $row['ReceiveTime'] . "</td>";
     echo 
    "</tr>";
     }
    echo 
    "</table>";

    mysql_close($con);
    ?>
    Last edited by stereotyyppi; 01-15-2008 at 08:32 AM.

  2. #2
    Join Date
    May 2007
    Location
    Canada
    Posts
    85
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    I assume that you are able to get the latitude and longitude information from your database using ajax. Once you have the data it will invoke your stateChanged() function

    In there you can call another function that can add the polylines directly on the google map, or you can do it in that function as well. Just make sure that you are able to access the "map" variable, which created the map. Create the polylines just like you did in your "load()" function

    var polyline = new GPolyline([.....

    now add the polylines to your map.

    You may have to remove the polylines using map.removeOverlay method and then add it.

    Let me know if this helps.

  3. #3
    Join Date
    Jan 2008
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Hi, thanks for reply.

    I did as you said, but the map is drawn empty. Maybe The google script doesn't support string code that "var coordinates" has.

    ------------- Here is the php code: ------------- (getuser.php)
    PHP Code:
    <?php
    $q
    =$_GET["q"];
    $s=$_GET["s"];
    $l=$_GET["l"];
    $con mysql_connect('localhost''username''password');
    if (!
    $con)
     {
     die(
    'Could not connect: ' mysql_error());
     }

    mysql_select_db("awc"$con);

    $sql="SELECT * FROM locations WHERE mod(Id,".$q." ) = 0 AND str_to_date('".$s."','%Y-%m-%d %T') > ReceiveTime limit " .$l"";

    // str_to_date('".$s."','%Y-%m-%d %k:%i:%s')
    $result mysql_query($sql);



    while(
    $row mysql_fetch_array($result))
     {

     echo 
    "new Glatlng(" $row['Latitude'] . "," $row['Longitude'] . "),";

     }


    mysql_close($con);
    ?>
    --------------- And-here is the javascript: -------------- (selectuser.js)

    Code:
    var xmlHttp
    
    function showUser(steppi, start, limitti)
    { 
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
     {
     alert ("Browser does not support HTTP Request")
     return
     }
    var url="getuser.php"
    url= url + "?q=" + steppi + "&s=" + start + "&l=" + limitti
    url=url+"&sid="+Math.random()
    xmlHttp.onreadystatechange=stateChanged 
    xmlHttp.open("GET",url,true)
    xmlHttp.send(null)
    }
    
    function stateChanged() 
    { 
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
     {  
      
      var coordinates = xmlHttp.responseText;
      	
            if (GBrowserIsCompatible()) {
    		var map = new GMap2(document.getElementById("map"));
    		map.addControl(new GSmallMapControl());
    		map.addControl(new GMapTypeControl());
    		map.setCenter(new GLatLng(60.1766666666667,25.776666666666), 6);
    		var polyline = new GPolyline([                           
    			
    	new GLatLng(60.1592,24.9227),
    	+ coordinates +
    	new GLatLng(60.1592,12.9257),
    	], "#ff0000", 3, 0.9);
    	map.addOverlay(polyline);
          }
    }
    }
    
    
    function GetXmlHttpObject()
    {
    var xmlHttp=null;
    try
     {
     // Firefox, Opera 8.0+, Safari
     xmlHttp=new XMLHttpRequest();
     }
    catch (e)
     {
     //Internet Explorer
     try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
     catch (e)
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
     }
    return xmlHttp;
    }
    ---------------- And lastly index.html --------------------
    HTML Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <title>Google Maps JavaScript API Example</title>
        <script src="selectuser.js"></script>
        <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAA8932eZOB5JEYtvZPasq4FxQ54HRG6gq8VpzycMbCIkcuTGCE9hRMM
    9j97YB3eghRasY7q3LcbbWseg"
          type="text/javascript"></script>
    
        
      </head>
      <body>
        <h2>Arandan matka Combine4/2007</h2>
        Alkoi: 2007-12-10 12:30:00 ja p&auml;&auml;ttyi: 2007-12-14 07:35:00
        <h3>Hae tiedot:</h3>
        Anna aloitusaika, askelv&auml;li (yksi askel on noin 10s) ja esitett&auml;vien rivien m&auml;&auml;r&auml;. 
    	
        <form>
     
    	steppi: <input id="steppi" name="steppi" value="60" type="text"> Alkuaika: <input id="startti" name="startti" type="text" value="2009-12-10 12:30:00"> limit: <input id="limitti" name="limitti" value="10" type="text">
       
    	<input type="button" value="Hae" onclick="showUser(steppi.value, startti.value, limitti.value);load()" >
    	
    
    
    	<div id="map" style="width: 500px; height: 400px"></div>
      </body>
    </html>

  4. #4
    Join Date
    May 2007
    Location
    Canada
    Posts
    85
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Just a suggestion. Add the following in your external javascript file and call the load function like you had it before as body onLoad
    HTML Code:
           var map ;
            var polyline ;
    
    	function load() {
    	if (GBrowserIsCompatible()) {
    		map = new GMap2(document.getElementById("map"));
    		map.addControl(new GSmallMapControl());
    		map.addControl(new GMapTypeControl());
    		map.setCenter(new   
     GLatLng(60.1766666666667,25.776666666666), 6);
    		var polyline = new GPolyline([
    	new GLatLng(60.1592,24.9227),
    	new GLatLng(60.1592,12.4257),
    	], "#ff0000", 3, 0.9);
    	map.addOverlay(polyline);
          }
        }
    }
    Now, when the body loads, your google map should be showing up. Let's try modifying the following function

    HTML Code:
    function stateChanged() 
    { 
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
     { 
         var coordinates = xmlHttp.responseText;
         map.removeOverlay(polyline) ;
         polyline = new GPolyline([                           
    			
    	new GLatLng(60.1592,24.9227),
    	+ coordinates +
    	new GLatLng(60.1592,12.9257),
    	], "#ff0000", 3, 0.9);
    
         map.addOverlay(polyline);
     }
    I know it's almost the same as before. You should've been able to see the map instead of having it empty.

    polyline = new GPolyline([

    new GLatLng(60.1592,24.9227),
    + coordinates +
    new GLatLng(60.1592,12.9257),
    ], "#ff0000", 3, 0.9);

    I don't think the above is valid syntax. Did you try debugging your script and see if your had syntax error in these lines.

    I think what you can do is, when you are getting the coordinates from your database, instead of echoing it like below:

    echo "new Glatlng(" . $row['Latitude'] . "," . $row['Longitude'] . "),";

    do it without the "new Glatlng" part. Simply return the actual values separated by some special characters. Then in your stateChanged function in your javascript, when you get all the values in

    var coordinates = xmlHttp.responseText;

    You can parse through all the values and then go ahead from there.

    Do you have a link you can post?

  5. #5
    Join Date
    Jan 2008
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Hi, I have now working version in this site:

    http://gmaps.fimr.fi/cruises/awc.html

    only problem is that when zoomed in the gpolyline disappears. This might be bug in google Map api.

    Sincerely Juha

Bookmarks

Posting Permissions

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