Aujourd'hui nous allons développer une petite application en combinant la géolocalisation HTML5 avec Google Maps. Adresse de l'API Google Maps : https://developers.google.com/maps/documentation/javascript/?hl=zh-CN.
Pour appeler Google Maps, vous devez ajouter la référence js
La méthode InitMap consiste à appeler l'API de Google Maps pour initialiser la carte. Elle doit définir l'objet d'options. et utilisez-le lors de l'appel de l'initialisation de la carte.
Copier le codevar options = {
zoom : 4,
center : new google.maps.LatLng(38.6201, -90.2003),
mapTypeId : google. maps.MapTypeId.ROADMAP,
mapTypeControl : true,
mapTypeControlOptions : {
style : google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position : google.maps.ControlPosition.BOTTOM_CENTER
},
panControl : true,
panControlOptions : {
position : google.maps.ControlPosition.TOP_RIGHT
},
zoomControl : true,
zoomControlOptions : {
style : google.maps .ZoomControlStyle.LARGE,
position : google.maps.ControlPosition.LEFT_CENTER
},
scaleControl : true,
scaleControlOptions : {
position : google.maps.ControlPosition.BOTTOM_LEFT
},
streetViewControl : true,
streetViewControlOptions : {
position : google.maps.ControlPosition.LEFT_TOP
}
}
/* Créer une nouvelle carte pour le application */
map = new google.maps.Map($('#map')[0], options);
}
Les méthodes getLocation et watchLocation obtiennent des informations de positionnement .
Copier le codeif (navigator.geolocation) {
browserSupport = true;
navigator.geolocation.getCurrentPosition(plotLocation, reportProblem, { timeout: 45000 } );
} else {
reportProblem();
}
}
function watchLocation() {
/* Vérifiez si le navigateur prend en charge l'API de géolocalisation du W3C */
if (navigator .geolocation) {
browserSupport = true;
navigator.geolocation.watchPosition(plotLocation, reportProblem, { timeout : 45000 });
} else {
reportProblem(); }
}
Après avoir obtenu avec succès les informations de localisation, appelez la méthode plotLocation pour afficher l'emplacement sur Google Maps.
fonction plotLocation(position) {
tentatives = 0;
var point = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var Marker = new google.maps.Marker({
) position : point
});
marker.setMap(map);
map.setCenter(point);
map.setZoom(15); 🎜>Adresse de téléchargement de la démo :
googleMapGeolocation.rar