谷歌地图MySQL经纬度转换为JavaScript。

3
我有一个SQL数据库,其中包含固定的纬度和经度(lat、lng)值。现在我想要实现以下功能:当我在搜索框中输入城市名称并单击时,它会通过POST方式将数据发送到php文件,并进行SQL查询以返回lat、lng数据。我想要调用JavaScript函数来加载地图,并从PHP文件获取lat、lng参数。我希望所有这些都在简单的onClick事件中发生。
以下是我的JavaScript函数,用于初始化地图(load()函数):
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;
  }                                             
}

这是我的gmap.php文件:

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

这是 onClick 的调用:

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

问题在于JavaScript函数load()在PHP数据返回之前被调用。我已经花了一周的时间来解决这个问题,但是我找不到解决方案。我尝试过使用eval(),也尝试从PHP中调用load()函数,但失败了,因为它在一个onClick事件内部,该事件在一个div内部,所以load()函数不会执行,只会在div内部显示,当我在Firebug中检查元素时。我谈论的是GLatLng()的lat、lng值。
2个回答

2

我之前也在mysql方面做了类似的事情。不过,我使用的google地图API略有不同。

    <!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>

地图信息.php create_element("标记"); $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; 

?>


1
是的,但您已经固定了GLatLng(39.8163,-98.55762),我希望这些值(39.8163,-98.55762)从SQL中读取... - digitale
1
我明白你的意思。让我看看是否可以使用我的经纬度读数将其移动到那些点。 - shinjuo

2

AJAX(关键字异步)不会像您预期的那样阻止脚本的其余部分执行。

您需要使用onreadystatechange方法检查已完成的请求...

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

1
我之前尝试过这个,同样的问题,load()函数在php值传递之前执行... - digitale
1
你移除了 "return load(...)" 这行代码吗?如果是,那么 load() 函数在其他地方被调用了吗?在我提供的代码中,它只会在 PHP 返回值之后触发。因此,还有其他问题。 - simshaun
1
它在其他任何地方都没有被调用。我真的尝试了所有方法。我知道,但似乎不起作用。php文件没问题,我已经测试过几次了... - digitale

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接