One of the functionalities I'm working on involves tracking the user's position. First, I use getCurrentLocation to retrieve the user's location coordinates and then place a marker on the map to indicate their location (the marker variable is set globally). After that, I call the watchPosition function to continuously track any changes in the user's position. This piece of code is specifically created for an Ionic app, but the same concept can be applied to any web application (you can disregard $cordovaGeolocation as it is similar to navigator.geolocation).
var map = null;
var myPosition = null;
$scope.initMap = function(){
var posOptions = {
enableHighAccuracy: false,
timeout: 20000,
};
$cordovaGeolocation.getCurrentPosition(posOptions).then(
function (position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var myLatlng = new google.maps.LatLng(lat, long);
$scope.me = myLatlng;
var mapOptions = {
center: myLatlng,
zoom: 11,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
myPosition = new google.maps.Marker({
map: map,
position: myLatlng,
draggable:false,
icon: "https://i.sstatic.net/orZ4x.png",
});
var circle = new google.maps.Circle({radius: User.getUser().distance*1000, center: myLatlng});
map.fitBounds(circle.getBounds());
$cordovaGeolocation.watchPosition(win);
},
function(err) {
console.log(err);
}
);
}
The callback function for the watchPosition method can be seen below:
var win = function(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var myLatlng = new google.maps.LatLng(lat, long);
if(myPosition==null){
myPosition = new google.maps.Marker({
map: map,
position: myLatlng,
draggable:false,
icon: "https://i.sstatic.net/orZ4x.png",
});
myPosition.setMap(map);
}else{
myPosition.setPosition(myLatlng);
}
map.panTo(myLatlng);
};