Search code examples
javascriptangularjsgoogle-mapsionic-frameworkangular-google-maps

Angular-google-maps: How to set current user's position on load map?


I'm using http://angular-google-maps.org/ and IONIC-framework.

I set center manually this way:

.controller('mainCtrl', function($scope) {
        $scope.map = {
          center: {
            latitude: 51.219053,
            longitude: 4.404418
          },
        ...

I'm trying to set user position with Angular-google-maps when map loads.

also I must create new function in config()? bcause I want run it ones.


Solution

  • To set a user's position, you'll first need to know where they are. To do that you'll need to ask them for their location so you can get their latitude and longitude.

    I use this plugin to prompt and get the user's location.

    https://github.com/ionberry/cordova-plugin-geolocation-ios9-fix

    Once you have their latitude and longitude, you can set the center of the map to the user's location. If you choose to show markers, they will then be centered around where the user currently is.

    Getting a user's location with the plugin above:

    var positionOptions = {
        timeout: 10000,
        enableHighAccuracy: true
    };
    
    var getPosition = function() {
    
        var q = $q.defer();
    
        $ionicPlatform.ready().then(
            function() {
                $cordovaGeolocation.getCurrentPosition(positionOptions).then(
                    function(position) {
                        q.resolve(position);
                    }, function(error) {
                        q.reject(error);
                    }
                );
            }
        );
    
        return q.promise;
    };
    

    This will return a location object with latitude and longitude. From there you can pass the user's latitude and longitude to your map config object. The geolocation plugin has great documentation if you need additional details.