3

I have fixed latitude, and longitude (lat, lng) values in my SQL database. Now I want to do following: when I enter the name of the city in the searchbox, on an onClick event it sends the data via POST to the php file, and makes a SQL query which returns the lat, lng data. I want to call the JavaScript function for loading the map with the lat, lng parameters from the PHP file. I want all this to happen on a simple onClick event.

Here is my JavaScript function which is supposed to initialize the map (the load() function):

function getFile() {
  if (window.XMLHttpRequest) {              
    AJAX=new XMLHttpRequest();              
  } else {                                  
    AJAX=new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (AJAX) {
    var searchField = document.getElementById("searchField");

    AJAX.open("POST", "gmap.php", false);                             
    AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    AJAX.setRequestHeader("Content-length", searchField.value.length);
    AJAX.setRequestHeader("Connection", "close");
         AJAX.send("foo=" + searchField.value);
     return load(AJAX.responseText);   

  } else {
     return false;
  }                                             
}

And here is my gmap.php file:

<?php
header( 'Content-Type: text/html; charset=UTF-8' );
mb_internal_encoding( 'UTF-8' );
$a = $_POST['searchField'];
$dbhost = "localhost";
$dbuser = "*******";
$dbpass = "*******";
$dbname = "citydb";



    //connect sql
mysql_connect($dbhost, $dbuser, $dbpass);

    //select db
mysql_select_db($dbname) or die(mysql_error());
    //retrieve data
//$city=$_GET['city'];
    //escape user input to help prevent SQL injection
//$city=mysql_real_escape_string($city);
    //query
mysql_query('SET CHARACTER SET utf8');
$result=mysql_query("SELECT citystart, cityend FROM cityids WHERE city='$a' ");
if(!result) {

    die("Database query failed: " . myql_error());
    }

while($row=mysql_fetch_array($result)) {


    $lat=$row['citystart'];
    $lng=$row['cityend'];

Here is the onClick call:

<input type="submit" class="regular" name="FindEv" value="FindEv" onClick="getFile(); return false;" />

The problem is that the JavaScript function load() is called before the PHP data has returned. I've spend over a week now to figure this out, but I cannot find the solution. I've tried eval(), I've also tried to call the load() function from PHP, which also failed because it is inside an onClick event, which is inside a div, so the load() function doesn't execute, it is only displayed inside the div, when I go on Inspect element i Firebug.

I'm talking about lat, lng values for GLatLng().

2 Answers 2

2

I actually did sort of the same thing with mysql. The google map API I used was a little different though.

    <!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 Map API Test</title>
    <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAh6DEO6zsM8Xua6WBNm-dbBRD8yUxCv4Esyhw4vpb86bE3mijaBS3Fcz1Rq_adaGcRea0Mlr9lNqAJw"
            type="text/javascript"></script>

    <script type="text/javascript">
    //<![CDATA[

    var iconBlue = new GIcon(); 
    iconBlue.image = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
    iconBlue.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
    iconBlue.iconSize = new GSize(12, 20);
    iconBlue.shadowSize = new GSize(22, 20);
    iconBlue.iconAnchor = new GPoint(6, 20);
    iconBlue.infoWindowAnchor = new GPoint(5, 1);

    var iconRed = new GIcon(); 
    iconRed.image = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
    iconRed.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
    iconRed.iconSize = new GSize(12, 20);
    iconRed.shadowSize = new GSize(22, 20);
    iconRed.iconAnchor = new GPoint(6, 20);
    iconRed.infoWindowAnchor = new GPoint(5, 1);

    var iconYellow = new GIcon(); 
    iconYellow.image = 'http://labs.google.com/ridefinder/images/mm_20_yellow.png';
    iconYellow.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
    iconYellow.iconSize = new GSize(12, 20);
    iconYellow.shadowSize = new GSize(22, 20);
    iconYellow.iconAnchor = new GPoint(6, 20);
    iconYellow.infoWindowAnchor = new GPoint(5, 1);

    var iconGreen = new GIcon(); 
    iconGreen.image = 'http://labs.google.com/ridefinder/images/mm_20_green.png';
    iconGreen.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
    iconGreen.iconSize = new GSize(12, 20);
    iconGreen.shadowSize = new GSize(22, 20);
    iconGreen.iconAnchor = new GPoint(6, 20);
    iconGreen.infoWindowAnchor = new GPoint(5, 1);

    var customIcons = [];
    customIcons["175"] = iconGreen;
    customIcons["200"] = iconGreen;
    customIcons["225"] = iconGreen;
    customIcons["250"] = iconBlue;
    customIcons["275"] = iconBlue;
    customIcons["300"] = iconBlue;
    customIcons["325"] = iconRed;
    customIcons["350"] = iconRed;
    customIcons["375"] = iconRed;
    customIcons["100"] = iconYellow;
    customIcons["125"] = iconYellow;
    customIcons["150"] = iconYellow;

    function load() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(39.8163, -98.55762), 4);

        GDownloadUrl("markerData.php", function(data) {
          var xml = GXml.parse(data);
          var markers = xml.documentElement.getElementsByTagName("marker");
          for (var i = 0; i < markers.length; i++) {
            var mapTime = markers[i].getAttribute("time");
            var mapSize = markers[i].getAttribute("size");
            var mapCity = markers[i].getAttribute("city");
            var mapState = markers[i].getAttribute("state");
            var mapPop = markers[i].getAttribute("pop");
            var type = markers[i].getAttribute("size");
            var mapComments = markers[i].getAttribute("comments");
            var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                                    parseFloat(markers[i].getAttribute("lng")));
            var marker = createMarker(point, mapTime, mapSize, mapCity, mapState, mapPop, mapComments, type);
            map.addOverlay(marker);
          }
        });
      }
    }

    function createMarker(point, mapTime, mapSize, mapCity, mapState, mapPop, mapComments, type) {
      var marker = new GMarker(point, customIcons[type]);
      var html = "Time: " + mapTime + "<br/>" + "Size: " + mapSize + "<br/>" + "Location: " + mapCity + ", " + mapState + "<br/>" + "Population: " + mapPop + "<br/>" + "Comments: " + mapComments;
      GEvent.addListener(marker, 'click', function() {
        marker.openInfoWindowHtml(html);
      });
      return marker;
    }
    //]]>
  </script>

  </head>

  <body onload="load()" onunload="GUnload()">
    <div id="map" style="width: 750px; height: 500px"></div>
    <div style="width: 750px; text-align: center"><img src="http://labs.google.com/ridefinder/images/mm_20_yellow.png" /> Less than 1.75"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
         <img src="http://labs.google.com/ridefinder/images/mm_20_green.png" /> 1.75" - 2.25"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
         <img src="http://labs.google.com/ridefinder/images/mm_20_blue.png" />2.50" - 3.00"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
         <img src="http://labs.google.com/ridefinder/images/mm_20_red.png" />3.25" - 3.75"
    </div>
  </body>
