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 :

gestions des erreurs


Sujet :

APIs Google

  1. #1
    Membre à l'essai
    Homme Profil pro
    Inscrit en
    Octobre 2006
    Messages
    22
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Octobre 2006
    Messages : 22
    Points : 12
    Points
    12
    Par défaut gestions des erreurs
    Bonjour

    Comment peut on contrôler une erreur du type "plusieurs adresses retournée" quand on interroge google Maps avec "GClientGeocoder();"
    J'ai bien une fenêtre d'erreur quand l'adresse n'existe pas, mais pour controller si plusieurs adresse sont retournées je n'ai pas de message et la carte ne s'affiche pas !

    si quelqu'un avait une solution ça m'arrangerai bien, ces la dernière étape

  2. #2
    Invité
    Invité(e)
    Par défaut
    Bonjour,

    Ce n'est pas une erreur, seulement les données fournies ne sont pas assez précises. A priori, le max d'adresses retrounées serait de 10. La précision des données retournées allant de 0 à 9.
    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
    ....
    geocoder = new GClientGeocoder();
    .
    .
    .
    geocoder.getLocations(search, function (result)
          {
          .
          .
          .
          // donne le nb d'adresses possibles Placemark est un array
          nb_resultat = result.Placemark.length;
          .
          .
          .
          }
    )
    ...
    Un exemple de recherche
    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
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml"  xmlns:v="urn:schemas-microsoft-com:vml">
      <head>
        <meta http-equiv="content-type" content="text/html; charset=ISO-8859-2"/>
        <title>Google Maps JavaScript API Example</title>
    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAPDUET0Qt7p2VcSk6JNU1sBRRwPhutbWBmyj82Go_H6JlE7EvFBSKFFFHFePAwvib9UM0geoA3Pgafw" type="text/javascript"></script>
     
    	<style type="text/css">
      #map {width: 600px; height: 600px; border: 1px black solid;}
      </style>
     
    	<script  type="text/javascript">
      var map;
      var gdir;
      var geocoder;
      var resultText = "";
      var extractresul = {"pays": "",
                          "region": "",
                          "departement": "",
                          "ville": "",
                          "codepostal": "",
                          "voie": "",
                          "lieu dit": "",
                          "precision": ""};
     
      function initialize() {
        if (GBrowserIsCompatible()) {
          map = new GMap2(document.getElementById("map")); // Ajout de la carte dans l'element id="map"
          map.addControl(new GLargeMapControl()); // Ajout control deplacement de la carte et zoom
          map.addControl(new GMapTypeControl()); // Ajout control type de vue
          map.setCenter(new GLatLng(46.227638, 2.213749),6); // Centrage de la carte (lat, lng et zoom)
          geocoder = new GClientGeocoder(); // Creation d'une instance du client Geocoder
          gdir = new GDirections(map);
          GEvent.addListener(gdir, "load", onGDirectionsLoad);
          GEvent.addListener(gdir, "error", handleErrors);
     
          // Tableau des erreurs ertournees
          var reasons=[];
          reasons[G_GEO_SUCCESS]            = "Success";
          reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
          reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
          reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
          reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
          reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
          reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
        }
        else {
          alert("Sorry, the Google Maps API is not compatible with this browser");
        }
      }
     
      // fonction de recherche du lieu
      function go_lieu() {
        var search = document.getElementById("lieu").value;
        // ====== Perform the Geocoding ======
        geocoder.getLocations(search, function (result)
          {
            if (result.Status.code == G_GEO_SUCCESS) {
              for ( v in extractresul) extractresul[v] = "";
              // Nb de résultats trouvés
              document.getElementById("message").innerHTML = "<b>" + result.Placemark.length +"</b> résultats<br />";
              // Loop through the results, placing markers
              var resultText ="";
              var adrdetail;
              var details;
              var y = 0;
              for (var i=0; i<result.Placemark.length; i++) {
                resultText = "";
                var p = result.Placemark[i].Point.coordinates;
                resultText = JSON.stringify(result.Placemark[i].AddressDetails, extractAdress, ' ');
                var adrHTML = '\n';
                for (adr in extractresul) {
                    adrHTML += (extractresul[adr] != "") ? (adr + ' : ' + extractresul[adr] + '\n') : "";
                }
                var marker = createMarker(new GLatLng(p[1],p[0]), result.Placemark[i].address); // Création du marqueur
                document.getElementById("message").innerHTML += '<br>'+(i+1)+': '+ result.Placemark[i].address + marker.getPoint()+'<div style="background-color: palegreen; width: auto;"><pre>'+adrHTML+'</pre></div>';
                map.addOverlay(marker); // Affichage du marqueur sur la carte
              }
              // centre the map on the first result
              var p = result.Placemark[0].Point.coordinates;
              map.setCenter(new GLatLng(p[1],p[0]),6);
            }
            // ====== Decode the error status ======
            else {
              var reason="Code "+result.Status.code;
              if (reasons[result.Status.code]) {
                reason = reasons[result.Status.code]
              }
              alert('Could not find "'+search+ '" ' + reason);
            }
          }
        )
      }
     
      // Creation du marqueur deplacable avec une bulle info
      function createMarker(point,html) {
        var marker = new GMarker(point, {draggable: true});
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml(html);
        });
        return marker;
      }
     
      // fonction pour JSON
      function extractAdress(k, v) {
          switch (k) {
            case "CountryNameCode": // code pays
              extractresul["pays"] = v;
              break;
            case "AdministrativeAreaName": // région
              extractresul["region"] = v;
              break;
            case "SubAdministrativeAreaName": // Département
              extractresul["departement"] = v;
              break;
            case "LocalityName": // ville
              extractresul["ville"] = v;
              break;
            case "PostalCodeNumber": // code postal
              extractresul["codepostal"] = v;
              break;
            case "ThoroughfareName": // nom de la voie avec n° si présent
              extractresul["voie"] = v;
              break;
            case "DependentLocalityName": // lieu dit
              extractresul["lieu dit"] = v;
              break;
            case "Accuracy": // lieu dit
              extractresul["precision"] = v;
              break;
          }
          return v;
      }
     
     
      function onGDirectionsLoad() {};
     
      function handleErrors() {};
     
     
    // manipulation JSON ===========================================================
    if (!this.JSON) {
        JSON = function () {
            function f(n) {
                return n < 10 ? '0' + n : n;
            }
            Date.prototype.toJSON = function (key) {
                return this.getUTCFullYear()   + '-' +
                     f(this.getUTCMonth() + 1) + '-' +
                     f(this.getUTCDate())      + 'T' +
                     f(this.getUTCHours())     + ':' +
                     f(this.getUTCMinutes())   + ':' +
                     f(this.getUTCSeconds())   + 'Z';
            };
            String.prototype.toJSON =
            Number.prototype.toJSON =
            Boolean.prototype.toJSON = function (key) {
                return this.valueOf();
            };
            var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
                escapeable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
                gap,
                indent,
                meta = {    // table of character substitutions
                    '\b': '\\b',
                    '\t': '\\t',
                    '\n': '\\n',
                    '\f': '\\f',
                    '\r': '\\r',
                    '"' : '\\"',
                    '\\': '\\\\'
                },
                rep;
            function quote(string) {
                escapeable.lastIndex = 0;
                return escapeable.test(string) ?
                    '"' + string.replace(escapeable, function (a) {
                        var c = meta[a];
                        if (typeof c === 'string') {
                            return c;
                        }
                        return '\\u' + ('0000' +
                                (+(a.charCodeAt(0))).toString(16)).slice(-4);
                    }) + '"' :
                    '"' + string + '"';
            }
            function str(key, holder) {
                var i,          // The loop counter.
                    k,          // The member key.
                    v,          // The member value.
                    length,
                    mind = gap,
                    partial,
                    value = holder[key];
                if (value && typeof value === 'object' &&
                        typeof value.toJSON === 'function') {
                    value = value.toJSON(key);
                }
                if (typeof rep === 'function') {
                    value = rep.call(holder, key, value);
                }
                switch (typeof value) {
                case 'string':
                    return quote(value);
     
                case 'number':
                    return isFinite(value) ? String(value) : 'null';
                case 'boolean':
                case 'null':
                    return String(value);
                case 'object':
                    if (!value) {
                        return 'null';
                    }
                    gap += indent;
                    partial = [];
                    if (typeof value.length === 'number' &&
                            !(value.propertyIsEnumerable('length'))) {
                        length = value.length;
                        for (i = 0; i < length; i += 1) {
                            partial[i] = str(i, value) || 'null';
                        }
                        v = partial.length === 0 ? '[]' :
                            gap ? '[\n' + gap +
                                    partial.join(',\n' + gap) + '\n' +
                                        mind + ']' :
                                  '[' + partial.join(',') + ']';
                        gap = mind;
                        return v;
                    }
                    if (rep && typeof rep === 'object') {
                        length = rep.length;
                        for (i = 0; i < length; i += 1) {
                            k = rep[i];
                            if (typeof k === 'string') {
                                v = str(k, value);
                                if (v) {
                                    partial.push(quote(k) + (gap ? ': ' : ':') + v);
                                }
                            }
                        }
                    } else {
                        for (k in value) {
                            if (Object.hasOwnProperty.call(value, k)) {
                                v = str(k, value);
                                if (v) {
                                    partial.push(quote(k) + (gap ? ': ' : ':') + v);
                                }
                            }
                        }
                    }
                    v = partial.length === 0 ? '{}' :
                        gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                                mind + '}' : '{' + partial.join(',') + '}';
                    gap = mind;
                    return v;
                }
            }
            return {
                stringify: function (value, replacer, space) {
                    var i;
                    gap = '';
                    indent = '';
                    if (typeof space === 'number') {
                        for (i = 0; i < space; i += 1) {
                            indent += ' ';
                        }
                    } else if (typeof space === 'string') {
                        indent = space;
                    }
                    rep = replacer;
                    if (replacer && typeof replacer !== 'function' &&
                            (typeof replacer !== 'object' ||
                             typeof replacer.length !== 'number')) {
                        throw new Error('JSON.stringify');
                    }
                    return str('', {'': value});
                },
                parse: function (text, reviver) {
                    var j;
                    function walk(holder, key) {
                        var k, v, value = holder[key];
                        if (value && typeof value === 'object') {
                            for (k in value) {
                                if (Object.hasOwnProperty.call(value, k)) {
                                    v = walk(value, k);
                                    if (v !== undefined) {
                                        value[k] = v;
                                    } else {
                                        delete value[k];
                                    }
                                }
                            }
                        }
                        return reviver.call(holder, key, value);
                    }
                    cx.lastIndex = 0;
                    if (cx.test(text)) {
                        text = text.replace(cx, function (a) {
                            return '\\u' + ('0000' +
                                    (+(a.charCodeAt(0))).toString(16)).slice(-4);
                        });
                    }
                    if (/^[\],:{}\s]*$/.
    test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
    replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
    replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
                        j = eval('(' + text + ')');
                        return typeof reviver === 'function' ?
                            walk({'': j}, '') : j;
                    }
                    throw new SyntaxError('JSON.parse');
                }
            };
        }();
    }
    // FIN manipulation JSON =======================================================
     </script>
    </head>
    <body onload="initialize()" onunload="GUnload()">
    <div id="map"></div>
    <form onsubmit="go_lieu(); return false">
          <input id="lieu" size="60" type="text" value="prades">
          <input type="submit" value="Go!">
          <input type="button" onclick="javascript:map.clearOverlays();return false" value="Clear markers">
    </form>
     
    <div id="message"></div>
    </body>
    </html>
    Le code semble long, mais il y a la fonction JSON bien utile !!

    A+

  3. #3
    Membre à l'essai
    Homme Profil pro
    Inscrit en
    Octobre 2006
    Messages
    22
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Octobre 2006
    Messages : 22
    Points : 12
    Points
    12
    Par défaut
    est ce que je peut ne mettre que cette partie

    var reasons=[];
    reasons[G_GEO_SUCCESS] = "Success";
    reasons[G_GEO_MISSING_ADDRESS] = "Missing Address: The address was either missing or had no value.";
    reasons[G_GEO_UNKNOWN_ADDRESS] = "Unknown Address: No corresponding geographic location could be found for the specified address.";
    reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address: The geocode for the given address cannot be returned due to legal or contractual reasons.";
    reasons[G_GEO_BAD_KEY] = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
    reasons[G_GEO_TOO_MANY_QUERIES] = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
    reasons[G_GEO_SERVER_ERROR] = "Server error: The geocoding request could not be successfully processed.";

    avec la fontion précédament citée

  4. #4
    Membre à l'essai
    Homme Profil pro
    Inscrit en
    Octobre 2006
    Messages
    22
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Octobre 2006
    Messages : 22
    Points : 12
    Points
    12
    Par défaut
    ce que je veux c'est la gestion des erreurs, dailleur merci pour ton code ça me donne une piste mais je ne pense pas être encore au top pour gérer une partie JSON c'est dans les projets.
    Est ce qu'il est possible de gérer cette partie qui retourne des erreurs sans JSON

Discussions similaires

  1. [FB] Gestion des erreurs et application francophone
    Par Benjamin GAGNEUX dans le forum Installation
    Réponses: 10
    Dernier message: 20/05/2006, 14h54
  2. [struts][Datasource]Gestion des erreurs
    Par GreenJay dans le forum Struts 1
    Réponses: 8
    Dernier message: 15/09/2004, 16h51
  3. [VB6] Gestion des erreurs dans une dll
    Par zimba-tm dans le forum VB 6 et antérieur
    Réponses: 8
    Dernier message: 02/08/2004, 11h20
  4. [XSLT]Est ce qu'il y'a la gestion des erreur en xslt ?
    Par miloud dans le forum XSL/XSLT/XPATH
    Réponses: 2
    Dernier message: 04/02/2004, 17h19
  5. [LG]gestion des erreurs
    Par frontin dans le forum Langage
    Réponses: 3
    Dernier message: 29/11/2003, 22h41

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