拖动标记时更新mysqli数据库中的lat和lng

时间:2016-07-22 18:39:22

标签: javascript php google-maps google-maps-api-3 mysqli

我有一张地图,里面有许多从mysqli数据库加载的标记。我已经使用本教程(https://www.sanwebe.com/2013/10/google-map-v3-editing-saving-marker-in-database)来达到这一点。我需要的是能够在移动标记时拖动标记并更新数据库。我已经为调用函数的dragend添加了一个监听器。我试图添加update_marker函数,但它不起作用。我不确定是否尝试使用ID或maptitle进行更新 - 所有标记在db中都有不同的名称。任何方向都会有所帮助。感谢。

的index.php

//############### 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: MapTitle,
        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+'</h1>'+
    iconPath+ 
    '</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);
    });

    google.maps.event.addListener(marker, 'dragend', function() {
        var mytitle = marker.getTitle(); //get marker position
        update_marker(marker, mytitle);
            alert('Marker dropped');
            alert(mytitle);
            });


    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);
    }
}

//############### Remove Marker Function ##############
function remove_marker(Marker)
{


        //Remove saved marker from DB and map using jQuery Ajax
        var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
        var myData = {del : 'true', latlang : mLatLang}; //post variables
        $.ajax({
          type: "POST",
          url: "map_process.php",
          data: myData,
          success:function(data){
                Marker.setMap(null); 
                alert(data);
            },
            error:function (xhr, ajaxOptions, thrownError){
                alert(thrownError); //throw any errors
            }
        });
    }

    //############### Update Marker Function ##############
function update_marker(Marker, mytitle)
{


        //Update saved marker from DB and map using jQuery Ajax
        var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
        var mytitle = Marker.getTitle(); //get marker position
        var myData = {update : 'true', name : mytitle, latlang : mLatLang}; //post variables
        $.ajax({
          type: "POST",
          url: "map_process.php",
          data: myData,
          success:function(data){
                alert(data);
            },
            error:function (xhr, ajaxOptions, thrownError){
                alert(mLatLang); //throw any errors
            }
        });
    }



//############### Save Marker Function ##############
function save_marker(Marker, mName, mAddress, mType, replaceWin)
{
    //Save new marker using jQuery Ajax
    var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
    var myData = {name : mName, address : mAddress, latlang : mLatLang, type : mType }; //post variables
    console.log(replaceWin);        
    $.ajax({
      type: "POST",
      url: "map_process.php",
      data: myData,
      success:function(data){
            replaceWin.html(data); //replace info window with new html
            Marker.setDraggable(false); //set marker to fixed
            Marker.setIcon('blue-pin.png'); //replace icon
        },
        error:function (xhr, ajaxOptions, thrownError){
            alert(thrownError); //throw any errors
        }
    });
}

});
</script>

<style type="text/css">
h1.heading{padding:0px;margin: 0px 0px 10px 0px;text-align:center;font:     18px Georgia, "Times New Roman", Times, serif;}

 /* width and height of google map */
#google_map {width: 90%; height: 500px;margin-top:0px;margin-left:auto;margin-right:auto;}

  /* Marker Edit form */
.marker-edit label{display:block;margin-bottom: 5px;}
.marker-edit label span {width: 100px;float: left;}
 .marker-edit label input, .marker-edit label select{height: 24px;}
.marker-edit label textarea{height: 60px;}
.marker-edit label input, .marker-edit label select, .marker-edit label     textarea {width: 60%;margin:0px;padding-left: 5px;border: 1px solid     #DDD;border-radius: 3px;}

/* Marker Info Window */
h1.marker-heading{color: #585858;margin: 0px;padding: 0px;font: 18px     "Trebuchet MS", Arial;border-bottom: 1px dotted #D8D8D8;}
div.marker-info-win {max-width: 300px;margin-right: -20px;}
div.marker-info-win p{padding: 0px;margin: 10px 0px 10px 0;}
div.marker-inner-win{padding: 5px;}
button.save-marker, button.remove-marker{border: none;background: rgba(0,     0, 0, 0);color: #00F;padding: 0px;text-decoration:     underline;margin-right: 10px;cursor: pointer;
}
 </style>
 </head>
 <body>             
<h1 class="heading">My Google Map</h1>
<div align="center">Right Click to Drop a New Marker</div>
<div id="google_map"></div>
</body>
</html>    

map_process.php

################ 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);


//Update Marker
if(isset($_POST["update"]) && $_POST["update"]==true)
{
    $results = $mysqli->query("INSERT INTO markers (lat, lng) VALUES ($mLat, $mLng) WHERE name=mytitle");
    if (!$results) {  
      header('HTTP/1.1 500 Error: Could not Update Markers!'); 
      exit();
    } 
    exit("Updated!");
}




$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);

}

UPDATE ////////// 我编辑了代码,以显示当前尝试即时制作。我可以从update_marker获取警报,该警报显示移动标记时的latlng,或者我可以更改它并获得标题。那些工作。我可能没有正确地将数据发送到map_process.php或让它选择正确的记录。删除和保存查询在post函数中运行,并且正在调用更新查询,因为我得到HTTP / 1.1 500错误:无法更新标记!&#39;警报。

1 个答案:

答案 0 :(得分:0)

我从这个页面找到了它 - https://www.sanwebe.com/2013/03/basic-php-mysqli-usage#update-a-record-我没有在我的更新查询周围使用刻度线!它杀死的小东西

$results = $mysqli->query("UPDATE markers SET lat='$mLat', lng='$mLng' WHERE name='$mName'");