I'm a newbie in AngularJS and I'm trying to use the goToUserLocation() function from the userLocation directive in the getMyPosition() function in the MapController. The reason I want to do this is that once the user clicks a button I want to take his location, zoom in to 40 and place it at the center of the map. Can someone please help me with this? Thank you. Here are the directive, the controller and a service that the directive uses:
(function ()
{
'use strict';
angular
.module('app.map')
.directive('userLocation', userLocation);
function userLocation(geolocation)
{
return {
restrict: "A",
link: function(scope, element, attrs){
var ctrl = scope['vm'];
var goToUserLocation = UserLocationFactory();
goToUserLocation(ctrl, geolocation, ctrl.defaultLocation );
}
};
}
//Factory to build goToUserLocation function with callbacks configuration
function UserLocationFactory(cantGetLocation, notSupportedBrowser)
{
return goToUserLocation;
//function to make the map go to user location
function goToUserLocation(vm, geolocation, defaultLocation)
{
resolveErrorCallbacks();
geolocation.goToUserLocation(success, cantGetLocation, notSupportedBrowser);
function success(position)
{
var location = {
lat: position.lat,
lng: position.lng,
zoom: 15
};
configureLatlng(location);
}
function configureLatlng(location)
{
vm.map = {
center: location
};
}
function resolveErrorCallbacks(){
if( !cantGetLocation || !( typeof cantGetLocation === "function" ) )
{
cantGetLocation = function()
{
configureLatlng(defaultLocation);
};
}
if( !notSupportedBrowser || !( typeof notSupportedBrowser === "function" ) )
{
notSupportedBrowser = function()
{
configureLatlng(defaultLocation);
};
}
}
}
}
})();
Here is the controller:
(function ()
{
'use strict';
angular
.module('app.map')
.controller('MapController', MapController);
/** @ngInject */
function MapController($mdDialog, $mdSidenav, $animate, $timeout, $scope, $document, MapData,
leafletData, leafletMapEvents, api, prototypes, $window, appEnvService, geolocation) {
var vm = this;
vm.getMyPosition = getMyPosition;
function getMyPosition(){
console.log("Here is your location.");
}
Here is a service that the directive us:
(function() {
'use strict';
angular
.module('app.map')
.service('geolocation', geolocation);
function geolocation() {
/*
success - called when user location is successfully found
cantGetLocation - called when the geolocation browser api find an error in retrieving user location
notSupportedBrowser - callend when browser dont have support
*/
this.goToUserLocation = function(success, cantGetLocation, notSupportedBrowser)
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(currentPosition, function() {
cantGetLocation();
});
}
else
{
// Browser doesn't support Geolocation
notSupportedBrowser();
}
function currentPosition(position)
{
var pos =
{
lat: position.coords.latitude,
lng: position.coords.longitude
};
success(pos);
}
};
}
})();