谷歌地图没有从mysql数据库加载点

Google Maps not loading points from a mysql database

本文关键字:数据库 加载 mysql 谷歌地图      更新时间:2023-09-26

我将按照本教程通过表单窗口在谷歌地图上放置标记并将其保存到数据库中。一切都很好,但是地图加载时没有从数据库加载标记。在我的main.php文件(包含所有html)中,我运行了这个函数来在地图上放置标记。

//############### Create Marker Function ##############
function create_marker(MapPos, MapTitle, MapDesc,  InfoOpenDefault, DragAble, Removable, iconPath)
{                 
    //new marker
    var marker = new google.maps.Marker({
        position: MapPos,
        map: map,
        draggable:DragAble,
        animation: google.maps.Animation.DROP,
        title:"Hello World!",
        //icon: iconPath
    });
    //Content structure of info Window for the Markers
    var contentString = $('<div class="marker-info-win">'+
    '<div class="marker-inner-win"><span class="info-content">'+
    '<h1 class="marker-heading">'+MapTitle+'</h1>'+
    MapDesc+ 
    '</span><button name="remove-marker" class="remove-marker" title="Remove Marker">Remove Marker</button>'+
    '</div></div>');    

    //Create an infoWindow
    var infowindow = new google.maps.InfoWindow();
    //set the content of infoWindow
    infowindow.setContent(contentString[0]);
    //Find remove button in infoWindow
    var removeBtn   = contentString.find('button.remove-marker')[0];
    var saveBtn     = contentString.find('button.save-marker')[0];
    //add click listner to remove marker button
    google.maps.event.addDomListener(removeBtn, "click", function(event) {
        remove_marker(marker);
    });
    if(typeof saveBtn !== 'undefined') //continue only when save button is present
    {
        //add click listner to save marker button
        google.maps.event.addDomListener(saveBtn, "click", function(event) {
            var mReplace = contentString.find('span.info-content'); //html to be replaced after success
            var mName = contentString.find('input.save-name')[0].value; //name input field value
            var mDesc  = contentString.find('textarea.save-desc')[0].value; //description input field value
            var mType = contentString.find('select.save-type')[0].value; //type of marker
            if(mName =='' || mDesc =='')
            {
                alert("Please enter Name and Description!");
            }else{
                save_marker(marker, mName, mDesc, mType, mReplace); //call save marker function
            }
        });
    }
    //add click listner to save marker button        
    google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map,marker); // click on marker opens info window 
    });
    if(InfoOpenDefault) //whether info window should be open by default
    {
      infowindow.open(map,marker);
    }
}

在我的map_process.php文件(处理数据库请求的文件)中我有这个:

<?php
//PHP 5 +
// database settings 
$db_username = 'user4321';
$db_password = '4321';
$db_name = 'test';
$db_host = 'localhost';
//mysqli
$mysqli = new mysqli($db_host, $db_username, $db_password, $db_name);
if (mysqli_connect_errno()) 
{
    header('HTTP/1.1 500 Error: Could not connect to db!'); 
    exit();
}
################ Save & delete markers #################
if($_POST) //run only if there's a post data
{
    //make sure request is comming from Ajax
    $xhr = $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'; 
    if (!$xhr){ 
        header('HTTP/1.1 500 Error: Request must come from Ajax!'); 
        exit(); 
    }
    // get marker position and split it for database
    $mLatLang   = explode(',',$_POST["latlang"]);
    $mLat       = filter_var($mLatLang[0], FILTER_VALIDATE_FLOAT);
    $mLng       = filter_var($mLatLang[1], FILTER_VALIDATE_FLOAT);
    //Delete Marker
    if(isset($_POST["del"]) && $_POST["del"]==true)
    {
        $results = $mysqli->query("DELETE FROM markers WHERE lat=$mLat AND lng=$mLng");
        if (!$results) {  
          header('HTTP/1.1 500 Error: Could not delete Markers!'); 
          exit();
        } 
        exit("Done!");
    }
    $mName      = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
    $mAddress   = filter_var($_POST["address"], FILTER_SANITIZE_STRING);
    $mType      = filter_var($_POST["type"], FILTER_SANITIZE_STRING);
    $results = $mysqli->query("INSERT INTO markers (name, address, lat, lng, type) VALUES ('$mName','$mAddress',$mLat, $mLng, '$mType')");
    if (!$results) {  
          header('HTTP/1.1 500 Error: Could not create marker!'); 
          exit();
    } 
    $output = '<h1 class="marker-heading">'.$mName.'</h1><p>'.$mAddress.'</p>';
    exit($output);
}

################ Continue generating Map XML #################
//Create a new DOMDocument object
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers"); //Create new element node
$parnode = $dom->appendChild($node); //make the node show up 
// Select all the rows in the markers table
$results = $mysqli->query("SELECT * FROM markers WHERE 1");
if (!$results) {  
    header('HTTP/1.1 500 Error: Could not get markers!'); 
    //console.log("This an error");
    exit();
} 
//set document header to text/xml
header("Content-type: text/xml"); 
// Iterate through the rows, adding XML nodes for each
while($obj = $results->fetch_object())
{
  $node = $dom->createElement("marker");  
  $newnode = $parnode->appendChild($node);   
  $newnode->setAttribute("name",$obj->name);
  $newnode->setAttribute("address", $obj->address);  
  $newnode->setAttribute("lat", $obj->lat);  
  $newnode->setAttribute("lng", $obj->lng);  
  $newnode->setAttribute("type", $obj->type);   
}
echo $dom->saveXML();
?>

现在我似乎找不到为什么它一开始就没有加载标记的来源。考虑到我所有其他的命名都是正确的,上面的任何代码都不正确吗。

edit:我在控制台中得到了一个500(内部服务器错误),但我看不出这是问题所在,因为我正在测试另一个地图,它正确地加载了保存的点。的格式为'GET' serveraddress/mapprocess.php (500 internal server error)。不确定这是否有帮助,但在保存标记(成功保存)后,我会得到XHR finished loading: GET "severaddress/mapprocess.php"作为响应。

有没有关于为什么这不会加载标记的想法。或者我应该去哪里找。

我知道它可能已经晚了,但它不起作用的原因是从mysql返回的数据(即经度和纬度)可能是字符串格式的,而谷歌地图api需要经度和纬度的浮点值,因此使用Javascript中的parseFloat()将接收到的值转换为浮点值。