Google Maps v3 API右键单击只创建1个标记

时间:2014-04-10 13:53:08

标签: javascript jquery google-maps google-maps-api-3

我正在开发一个新项目,我是Google Maps API的新手。

我需要你的帮助才能在地图上只标记一个标记。我们的客户会通过右键单击指示他们的位置,并且只有他们删除现有标记后才会重新插入其位置。

我试过if和else,唯一的结果是地图没有加载。

我已经创建了一个代码小提琴,希望它有所帮助:http://jsfiddle.net/JG9bG/

$(document).ready(function () {
    var mapCenter = new google.maps.LatLng(39.39987199999999, -8.224454000000037); //Google map Coordinates
    var map;

    map_initialize(); // initialize google map

    //############### Google Map Initialize ##############
    function map_initialize() {
        var googleMapOptions = {
            center: mapCenter, // map center
            zoom: 7, //zoom level, 0 = earth view to higher value
            maxZoom: 18,
            minZoom: 7,
            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, "http://google.com/mapfiles/ms/micons/blue.png");
            });
        });

        //Right Click to Drop a New Marker

        myListener = 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="pid"><span> Property Id: </span><input type="text" readonly name="pid" class="save-propid" value="<?php echo $prop_id;?>" maxlength="40" /></label>' +
                '<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="Rent">Rent</option><option value="Sell">Sell</option><option value="Holiday Rentals">Holiday Rentals</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, 'Insert your Property Location', EditForm, true, true, true, "http://google.com/mapfiles/ms/micons/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: 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
                var mpid = contentString.find('input.save-propid')[0].value; //prop id

                if (mName == '' || mDesc == '') {
                    alert("Please enter Name and Description!");
                } else {
                    save_marker(marker, mName, mDesc, /*mType, */ mpid, 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 */
        if (Marker.getDraggable()) {
            Marker.setMap(null); //just remove new marker
        } else {
            //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: "http://.../.../.../cpanel.php?exe=client_properties/google/map_process",
                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, */ mpid, 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, */
            propid: mpid
        }; //post variables
        console.log(replaceWin);
        $.ajax({
            type: "POST",
            url: "http://.../.../.../cpanel.php?exe=client_properties/google/map_process",
            data: myData,
            success: function (data) {
                replaceWin.html(data); //replace info window with new html
                Marker.setDraggable(false); //set marker to fixed
                Marker.setIcon('http://google.com/mapfiles/ms/micons/blue.png'); //replace icon
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(thrownError); //throw any errors
            }
        });
    }
});

感谢您的帮助

后端:

    <?php
//PHP 5 +

// database settings 
$db_username = '';
$db_password = '';
$db_name = '';
$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 tblmarkers WHERE geo_lat=$mLat AND geo_lng=$mLng");
        if (!$results) {  
          header('HTTP/1.1 500 Error: Could not delete Marker!'); 
          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);*/
    $mpid       = filter_var($_POST["propid"], FILTER_SANITIZE_STRING);

    $results = $mysqli->query("INSERT INTO tblmarkers (geo_name, geo_address, geo_lat, geo_lng, prop_id) VALUES ('$mName','$mAddress',$mLat, $mLng, '$mpid')");

/*  $results = $mysqli->query("INSERT INTO tblmarkers (geo_name, geo_address, geo_lat, geo_lng, geo_type, prop_id) VALUES ('$mName','$mAddress',$mLat, $mLng, '$mType', '$mpid')");*/


    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 tblmarkers 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("geo_name",$obj->name);
  $newnode->setAttribute("geo_address", $obj->address);  
  $newnode->setAttribute("geo_lat", $obj->lat);  
  $newnode->setAttribute("geo_lng", $obj->lng);  
  $newnode->setAttribute("geo_type", $obj->type);   
}

echo $dom->saveXML();

2 个答案:

答案 0 :(得分:1)

试试这个:

google.maps.event.addListener(map, "rightclick",function(event){
    marker = new google.maps.Marker({
    position: event.latLng, 
    title: 'Changer la position',
    map: map,
    draggable: true
});

这是一个例子:http://jsfiddle.net/hweb/M7K4L/

答案 1 :(得分:0)

一个选项:

  • 全局声明标记(在任何函数定义之外):

    var marker = null;
    
  • 检查它是否存在,是否在新地点创建之前将其删除:

    function create_marker(MapPos, MapTitle, MapDesc, InfoOpenDefault, DragAble, Removable, iconPath) {
      if ((marker != null) && marker.setMap) {
        marker.setMap(null); 
        marker = null;
      }
      //new marker
      marker = new google.maps.Marker({
        position: MapPos,
        map: map,
        draggable: DragAble,
        animation: google.maps.Animation.DROP,
        title: "Hello World!",
        icon: iconPath
      });
    

working fiddle