Trouver l’emplacement le plus proche, par rapport à un autre (adresse ou code postal)

HTML

				
					<script src="https://maps.googleapis.com/maps/api/js?key=VOTRE_CLE_API_ICI&libraries=geometry&region=CA&language=fr"></script> <input id="address" type="text" value="Palo Alto, CA">
<input type="button" value="Search" onclick="codeAddress();">

<div id="map"></div>
<div id="results"></div>
				
			
  • Ligne 1 – Remplacez VOTRE_CLE_API_ICI par votre clé API Google Maps (lire la documentation). Assurez-vous de lui octroyer les bons droits d’utilisation et les bonnes composantes (Maps JavaScript API, Geocoding API et Distance Matrix API) pour ce code;
  • Ligne 1 – Ajoutez &region=CA&language=fr dans l’appel à l’API Google Maps pour afficher la carte et les résultats en français;

CSS

				
					#map
  { height:500px; margin-top:20px; width:100%; }
#results
  { margin-top:20px; }
				
			
  • Ligne 2 – Afin qu’elle soit visible, assurez-vous d’assigner une hauteur (height) à votre carte;

JS

				
					var locations = [
  ["John's Pizza", "400 University Ave, Palo Alto, CA", "37.447038,-122.160575", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
  ["JJs Express", "1000 Santa Cruz Ave, Menlo Park, CA", "37.448638,-122.187176", "http://maps.google.com/mapfiles/ms/icons/green.png"],
  ["John Paul's Pizzeria", "1100 El Camino Real, Belmont, CA", "37.520436,-122.275978", "http://maps.google.com/mapfiles/ms/icons/yellow.png"],
  ["JJs Express", "300 E 4th Ave, San Mateo, CA", "37.564435,-122.322080", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
  ["John's Pizza", "1400 Broadway Ave, Burlingame, CA", "37.584935,-122.366182", "http://maps.google.com/mapfiles/ms/icons/green.png"],
  ["JJs Express", "700 San Bruno Ave, San Bruno, CA", "37.630934,-122.406883", "http://maps.google.com/mapfiles/ms/icons/yellow.png"],
  ["JJs Express", "300 Beach St, San Francisco, CA", "37.807628,-122.413782", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
  ["JJs Express", "1400 Haight St, San Francisco, CA", "37.770129,-122.445082", "http://maps.google.com/mapfiles/ms/icons/green.png"],
  ["JJs Express", "2400 Mission St, San Francisco, CA", "37.758630,-122.419082", "http://maps.google.com/mapfiles/ms/icons/yellow.png"],
  ["JJs Express", "500 Castro St, Mountain View, CA", "37.390040,-122.081573", "http://maps.google.com/mapfiles/ms/icons/blue.png"]
];

var geocoder = null;
var map = null;
var customerMarker = null;
var gMarkers = [];
var closest = [];

function initialize() {

  geocoder = new google.maps.Geocoder();
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 9,
    center: new google.maps.LatLng(52.6699927, -0.7274620),
    streetViewControl: false,
    mapTypeControl: false,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    styles: [{'featureType': 'water', 'elementType': 'geometry', 'stylers': [{'color': '#e9e9e9'},{'lightness': 17}]},{'featureType': 'landscape', 'elementType': 'geometry', 'stylers': [{'color': '#f5f5f5'},{'lightness': 20}]},{'featureType': 'road.highway', 'elementType': 'geometry.fill', 'stylers': [{'color': '#ffffff'},{'lightness': 17}]},{'featureType': 'road.highway', 'elementType': 'geometry.stroke', 'stylers': [{'color': '#ffffff'},{'lightness': 29},{'weight': 0.2}]},{'featureType': 'road.arterial', 'elementType': 'geometry', 'stylers': [{'color': '#ffffff'},{'lightness': 18}]},{'featureType': 'road.local', 'elementType': 'geometry', 'stylers': [{'color': '#ffffff'},{'lightness': 16}]},{'featureType': 'poi', 'elementType': 'geometry', 'stylers': [{'color': '#f5f5f5'},{'lightness': 21}]},{'featureType': 'poi.park', 'elementType': 'geometry', 'stylers': [{'color': '#dedede'},{'lightness': 21}]},{'elementType': 'labels.text.stroke', 'stylers': [{'visibility': 'on'},{'color': '#ffffff'},{'lightness': 16}]},{'elementType': 'labels.text.fill', 'stylers': [{'saturation': 36},{'color': '#333333'},{'lightness': 40}]},{'elementType': 'labels.icon', 'stylers': [{'visibility': 'off'}]},{'featureType': 'transit', 'elementType': 'geometry', 'stylers': [{'color': '#f2f2f2'},{'lightness': 19}]},{'featureType': 'administrative', 'elementType': 'geometry.fill', 'stylers': [{'color': '#fefefe'},{'lightness': 20}]},{'featureType': 'administrative', 'elementType': 'geometry.stroke', 'stylers': [{'color': '#fefefe'},{'lightness': 17},{'weight': 1.2}]}]
  });

  var infoWindow = new google.maps.InfoWindow();
  var marker, i;
  var bounds = new google.maps.LatLngBounds();

  for( var i = 0; i < locations.length; i++ ) {

    var coordStr = locations[i][2];
    var coords = coordStr.split(',');
    var pt = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));

    bounds.extend(pt);

    marker = new google.maps.Marker({
      position: pt,
      map: map,
      icon: locations[i][3],
      address: locations[i][1],
      title: locations[i][0],
      html: locations[i][0] + '<br>' + locations[i][1]
    });

    gMarkers.push(marker);

    google.maps.event.addListener(marker, 'click', (function(marker, i) {
      return function() {
        infoWindow.setContent(marker.html);
        infoWindow.open(map, marker);
        map.panTo(this.getPosition());
        map.setZoom(4);
      }
    }) (marker, i));

  }

  map.fitBounds(bounds);

}

