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

Contribuez Discussion :

[Google Maps]Distance entre 2 points ou point dans un rayon


Sujet :

Contribuez

  1. #1
    Modérateur

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

    Informations forums :
    Inscription : Janvier 2011
    Messages : 16 959
    Points : 44 122
    Points
    44 122
    Par défaut [Google Maps]Distance entre 2 points ou point dans un rayon

    Question
    Comment calculer la distance entre deux points dans un environnement Google Maps?

    Réponse
    Pour calculer la distance entre deux points, on utilise simplement la méthode computeDistanceBetween mise à disposition par la librairie geometry, qu'il ne faut oublier de charger.

    Le code javascript
    Code javascript : 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
    (function(){
      var oRedIcone, oGreenIcone, oShadow;
      function drawMarker( marker, origine, rayon){
        // calcul distance
        var distance = google.maps.geometry.spherical.computeDistanceBetween( origine, marker.getPosition());
        // ici on joue sur la couleur du marker
        var icone = (distance > rayon) ? oRedIcone : oGreenIcone;
        // affectation icone qui va bien
        marker.setOptions({'icon' : icone});
        // ajoute l'ombre
        marker.setOptions({'shadow': oShadow});
        // ajout distance au survol
        var km = (distance/1000).toFixed(3) +' km';
        marker.setOptions({'title' : km});
      }
      function initCarte(){
        // création de l'ombre
        oShadow = new google.maps.MarkerImage(
          'http://maps.google.com/mapfiles/shadow50.png',
          new google.maps.Size( 37, 34),
          new google.maps.Point( 0, 0),
          new google.maps.Point( 10, 34)
        );
        // création de l'icone hors limite
        oRedIcone = new google.maps.MarkerImage(
          'http://maps.google.com/mapfiles/marker.png',
          new google.maps.Size( 20, 34),
          new google.maps.Point( 0, 0),
          new google.maps.Point( 10, 34)
        );
        // création de l'icone dans limite
        oGreenIcone = new google.maps.MarkerImage(
          'http://maps.google.com/mapfiles/marker_green.png',
          new google.maps.Size( 20, 34),
          new google.maps.Point( 0, 0),
          new google.maps.Point( 10, 34)
        );
     
        var tabMarkers = [];
        var centre = new google.maps.LatLng( 46.80, 1.75);
        // création de la carte
        var oMap = new google.maps.Map(document.getElementById('div_carte'),{
            'backgroundColor': '#FFF',
            'zoom': 15,
            'center': centre,
            'disableDoubleClickZoom':true,
            'panControl':false,
            'mapTypeControl':  false,
            'streetViewControl': false,
            'zoomControlOptions': {
                'style': google.maps.ZoomControlStyle.SMALL
              },
            'mapTypeId': google.maps.MapTypeId.ROADMAP
          });
        // création du cercle pour les limites
        var oCercle = new google.maps.Circle({
            'center': centre,
            'map': oMap,
            'radius': 500,
            'fillColor': '#FFF',
            'fillOpacity': .5,
            'strokeWeight':1,
            'strokeColor': '#888',
            'clickable':false,
            'editable':true,
            'strokeOpacity': 1.0
          });
        // evenement sur changement de la position du centre du cercle
        google.maps.event.addListener( oCercle, 'center_changed', function(){
            // redraw des markers
            var origine = this.getCenter(),
                rayon   = this.getRadius(),
                i, nb   = tabMarkers.length;
            for( i=0; i < nb; i++){
              drawMarker( tabMarkers[i], origine, rayon);
            }
          });
        // evenement sur changement du rayon du cercle
        google.maps.event.addListener( oCercle, 'radius_changed', function(){
            // redraw des markers
            var origine = this.getCenter(),
                rayon   = this.getRadius(),
                i, nb   = tabMarkers.length;
            for( i=0; i < nb; i++){
              drawMarker( tabMarkers[i], origine, rayon);
            }
          });
        // evenement double click pour création des markers
        google.maps.event.addListener( oMap, 'dblclick', function(data) {
            // création d'un marqueur
            var oMarker = new google.maps.Marker({
                'position' : data.latLng,
                'map' : this
              });
            // test affichage
            var origine = oCercle.getCenter(),
                rayon   = oCercle.getRadius();
            // redraw le marker
            drawMarker( oMarker, origine, rayon);
            // empile le marker
            tabMarkers.push( oMarker);
          });
      }
      // init lorsque la page est chargee
      google.maps.event.addDomListener(window, 'load', initCarte);
    })();
    Explication
    On passe à la fonction la LatLng du centre du cercle et la LatLng du marker, si la distance est supérieure au rayon du cercle on affecte au marker une icône rouge sinon on lui affecte une icône verte.

    En cas de modification de la position du cercle ou de son diamètre, on recalcule les distances par rapport à ce "nouveau" cercle.

    Dans cet exemple l'utilisation du cercle ne sert qu'à visualiser le résultat en déterminant un point, son centre, et une distance, son rayon.

    On pourrait également décider de rendre, ou non, visible le marker suivant sa distance au centre.

    Le résultat

    Le code complet
    faites un copier /coller et profitez
    Code html : 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
    <!DOCTYPE html>
    <html lang="fr">
    <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
    <meta charset="UTF-8"/>
    <title>[GoogleMaps API V3]Distance, point dans un rayon de...</title>
    <style type="text/css">
    html, body{
      height:100%;
      margin:0px;
      padding:0px;
      font-family:"Trebuchet MS",Verdana,sans-serif;
      font-size:1.0em;
      background:#E8E8EA;
    }
    #page{
      position:relative;
      width:52em;
      min-height:100%;
      margin:0 auto;
      background: #FFF;
      padding-bottom:40px;
      border-left: 1px solid #C0C0C0;
      border-right: 1px solid #C0C0C0;
      box-shadow: 0 0 10px 2px #C0C0C0;
      overflow:hidden;
    }
    #page h2{
      color: #4488BB;
      font-size:1.25em;
      margin:0.5em;
      margin-left:-1em;
    }
    #header{
      position:relative;
      font-size:0.9em;
      margin:2px;
      background-color:#E1E4F2;
      border:1px solid #B0B0FF;
    }
    #header h1{
      color:#006699;
      font-size:1.5em;
      font-style:normal;
      line-height:2.0em;
      padding:0.25em 0.5em 0;
      margin:0;
      text-shadow:1px 1px 0px #FFF;
      color:#4488BB;
    }
    #header span {
      float: right;
      font-size: 0.6em;
      font-style: italic;
      line-height: 1em;
      position: absolute;
      right: 0.5em;
      top: 0.5em;
    }
    .section{
      width:46em;
      margin:0 auto;
    }
    p{
      text-align:justify;
      margin:0.5em 0;
    }
    p img{
      height:17px;
      vertical-align:middle;
      margin:0 0.5em;
    }
    #div_carte{
      height:40em;
      width:42em;
      margin:0 auto;
      border:5px solid #FFF;
      box-shadow: 0 2px 4px 2px #CCC;
    }
    code{
      font-family:"Courier New";
      font-size:1em;
      color:#080;
    }
    #footer{
      font-family:Verdana,sans-serif;
      position:absolute;
      bottom:0;
      left:0;
      width:100%;
      margin:0;
      padding:0.5em;
      background-color:#F2F2F2;
      border-top:1px solid #B0B0FF;
      overflow:hidden;
    }
    #footer p{
      margin:0;
      padding:0;
      font-size:0.7em;
      line-height:1em;
    }
    #footer a{
      color:#00F;
      text-decoration:none;
    }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,drawing"></script>
    <script type="text/javascript">
    (function(){
      var oRedIcone, oGreenIcone, oShadow;
      function drawMarker( marker, origine, rayon){
        // calcul distance
        var distance = google.maps.geometry.spherical.computeDistanceBetween( origine, marker.getPosition());
        // ici on joue sur la couleur du marker
        var icone = (distance > rayon) ? oRedIcone : oGreenIcone;
        // affectation icone qui va bien
        marker.setOptions({'icon' : icone});
        // ajoute l'ombre
        marker.setOptions({'shadow': oShadow});
        // ajout distance au survol
        var km = (distance/1000).toFixed(3) +' km';
        marker.setOptions({'title' : km});
      }
      function initCarte(){
        // création de l'ombre
        oShadow = new google.maps.MarkerImage(
          'http://maps.google.com/mapfiles/shadow50.png',
          new google.maps.Size( 37, 34),
          new google.maps.Point( 0, 0),
          new google.maps.Point( 10, 34)
        );
        // création de l'icone hors limite
        oRedIcone = new google.maps.MarkerImage(
          'http://maps.google.com/mapfiles/marker.png',
          new google.maps.Size( 20, 34),
          new google.maps.Point( 0, 0),
          new google.maps.Point( 10, 34)
        );
        // création de l'icone dans limite
        oGreenIcone = new google.maps.MarkerImage(
          'http://maps.google.com/mapfiles/marker_green.png',
          new google.maps.Size( 20, 34),
          new google.maps.Point( 0, 0),
          new google.maps.Point( 10, 34)
        );
     
        var tabMarkers = [];
        var centre = new google.maps.LatLng( 46.80, 1.75);
        // création de la carte
        var oMap = new google.maps.Map(document.getElementById('div_carte'),{
            'backgroundColor': '#FFF',
            'zoom': 15,
            'center': centre,
            'disableDoubleClickZoom':true,
            'panControl':false,
            'mapTypeControl':  false,
            'streetViewControl': false,
            'zoomControlOptions': {
                'style': google.maps.ZoomControlStyle.SMALL
              },
            'mapTypeId': google.maps.MapTypeId.ROADMAP
          });
        // création du cercle pour les limites
        var oCercle = new google.maps.Circle({
            'center': centre,
            'map': oMap,
            'radius': 500,
            'fillColor': '#FFF',
            'fillOpacity': .5,
            'strokeWeight':1,
            'strokeColor': '#888',
            'clickable':false,
            'editable':true,
            'strokeOpacity': 1.0
          });
        // evenement sur changement de la position du centre du cercle
        google.maps.event.addListener( oCercle, 'center_changed', function(){
            // redraw des markers
            var origine = this.getCenter(),
                rayon   = this.getRadius(),
                i, nb   = tabMarkers.length;
            for( i=0; i < nb; i++){
              drawMarker( tabMarkers[i], origine, rayon);
            }
          });
        // evenement sur changement du rayon du cercle
        google.maps.event.addListener( oCercle, 'radius_changed', function(){
            // redraw des markers
            var origine = this.getCenter(),
                rayon   = this.getRadius(),
                i, nb   = tabMarkers.length;
            for( i=0; i < nb; i++){
              drawMarker( tabMarkers[i], origine, rayon);
            }
          });
        // evenement double click pour création des markers
        google.maps.event.addListener( oMap, 'dblclick', function(data) {
            // création d'un marqueur
            var oMarker = new google.maps.Marker({
                'position' : data.latLng,
                'map' : this
              });
            // test affichage
            var origine = oCercle.getCenter(),
                rayon   = oCercle.getRadius();
            // redraw le marker
            drawMarker( oMarker, origine, rayon);
            // empile le marker
            tabMarkers.push( oMarker);
          });
      }
      // init lorsque la page est chargee
      google.maps.event.addDomListener(window, 'load', initCarte);
    })();
    </script>
    </head>
    <body>
    <div id="page">
      <div id="header">
        <h1><span>[Google Maps API]</span>Distance entre 2 points ou point dans un rayon de...</h1>
      </div>
      <div class="section">
        <h2>Comment joue t-on ?</h2>
        <p>Double cliquez sur la carte, dans ou hors du cercle, pour créer des markers.</p>
        <p>Si un marker se trouve dans le cercle il sera vert<img src="http://maps.google.com/mapfiles/marker_green.png" alt="marker_green.png">dans le cas contraire il sera rouge<img src="http://maps.google.com/mapfiles/marker.png" alt="marker.png">.</p>
        <p>Ensuite jouez avec le cercle en le déplaçant, en augmentant ou réduisant son rayon.
        Les markers changeront de couleur en fonction du fait qu'ils sont ou non dans le cercle,
        donc en fonction de leur distance au centre du cercle.</p>
      </div>
      <div class="section">
        <h2>L'espace de jeu</h2>
        <div id="div_carte"></div>
        <br>
      </div>
      <div class="section">
        <h2>Explication</h2>
        <p>Pour calculer la distance entre deux points, on utilise simplement la méthode <a href="https://developers.google.com/maps/documentation/javascript/reference#spherical" target="GOOGLE">computeDistanceBetween</a> mise à disposition par la librairie <a href="https://developers.google.com/maps/documentation/javascript/geometry" target="GOOGLE">geometry</a>, qu'il ne faut oublier de charger.</p>
        <p>On passe à la fonction la <code>LatLng</code> du centre du cercle et la <code>LatLng</code> du marker, si la distance est supérieure au rayon du cercle on affecte au marker une icône rouge sinon on lui affecte une icône verte.</p>
        <p>En cas de modification de la position du cercle ou de son diamètre, on recalcule les distances par rapport à ce "nouveau" cercle.</p>
        <p>Dans cet exemple l'utilisation du cercle ne sert qu'à visualiser le résultat en déterminant un point, son centre, et une distance, son rayon.</p>
        <p>On pourrait également décider de rendre, ou non, visible le marker suivant sa distance au centre.</p>
        <br>
      </div>
      <div id="footer">
        <p>Auteur : <a href="http://www.developpez.net/forums/u405341/nosmoking/" target="DVP">NoSmoking</a> pour <a href="http://web.developpez.com/" target="DVP">developpez.com</a></p>
        <p>Les sources issues de cette page sont libres de droits et vous pouvez les utiliser à votre convenance.</p>
      </div>
    </div>
    </body>
    </html>
    Images attachées Images attachées  

Discussions similaires

  1. Calcul de distance entre deux points dans une grille
    Par Yoratheon dans le forum Mathématiques
    Réponses: 3
    Dernier message: 30/10/2016, 21h59
  2. distance entre deux points dans un repere
    Par courageuse dans le forum MATLAB
    Réponses: 3
    Dernier message: 10/12/2011, 15h01
  3. [Google API v3] Calcul de distance entre plusieurs points
    Par akrogames dans le forum APIs Google
    Réponses: 1
    Dernier message: 08/04/2010, 17h35
  4. Distance entre 2 points dans un repère 3D
    Par hush dans le forum Mathématiques
    Réponses: 8
    Dernier message: 28/10/2009, 17h47
  5. mesure de distance entre 2 points dans une figure
    Par sdecorme dans le forum MATLAB
    Réponses: 4
    Dernier message: 04/07/2008, 19h51

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