</html>

Map Info.php create_element("markers"); $parnode = $doc->append_child($node);

// Opens a connection to a MySQL server
$connection=mysql_connect ($host, $username, $password);
if (!$connection) {
    die('Not connected : ' . mysql_error()); 
}

// Set the active MySQL database 
$db_selected = mysql_select_db($database, $connection); 
if (!$db_selected) { 
    die ('Can\'t use db : ' . mysql_error()); 
}// Select all the rows in the markers table 
$query = "SELECT * FROM mapData WHERE 1";
$result = mysql_query($query);
if (!$result) {
    die('Invalid query: ' . mysql_error()); 
}

header("Content-type: text/xml"); 
// Iterate through the rows, adding XML nodes for each 
while ($row = @mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
    $node = $doc->create_element("marker");
    $newnode = $parnode->append_child($node);
    $newnode->set_attribute("time", $row['Time']);
    $newnode->set_attribute("size", $row['Size']);
    $newnode->set_attribute("city", $row['City']);
    $newnode->set_attribute("state", $row['State']);
    $newnode->set_attribute("pop", $row['Population']);
    $newnode->set_attribute("comments", $row['Comments']);
    $newnode->set_attribute("lat", $row['Latitude']);
    $newnode->set_attribute("lng", $row['Longitude']);
}
$xmlfile = $doc->dump_mem(); echo $xmlfile; 

?>

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, but you have fixed GLatLng(39.8163, -98.55762), i want this values (39.8163, -98.55762) to be read from SQL...
I see what you mean. let me see if I can make it move to those points with my lat lon reading
2

AJAX (keyword asynchronous) doesn't block the rest of the script from executing as you are expecting it to.

You have to check for a completed request using the onreadystatechange method...

AJAX.onreadystatechange = function() {
    if (AJAX.readyState == 4 && AJAX.status == 200) {
        load(AJAX.responseText);
    }
}

3 Comments

I've tried this earlier, same thing, the load() function executes before the php values are passed...
Did you remove the "return load(...)" line? If so, is load() called anywhere else? In the code I provided, it will only fire after PHP has returned values. Therefore, something else is wrong.
It isn't called anywhere else. I've really tried everything. I know, but it seems that it doesn't. The php file is ok, I've tested it several times...

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.