移动谷歌地图标记点时用纬度和经度更新数据库

Posted

技术标签:

【中文标题】移动谷歌地图标记点时用纬度和经度更新数据库【英文标题】:Update db with latitude and longitude when google map marker point is move 【发布时间】:2013-11-10 09:31:51 【问题描述】:

嗯,我有一个谷歌地图,所有经纬度都来自 db,它显示在地图上。

我可以用这张地图做什么:

1)我可以在地图上右键创建新点, 2)我可以删除现有的点。

现在你能告诉我当现有标记点移动到另一个地方时,我如何用新的纬度和经度更新数据库?

您可以在 www.creativeartbd.com/map 上查看我的实时地图

Index.php 页面代码:

<!DOCTYPE html>
<html>
<head>
<title>Google Map</title>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api    
/js?sensor=false"></script>
<script type="text/javascript">
$(document).ready(function() 

var mapCenter = new google.maps.LatLng(23.721869, 90.390518); //Google map 
Coordinates
var map;

map_initialize(); // initialize google map

//############### Google Map Initialize ##############
function map_initialize()

        var googleMapOptions = 
         
            center: mapCenter, // map center
            zoom: 15, //zoom level, 0 = earth view to higher value
            maxZoom: 15,
            minZoom: 5,
            zoomControlOptions: 
        style: google.maps.ZoomControlStyle.SMALL //zoom control size
        ,
    scaleControl: true, // enable scale control             
    mapTypeId: google.maps.MapTypeId.ROADMAP // google map type
        ;

map = new google.maps.Map(document.getElementById("google_map"), 
googleMapOptions);          

        //Load Markers from the XML File, Check (map_process.php)
        $.get("map_process.php", function (data) 
            $(data).find("marker").each(function () 
          var name      = $(this).attr('name');
          var address   = '<p>'+ $(this).attr('address') +'</p>';
          var type      = $(this).attr('type');
          var point     = new 
google.maps.LatLng(parseFloat($(this).attr('lat')),parseFloat($(this).attr('lng')));
create_marker(point, name, address, false, false, false, "icons/pin_blue.png");
            );
        ); 

        //Right Click to Drop a New Marker
        google.maps.event.addListener(map, 'rightclick', function(event) 
            //Edit form to be displayed with new marker
var EditForm = '<p><div class="marker-edit">'+
'<form action="ajax-save.php" method="POST" name="SaveMarker" id="SaveMarker">'+
'<label for="pName"><span>Place Name :</span><input type="text" name="pName" 
class="save-name" placeholder="Enter Title" maxlength="40" /></label>'+
'<label for="pDesc"><span>Description :</span><textarea name="pDesc" class="save-desc" 
placeholder="Enter Address" maxlength="150"></textarea></label>'+
'<label for="pType"><span>Type :</span> <select name="pType" class="save-type"><option 
value="restaurant">Rastaurant</option><option value="bar">Bar</option>'+
'<option value="house">House</option></select></label>'+
'</form>'+
'</div></p><button name="save-marker" class="save-marker">Save Marker 
Details</button>';

//Drop a new Marker with our Edit Form
create_marker(event.latLng, 'New Marker', EditForm, true, true, true, 
"icons/pin_green.png");
        );



//############### 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:true,
        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);
    


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


    /* determine whether marker is draggable 
    new markers are draggable and saved markers are fixed */

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




//############### 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(true); //set marker to fixed
            Marker.setIcon('icons/pin_blue.png'); //replace icon
        ,
        error:function (xhr, ajaxOptions, thrownError)
            alert(thrownError); //throw any errors
        
    );


);
</script>


</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 代码

// database settings 
$db_username = 'username';
$db_password = 'pass';
$db_name = 'db';
$db_host = 'my host';

//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!'); 
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();

非常感谢您的帮助:)

【问题讨论】:

【参考方案1】:

您应该为标记添加一个偶数侦听器,该侦听器在标记被放下时触发。

// adds an event listener on the marker. 
// The event is fired when the marker is dropped in this case
google.maps.event.addListener(marker, 'dragend', function() 
    alert('Marker dropped');
);

别忘了设置标记选项draggable:true

这里是 Marker 类的方法和事件的文档:google.maps.Marker

这里是jsFiddle的演示

【讨论】:

以上是关于移动谷歌地图标记点时用纬度和经度更新数据库的主要内容,如果未能解决你的问题,请参考以下文章

移动地图时,在谷歌地图中更新Ajax Json数组中的标记

将数据库中的多个纬度/经度点加载到谷歌地图标记中的好方法?

如何将谷歌地图标记的纬度和经度发送到 Firebase - android? [关闭]

我想通过从 json 获取经度和纬度在谷歌地图上显示标记

如何在 JPG 地图上叠加经度和纬度标记?

检查纬度和经度是不是在我的谷歌地图起点和终点范围内