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 :

Calculer le trajet en km google map


Sujet :

APIs Google

  1. #1
    Membre averti
    Homme Profil pro
    Inscrit en
    Mai 2011
    Messages
    790
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations forums :
    Inscription : Mai 2011
    Messages : 790
    Points : 443
    Points
    443
    Par défaut Calculer le trajet en km google map
    Bonjour,

    Je suis entrain de tester api google map et pour cela j'ai effectuée l'exemple suivant :

    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
    <!DOCTYPE html>
    <html>
      <head>
        <title>Place Autocomplete</title>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta charset="utf-8">
        <style>
          html, body {
            height: 100%;
            margin: 0;
            padding: 0;
          }
          #map {
            height: 100%;
          }
    .controls {
      margin-top: 10px;
      border: 1px solid transparent;
      border-radius: 2px 0 0 2px;
      box-sizing: border-box;
      -moz-box-sizing: border-box;
      height: 32px;
      outline: none;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
    }
     
    #origin-input,
    #destination-input {
      background-color: #fff;
      font-family: Roboto;
      font-size: 15px;
      font-weight: 300;
      margin-left: 12px;
      padding: 0 11px 0 13px;
      text-overflow: ellipsis;
      width: 200px;
    }
     
    #origin-input:focus,
    #destination-input:focus {
      border-color: #4d90fe;
    }
     
    #mode-selector {
      color: #fff;
      background-color: #4d90fe;
      margin-left: 12px;
      padding: 5px 11px 0px 11px;
    }
     
    #mode-selector label {
      font-family: Roboto;
      font-size: 13px;
      font-weight: 300;
    }
     
     
        </style>
      </head>
      <body>
        <input id="origin-input" class="controls" type="text"
            placeholder="Enter an origin location">
     
        <input id="destination-input" class="controls" type="text"
            placeholder="Enter a destination location">
     
        <div id="mode-selector" class="controls" style="display: none">
          <input type="radio" name="type" id="changemode-walking" checked="checked" >
          <label for="changemode-walking">Walking</label>
     
          <input type="radio" name="type" id="changemode-transit">
          <label for="changemode-transit">Transit</label>
     
          <input type="radio" name="type" id="changemode-driving">
          <label for="changemode-driving">Driving</label>
        </div>
     
        <div id="map"></div>
     
        <script>
     
     
     
     
    function initMap() {
      var origin_place_id = null;
      var destination_place_id = null;
      var travel_mode = google.maps.TravelMode.WALKING;
      var map = new google.maps.Map(document.getElementById('map'), {
        mapTypeControl: false,
        center: {lat: 48.8737793, lng: 2.2950156},
        zoom: 13
      });
     
     
      var directionsService = new google.maps.DirectionsService;
      var directionsDisplay = new google.maps.DirectionsRenderer;
      directionsDisplay.setMap(map);
     
      var origin_input = document.getElementById('origin-input');
      var destination_input = document.getElementById('destination-input');
     
     
     
      var modes = document.getElementById('mode-selector');
     
      map.controls[google.maps.ControlPosition.TOP_LEFT].push(origin_input);
      map.controls[google.maps.ControlPosition.TOP_LEFT].push(destination_input);
      map.controls[google.maps.ControlPosition.TOP_LEFT].push(modes);
     
      var origin_autocomplete = new google.maps.places.Autocomplete(origin_input);
      origin_autocomplete.bindTo('bounds', map);
      var destination_autocomplete =
          new google.maps.places.Autocomplete(destination_input);
      destination_autocomplete.bindTo('bounds', map);
     
      // Sets a listener on a radio button to change the filter type on Places
      // Autocomplete.
      function setupClickListener(id, mode) {
        var radioButton = document.getElementById(id);
        radioButton.addEventListener('click', function() {
          travel_mode = mode;
        });
      }
      setupClickListener('changemode-walking', google.maps.TravelMode.WALKING);
      setupClickListener('changemode-transit', google.maps.TravelMode.TRANSIT);
      setupClickListener('changemode-driving', google.maps.TravelMode.DRIVING);
     
      function expandViewportToFitPlace(map, place) {
        if (place.geometry.viewport) {
          map.fitBounds(place.geometry.viewport);
        } else {
          map.setCenter(place.geometry.location);
          map.setZoom(17);
        }
      }
     
      origin_autocomplete.addListener('place_changed', function() {
        var place = origin_autocomplete.getPlace();
        if (!place.geometry) {
          window.alert("Autocomplete's returned place contains no geometry");
          return;
        }
        expandViewportToFitPlace(map, place);
     
        // If the place has a geometry, store its place ID and route if we have
        // the other place ID
        origin_place_id = place.place_id;
        route(origin_place_id, destination_place_id, travel_mode,
              directionsService, directionsDisplay);
      });
     
      destination_autocomplete.addListener('place_changed', function() {
        var place = destination_autocomplete.getPlace();
     
        if (!place.geometry) {
          window.alert("Autocomplete's returned place contains no geometry");
          return;
        }
        expandViewportToFitPlace(map, place);
     
        // If the place has a geometry, store its place ID and route if we have
        // the other place ID
        destination_place_id = place.place_id;
        route(origin_place_id, destination_place_id, travel_mode,
              directionsService, directionsDisplay);
      });
     
      function route(origin_place_id, destination_place_id, travel_mode,
                     directionsService, directionsDisplay) {
        if (!origin_place_id || !destination_place_id) {
          return;
        }
        directionsService.route({
          origin: {'placeId': origin_place_id},
          destination: {'placeId': destination_place_id},
          travelMode: travel_mode
        }, function(response, status) {
          if (status === google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
          } else {
            window.alert('Directions request failed due to ' + status);
          }
        });
      }
     
     
     
    }
     
     
        </script>
        <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCos12fMCZ3i2Uk3Wp-hYx7vmQSHuc1ueA&signed_in=true&libraries=places&callback=initMap"
            async defer></script>
      </body>
    </html>

    Cette exemple m'affiche le trajet entre deux villes mais ce que je souhaite ajouter le nombre de km entre ces deux villes.

    Est-ce-que vous pouvez m'aider s'il vous plait à modifier la page ?

    Merci.

  2. #2
    Invité
    Invité(e)
    Par défaut
    J'avoue je n'ai pas regardé en détail mais tu trouveras une réponse ici

    https://developers.google.com/maps/d...istance-matrix


    Je crois

  3. #3
    Membre averti
    Homme Profil pro
    Inscrit en
    Mai 2011
    Messages
    790
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations forums :
    Inscription : Mai 2011
    Messages : 790
    Points : 443
    Points
    443
    Par défaut
    J'ai essayé le code suivant :

    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
    function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
      var R = 6371; // Radius of the earth in km
      var dLat = deg2rad(lat2-lat1);  // deg2rad below
      var dLon = deg2rad(lon2-lon1); 
      var a = 
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
        Math.sin(dLon/2) * Math.sin(dLon/2)
        ; 
      var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
      var d = R * c; // Distance in km
      return d;
    }
     
    function deg2rad(deg) {
      return deg * (Math.PI/180)
    }
    En exécutant le code entre paris 11 et paris 16 il m'affiche un 3126.83 ce qui me parait faux non ??

  4. #4
    Invité
    Invité(e)
    Par défaut
    Tu peux mettre le code complet pour que je regarde ou quelqu'un d'autre aussi

    Il exprime pas la distance en mètres ? Je connais pas paris

  5. #5
    Membre averti
    Homme Profil pro
    Inscrit en
    Mai 2011
    Messages
    790
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations forums :
    Inscription : Mai 2011
    Messages : 790
    Points : 443
    Points
    443
    Par défaut
    Oui bien sur.

    Mon code complet est le suivant :

    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
    <!DOCTYPE html>
    <html>
      <head>
        <title>Place Autocomplete</title>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta charset="utf-8">
        <style>
          html, body {
            height: 100%;
            margin: 0;
            padding: 0;
          }
          #map {
            height: 100%;
          }
    .controls {
      margin-top: 10px;
      border: 1px solid transparent;
      border-radius: 2px 0 0 2px;
      box-sizing: border-box;
      -moz-box-sizing: border-box;
      height: 32px;
      outline: none;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
    }
     
    #origin-input,
    #destination-input {
      background-color: #fff;
      font-family: Roboto;
      font-size: 15px;
      font-weight: 300;
      margin-left: 12px;
      padding: 0 11px 0 13px;
      text-overflow: ellipsis;
      width: 200px;
    }
     
    #origin-input:focus,
    #destination-input:focus {
      border-color: #4d90fe;
    }
     
    #mode-selector {
      color: #fff;
      background-color: #4d90fe;
      margin-left: 12px;
      padding: 5px 11px 0px 11px;
    }
     
    #mode-selector label {
      font-family: Roboto;
      font-size: 13px;
      font-weight: 300;
    }
     
     
        </style>
      </head>
      <body>
        <input id="origin-input" class="controls" type="text"
            placeholder="Enter an origin location" onblur="GetLocation()">
     
        <input id="destination-input" class="controls" type="text"
            placeholder="Enter a destination location" onblur="GetLocationdestination()">
     
     
        <div id="mode-selector" class="controls" style="display: none">
          <input type="radio" name="type" id="changemode-walking" checked="checked" >
          <label for="changemode-walking">Walking</label>
     
          <input type="radio" name="type" id="changemode-transit">
          <label for="changemode-transit">Transit</label>
     
          <input type="radio" name="type" id="changemode-driving">
          <label for="changemode-driving">Driving</label>
        </div>
     
        <div id="map"></div>
     
     
     
        <script>
     
     
     
     
    function initMap() {
      var origin_place_id = null;
      var destination_place_id = null;
      var travel_mode = google.maps.TravelMode.WALKING;
      var map = new google.maps.Map(document.getElementById('map'), {
        mapTypeControl: false,
        center: {lat: 48.8737793, lng: 2.2950156},
        zoom: 13
      });
     
     
      var directionsService = new google.maps.DirectionsService;
      var directionsDisplay = new google.maps.DirectionsRenderer;
      directionsDisplay.setMap(map);
     
      var origin_input = document.getElementById('origin-input');
      var destination_input = document.getElementById('destination-input');
     
     
     
      var modes = document.getElementById('mode-selector');
     
      map.controls[google.maps.ControlPosition.TOP_LEFT].push(origin_input);
      map.controls[google.maps.ControlPosition.TOP_LEFT].push(destination_input);
      map.controls[google.maps.ControlPosition.TOP_LEFT].push(modes);
     
      var origin_autocomplete = new google.maps.places.Autocomplete(origin_input);
      origin_autocomplete.bindTo('bounds', map);
      var destination_autocomplete =
          new google.maps.places.Autocomplete(destination_input);
      destination_autocomplete.bindTo('bounds', map);
     
      // Sets a listener on a radio button to change the filter type on Places
      // Autocomplete.
      function setupClickListener(id, mode) {
        var radioButton = document.getElementById(id);
        radioButton.addEventListener('click', function() {
          travel_mode = mode;
        });
      }
      setupClickListener('changemode-walking', google.maps.TravelMode.WALKING);
      setupClickListener('changemode-transit', google.maps.TravelMode.TRANSIT);
      setupClickListener('changemode-driving', google.maps.TravelMode.DRIVING);
     
      function expandViewportToFitPlace(map, place) {
        if (place.geometry.viewport) {
          map.fitBounds(place.geometry.viewport);
        } else {
          map.setCenter(place.geometry.location);
          map.setZoom(17);
        }
      }
     
      origin_autocomplete.addListener('place_changed', function() {
        var place = origin_autocomplete.getPlace();
     
     
     
        if (!place.geometry) {
          window.alert("Autocomplete's returned place contains no geometry");
          return;
        }
        expandViewportToFitPlace(map, place);
     
        // If the place has a geometry, store its place ID and route if we have
        // the other place ID
        origin_place_id = place.place_id;
        route(origin_place_id, destination_place_id, travel_mode,
              directionsService, directionsDisplay);
      });
     
      destination_autocomplete.addListener('place_changed', function() {
        var place = destination_autocomplete.getPlace();
     
        if (!place.geometry) {
          window.alert("Autocomplete's returned place contains no geometry");
          return;
        }
        expandViewportToFitPlace(map, place);
     
        // If the place has a geometry, store its place ID and route if we have
        // the other place ID
        destination_place_id = place.place_id;
        route(origin_place_id, destination_place_id, travel_mode,
              directionsService, directionsDisplay);
      });
     
      function route(origin_place_id, destination_place_id, travel_mode,
                     directionsService, directionsDisplay) {
        if (!origin_place_id || !destination_place_id) {
     
          return;
        }
        directionsService.route({
          origin: {'placeId': origin_place_id},
          destination: {'placeId': destination_place_id},
          travelMode: travel_mode
        }, function(response, status) {
          if (status === google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
          } else {
            window.alert('Directions request failed due to ' + status);
          }
        });
      }
     
     
     
    }
     
     
     
     
    function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
      var R = 6371; // Radius of the earth in km
      var dLat = deg2rad(lat2-lat1);  // deg2rad below
      var dLon = deg2rad(lon2-lon1); 
      var a = 
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
        Math.sin(dLon/2) * Math.sin(dLon/2)
        ; 
      var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
      var d = R * c; // Distance in km
      return d;
    }
     
    function deg2rad(deg) {
      return deg * (Math.PI/180)
    }
     
     
    var latitudeorigin;
    var longitudeorigin;
     
    var latitudedestination;
    var longitudedestination;
     
     function GetLocation() {
                var geocoder = new google.maps.Geocoder();
                var address = document.getElementById("origin-input").value;
                geocoder.geocode({ 'address': address }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                         latitude = results[0].geometry.location.lat();
                         longitude = results[0].geometry.location.lng();
     
    					 latitudeorigin = latitude;
    					 longitudeorigin = longitude;
     
                    } else {
                        alert("Request failed.")
                    }
                });
            };
     
     
     
    function GetLocationdestination() {
                var geocoder = new google.maps.Geocoder();
                var address = document.getElementById("destination-input").value;
                geocoder.geocode({ 'address': address }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                         latitudedest = results[0].geometry.location.lat();
                         longitudest = results[0].geometry.location.lng();
     
    					 latitudedestination = latitudedest;
    					 longitudedestination = longitudest;
     
                       var point1 = new google.maps.LatLng(latitudeorigin, longitudeorigin);     
    				   var point2 = new google.maps.LatLng(latitudedestination, longitudedestination); 
    				   var distanceKm = google.maps.geometry.spherical.computeDistanceBetween(point1, point2);
    				   distanceKm = distanceKm/1000;
     
    				   var dd = getDistanceFromLatLonInKm(latitudeorigin,longitudeorigin,latitudedestination,longitudedestination);
    				   window.alert(dd);
    				 //window.alert(latitudeorigin + "----" + longitudeorigin + "//" + latitudedestination + "-----" + longitudedestination);
                    } else {
                        alert("Request failed.")
                    }
                });
     
     
            };
     
        </script>
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
      </body>
    </html>
    Merci

  6. #6
    Modérateur

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

    Informations forums :
    Inscription : Janvier 2011
    Messages : 17 120
    Points : 44 917
    Points
    44 917
    Par défaut
    Bonjour,
    as tu eu la curiosité de regarder la réponse que tu obtenais, par exemple
    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
    function route(origin_place_id, destination_place_id, travel_mode,
        directionsService, directionsDisplay) {
        if (!origin_place_id || !destination_place_id) {
            return;
        }
        directionsService.route({
            origin: {
                'placeId': origin_place_id
            },
            destination: {
                'placeId': destination_place_id
            },
            travelMode: travel_mode
        }, function(response, status) {
            if (status === google.maps.DirectionsStatus.OK) {
                // -------------------------------------
                // mais qu'y a t-il dans la reponse !?!
                // -------------------------------------
                console.log(response.routes[0].legs[0]);
     
                directionsDisplay.setDirections(response);
            } else {
                window.alert('Directions request failed due to ' + status);
            }
        });
    }

Discussions similaires

  1. Application Trajet à multiples marker Google Maps
    Par Vice555 dans le forum API standards et tierces
    Réponses: 0
    Dernier message: 11/04/2015, 01h33
  2. Calcul de distance avec Google Map
    Par jouclar dans le forum Réseau/Web
    Réponses: 6
    Dernier message: 22/04/2010, 15h58
  3. Calcul itineraire google maps Api
    Par crovette51101 dans le forum Général JavaScript
    Réponses: 2
    Dernier message: 12/03/2009, 20h24
  4. Calculer une duree de trajet Google Map
    Par numerodix dans le forum Général JavaScript
    Réponses: 15
    Dernier message: 28/10/2008, 16h20
  5. Calcul de coordonnées sur Google Map
    Par queen_pitbull dans le forum Général JavaScript
    Réponses: 2
    Dernier message: 29/08/2008, 11h05

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