IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

APIs Google Discussion :

Sauvegarde des markers


Sujet :

APIs Google

  1. #1
    Candidat au Club
    Inscrit en
    Octobre 2009
    Messages
    4
    Détails du profil
    Informations forums :
    Inscription : Octobre 2009
    Messages : 4
    Points : 2
    Points
    2
    Par défaut Sauvegarde des markers
    Bonjour à tous,

    J'utilise depuis peu l'API GoogleMaps et j'ai déjà pu pondre quelques trucs chouettes. Cependant, j'ai un problème que je n'arrive pas à débugger lors de la sauvegarde d'un marker dans la base de données.
    Une erreur "Not Found" m'arrive en Pop-up !

    Voici l'index.ctp :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
        $(document).ready(function() {
     
            var mapCenter = new google.maps.LatLng(46.748952, 7.170837); //Google map Coordinates
            var map;
     
            map_initialize(); // initialize google map
     
            //############### Google Map Initialize ##############
            function map_initialize()
            {
                var googleMapOptions =
                {
                    center: mapCenter, // map center
                    zoom: 17, //zoom level, 0 = earth view to higher value
                    maxZoom: 40,
                    minZoom: 8,
                    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, "");
                    });
                });
     
                //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>Emplacement :</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="s1">Secteur 1</option>'+
                        '<option value="s2">Secteur 2</option>'+
                        '<option value="s3">Secteur 3</option>'+
                        '<option value="all">Autres</option></select></label>'+
                        '</form>'+
                        '</div></p><button name="save-marker" class="save-marker">Sauvegarder</button>';
     
                    //Drop a new Marker with our Edit Form
                    create_marker(event.latLng, 'Nouveau marqueur', EditForm, true, true, true, "");
                });
     
            }
     
            //############### 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">Supprimer</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("Entrez un nom et une 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 */
                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: "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(false); //set marker to fixed
                    },
                    error:function (xhr, ajaxOptions, thrownError){
                        alert(thrownError);
                    }
                });
            }
     
        });
    Et mon map_process.php :
    Code php : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    <?php
    //PHP 5 +
     
    // database settings 
    $db_username = 'root';
    $db_password = '';
    $db_name = 'xxxxxxx';
    $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!');
        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();

    C'est vraiment SaveMarkers() qui coince.
    Si vous avez des pistes, je suis preneur!

    Cordialement,

    DR

  2. #2
    Modérateur

    Avatar de NoSmoking
    Homme Profil pro
    Inscrit en
    Janvier 2011
    Messages
    17 089
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Isère (Rhône Alpes)

    Informations forums :
    Inscription : Janvier 2011
    Messages : 17 089
    Points : 44 660
    Points
    44 660
    Par défaut
    Bonjour,
    Une erreur "Not Found" m'arrive en Pop-up !
    je ne vois pas de rapport avec le code PHP que tu nous as mis, est ce qu'au moins tu reçois ce que tu envoies ?

  3. #3
    Candidat au Club
    Inscrit en
    Octobre 2009
    Messages
    4
    Détails du profil
    Informations forums :
    Inscription : Octobre 2009
    Messages : 4
    Points : 2
    Points
    2
    Par défaut
    Le rapport avec le code, c'est que dans "SaveMarkers", l'erreur "ThrownError" est un "NotFound". Il ne passe pas dans le Success et je ne comprends pas pour quelles raisons!
    Pourtant, avec un debug de data, je vois ma description et le nom associé au marqueur.

    PS: J'ai pensé à un problème de connexion avec la DB, mais j'utilise WampServer, donc l'utilisateur par défaut est "root" sans mot de passe.

  4. #4
    Modérateur

    Avatar de NoSmoking
    Homme Profil pro
    Inscrit en
    Janvier 2011
    Messages
    17 089
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Isère (Rhône Alpes)

    Informations forums :
    Inscription : Janvier 2011
    Messages : 17 089
    Points : 44 660
    Points
    44 660
    Par défaut
    Le rapport avec le code, c'est que dans "SaveMarkers", l'erreur "ThrownError" est un "NotFound".
    ce qui signifie en clair que la ressource appelée n'a pas été trouvée sur le serveur, fais un affichage de xhr.responseText et observe le message.

Discussions similaires

  1. sauvegarde des données des tables
    Par tomm dans le forum Bases de données
    Réponses: 18
    Dernier message: 27/04/2004, 21h29
  2. [Souris] Sauvegarde des paramètres du driver
    Par Giovanny Temgoua dans le forum x86 16-bits
    Réponses: 7
    Dernier message: 31/01/2004, 19h24
  3. Sauvegarde des attributs de texte en fichier ini
    Par Raylemon dans le forum Langage
    Réponses: 2
    Dernier message: 06/09/2003, 21h28

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo