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;®ion=CA&language=fr
dans l’appel à l’API Google Maps pour afficher la carte et les résultats en français;
#map
{ height:500px; margin-top:20px; width:100%; }
#results
{ margin-top:20px; }
2
– Afin qu’elle soit visible, assurez-vous d’assigner une hauteur (height
) à votre carte;
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] + '
' + 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 += "" + results[i].title + '
' + results[i].address + '
'
+ results[i].distance.text + ' appoximately '
+ results[i].duration.text + '
';
}
}
});
}
function sortByDistDM(a,b) {
return (a.distance.value - b.distance.value);
}
google.maps.event.addDomListener(window, 'load', initialize);
Note: Il se peut que vous ayez à défiler l’encadré ci-dessous pour visualiser l’entièreté du résultat.
© 2021 VERYA Inc.
Certaines images proviennent de Freepik et Unsplash.
Certaines icônes proviennent de FontAwesome.