The geolocation APIs

A geolocation API is a high-level interface used to locate information. It lets you find out where the user is and keep a track of his/her location when he/she moves. The geolocation API is device-agnostic of the underlying location source and doesn't care how the web browser determines the location. The following are the common sources for the location:

  • GPS
  • The network IP address
  • RFID
  • Wi-Fi
  • The Bluetooth MAC address
  • The GSM/CDMA cell ID
  • User inputs

The API represents location by latitude and longitude coordinates.

Note

The geolocation APIs do not guarantee returning the actual location of the device.

The geolocation API has the following classes:

  • Geolocation: This class is used to determine the location information associated with the hosting device
  • Geoposition: This class is used to store the coordinates and timestamp
  • Coordinates: This class is used to store the location information and speed of the device

Determining the current location

Let's see how we can use the geolocation API to obtain information about the current location:

import 'dart:html';

void main() {
  window.navigator.geolocation.getCurrentPosition()
  .then((Geoposition geoposition) {
   querySelector("#latitude").text = geoposition.coords.latitude
    .toStringAsFixed(6);
   querySelector("#longitude").text = geoposition.coords.longitude
    .toStringAsFixed(6);
}, onError: (PositionError error) {
    print(error.message);  
});
}

We can request the geolocation instance from the navigator property of the window object. The getCurrentPosition method of geolocation returns Geoposition in the Future object. When the Future will be resolved, we will assign the geoposition coordinates to the latitude and longitude HTML fields.

Note

Dartium doesn't support geolocation, so run pub serve and iterate with Chrome web browser.

The website must have permission before use your location information. You can let websites use your location information automatically or obtain a permission request first. This is a common requirement when an API tries to interact with something outside a web context, especially to avoid sharing user-specific information. To see the geolocation information, follow these steps:

  1. Open the Settings option in Chrome and type location in the search field, as shown in the following screenshot:
    Determining the current location
  2. Open the Content settings pop-up dialog by clicking on the button of the same name, scroll down the content, and you'll find the Location settings:
    Determining the current location
  3. Choose the recommended option and open the Geolocation exceptions dialog by clicking on the Manage exceptions button. For now, it will not contain our website, as shown in the following screenshot:
    Determining the current location
  4. Run the geolocation application. The Chrome web browser will ask you for permission to use your location information, as shown in the following screenshot:
    Determining the current location
  5. You can allow or deny location requests for this website. Your choice completes the future permission requests with the value of geoposition. The website is then added to the list of Geolocation exceptions. Open the Geolocation exceptions dialog again to see your website:
    Determining the current location

    Any error that occurs in the geolocation service will be printed:

    Network location provider at 'https://www.googleapis.com/' : Returned error code 400.
  6. We will now run pub serve from the root folder of our project:
    Loading source assets...
    Serving geolocation web on http://localhost:8080
    Build completed successfully
    [web] GET /geolocation.html => geolocation|web/geolocation.html
    [web] GET /geolocation.css => geolocation|web/geolocation.css
    [web] GET /packages/browser/dart.js => browser|lib/dart.js
    [Info from Dart2JS]:
    Compiling geolocation|web/geolocation.dart...
    [Info from Dart2JS]:
    Took 0:00:27.723586 to compile geolocation|web/geolocation.dart.
    Build completed successfully
    [web] GET /geolocation.dart.js => geolocation|web/geolocation.dart.js
    [web] GET /geolocation.dart.js.map => geolocation|web/geolocation.dart.js.map
  7. Then, open the web application in the Chrome web browser to get the following result:
    Determining the current location

Your example will be more interesting if you add Google Maps to show your current position on a real map.

Geolocation on maps

Add the google_maps package to your project and make the following changes to the code:

import 'dart:html';
import 'package:google_maps/google_maps.dart';

void main() {
  final mapOptions = new MapOptions()
  ..zoom = 15
  ..mapTypeId = MapTypeId.ROADMAP;
  final map = new GMap(querySelector("#map_canvas"), mapOptions);
  
  window.navigator.geolocation.getCurrentPosition()
  .then((Geoposition geoposition) {
    Coordinates coords = geoposition.coords;
    querySelector("#latitude").text = coords.latitude
     .toStringAsPrecision(6);
    querySelector("#longitude").text = coords.longitude
     .toStringAsPrecision(6);
    //
    map.center = new LatLng(coords.latitude, coords.longitude);
  }, onError: (PositionError error){
    print(error.message);
  });
}

In mapOptions, we specified the zoom and type of view. Maps can be presented in terms of the satellite, terrain, or hybrid view. Using the Google Maps API is very simple. Just add the div element with the specified ID to your HTML page. Then, execute the pub serve command to compile your code and run the server. When you open the Geolocation page in the Chrome web browser, you will get the following result:

Geolocation on maps

Tracking the present location

Geolocation APIs can monitor the current location of your device using the watchPosition method. With the enableHighAccuracy parameter, the geolocation API starts to use more accurate hardware available on your device. This method returns a stream of geoposition coordinates. You only need to listen to the events to track changes in your current position. The code is as follows:

import 'dart:html';
import 'package:google_maps/google_maps.dart';

void main() {
  final mapOptions = new MapOptions()
  ..zoom = 25
  ..mapTypeId = MapTypeId.ROADMAP;
  final map = new GMap(querySelector("#map_canvas"), mapOptions);
  
  window.navigator.geolocation
  .watchPosition(enableHighAccuracy:true)
   .listen((Geoposition geoposition) {
    Coordinates coords = geoposition.coords;
    map.center = new LatLng(coords.latitude, coords.longitude);
    //
    querySelector("#location_tracker").append(new DivElement()
    ..text = coords.latitude.toStringAsPrecision(6) + " x " + 
      coords.longitude.toStringAsPrecision(6));
  }, onError: (PositionError error){
      print(error.message);
  });
}

When you run the web application, you will receive the following result:

Tracking the present location
..................Content has been hidden....................

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