Adding geolocation via GPS

Now that we have an even better working map view, let's go ahead and add some basic navigation features to it, namely, the ability to focus the map on our current physical location.

First, let's add a button to the footer toolbar for now. Make sure that the ion-footer-bar tag looks like the following:

<ion-footer-bar class="bar-stable">
  <a ng-click="centerOnUser()" class="button button-icon icon ion-navigate"></a>
</ion-footer-bar>

Your preview should now look like this:

Adding geolocation via GPS

Now, we need to hook into the location capabilities of the native device in order to find the user's current location. Fortunately, this can be done directly through the HTML5 geolocation interface. To see it in action, let's add the following to the controller.js file inside the MapCtrl controller:

$scope.centerOnUser = function () {
  console.log("Centering on user");
  if (!$scope.map) {
    return;
  }

  navigator.geolocation.getCurrentPosition(function (pos) {
    console.log('Got pos', pos);
    $scope.map.setCenter(
      new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
  }, function (error) {
    alert('Unable to get location: ' + error.message);
  });
};

Note what we did here.

We defined the centerOnUser() scoped function. This function is in turn bound to the location button that we just defined in the index.html file.

In this function, we have the navigator.geolocation.getCurrentPosition function, a part of the HTML5 standard, in order to retrieve the current location of the user. This function takes a callback as an argument, which in turn takes a position object, pos, as an argument.

Inside the callback, we use the latitude and longitude value stored in pos in order to recenter the map using the setCenter() method provided by Google Maps.

You can now try out the navigation for yourself in the preview. Clicking on the location button should change the focus of the map to your current location. That's it. We are done!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.27.74