function codeAddress() {

  var numberOfResults = locations.length;
  var address = document.getElementById('address').value;

  geocoder.geocode({'address': address}, function(results, status) {

    if( status == google.maps.GeocoderStatus.OK ) {

      map.setCenter(results[0].geometry.location);

      if( customerMarker ) customerMarker.setMap(null);

      customerMarker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location,
        icon: 'http://maps.google.com/mapfiles/ms/icons/red.png'
      });

      closest = findClosestN(results[0].geometry.location, numberOfResults);
      closest = closest.splice(0, numberOfResults);

      google.maps.event.trigger(closest[0], 'click');

      calculateDistances(results[0].geometry.location, closest, numberOfResults);

    } else {

      alert('Geocode was not successful for the following reason: ' + status);

    }

  });

}

function findClosestN(pt, numberOfResults) {

  var closest = [];

  for( var i = 0; i < gMarkers.length; i++ ) {

    gMarkers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt, gMarkers[i].getPosition());
    gMarkers[i].setMap(null);
    closest.push(gMarkers[i]);

  }

  closest.sort(sortByDist);

  return closest;

}

function sortByDist(a, b) {

  return (a.distance - b.distance)

}

function calculateDistances(pt, closest, numberOfResults) {

  var service = new google.maps.DistanceMatrixService();
  var request = {
    origins: [pt],
    destinations: [],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.METRIC,
    avoidHighways: false,
    avoidTolls: false
  };

  for( var i = 0; i < closest.length; i++ ) {

    request.destinations.push(closest[i].getPosition());

  }

  service.getDistanceMatrix(request, function(response, status) {

    if( status != google.maps.DistanceMatrixStatus.OK ) {

      alert('Error: ' + status);

    } else {

      var origins = response.originAddresses;
      var destinations = response.destinationAddresses;
      var outputDiv = document.getElementById('results');
      var results = response.rows[0].elements;

      for( var i = 0; i < closest.length; i++ ) {

        results[i].title = closest[i].title;
        results[i].address = closest[i].address;
        results[i].idx_closestMark = i;

      }

      results.sort(sortByDistDM);

      outputDiv.innerHTML = '';

      for( var i = 0; ((i < numberOfResults) && (i < closest.length)); i++ ) {

        closest[i].setMap(map);
        outputDiv.innerHTML += "<p><a href='javascript:google.maps.event.trigger(closest[" + results[i].idx_closestMark + "], \"click\");'>" + results[i].title + '</a><br>' + results[i].address + '<br>'
          + results[i].distance.text + ' appoximately '
          + results[i].duration.text + '</p>';

      }

    }

  });

}

function sortByDistDM(a,b) {

  return (a.distance.value - b.distance.value);

}

google.maps.event.addDomListener(window, 'load', initialize);
				
			
  • Lignes 2-11 – Liste des emplacements avec les paramètres suivant (dans l’ordre):
    • Paramètre 1: Nom du commerce (pour affichage seulement);
    • Paramètre 2: Adresse du commerce (pour affichage seulement; non utilisée pour le calcul de distance);
    • Paramètre 3: Coordonnées géographiques de l’emplacement (latitude et longitude);
    • Paramètre 4: URL complète de l’icône qui sert de marqueur pour l’emplacement;
  • Lignes 24-29 – Liste des paramètres et affichage de la carte (lire la documentation de l’API Google Maps);
  • Ligne 29 – Styles de la carte (SnazzyMaps en répertorie plusieurs pour vous faciliter la tâche);
  • Lignes 45-50 – Liste des paramètres et ajout des marqueurs sur la carte (selon le tableau d’emplacements);
  •  Lignes 84-86 – Liste des paramètres et ajout d’un marqueur à l’emplacement entré par l’utilisateur (champ de recherche);
  • Lignes 175-178 – Affichage (dans l’ordre) des emplacements selon la distance avec l’emplacement recherché;

Résultat du code

Note: Il se peut que vous ayez à défiler l’encadré ci-dessous pour visualiser l’entièreté du résultat.